import { Component, OnInit,AfterViewInit,Output,Input,EventEmitter,ViewChild,ElementRef } from '@angular/core';
import { Subject,Unsubscribable } from 'rxjs';
import { ActivatedRoute } from '@angular/router';
import { NavController,ModalController } from '@ionic/angular';
import { AppNotification } from '@global/service/Notification';
import { App } from '@global/service/App';
import { Http } from '@global/service/Http';
import { ComUtil } from '@global/util/ComUtil';
import { AppEnvironment } from 'src/environments/AppEnvironment';


import MobMDViewEngine from 'src/engine/view/mob-mdview-engine';
import { Mdctrl } from '@widget/wfwork-list/usr-mobmdctrl/usr-mobmdctrl';
import { Righttoolbar } from '@widget/wfwork-list/mob-mdviewrighttoolbar-toolbar/mob-mdviewrighttoolbar-toolbar';

@Component({
  selector: 'view-wfwork-list-mob-mdview',
  templateUrl: './wfwork-list-mob-mdview.page.html',
  styleUrls: ['./wfwork-list-mob-mdview.page.scss']
})
export class WFWorkListMobMDViewPage implements OnInit,AfterViewInit {

    /**
     * 子组件Mdctrl
     *
     * @public
     * @type {Subject}
     * @memberof WFWorkListMobMDView
     */
    @ViewChild(Mdctrl)
    private mdctrl: Mdctrl;

    /**
     * 子组件Righttoolbar
     *
     * @public
     * @type {Subject}
     * @memberof WFWorkListMobMDView
     */
    @ViewChild(Righttoolbar)
    private righttoolbar: Righttoolbar;

    /**
     * 视图订阅对象
     *
     * @public
     * @type {Subject}
     * @memberof WFWorkListMobMDView
     */
    public viewState: Subject<ViewState> = new Subject();

    /**
     * 路由传递参数
     *
     * @public
     * @type {void}
     * @memberof WFWorkListMobMDView
     */
    public $route ={};

    /**
     * 当前视图激活数据
     *
     * @public
     * @type {void}
     * @memberof WFWorkListMobMDView
     */
    public $activeData:Array<any> =[];

    /**
     * 是否为模态框弹出
     *
     * @memberof WFWorkListMobMDView
     */
    @Input() isModalMode:boolean =false;

    /**
     * 是否嵌入分页导航视图
     *
     * @memberof TestEntity2MobPickupView
     */
    @Input() isTabexp:boolean =false;

    /**
     * 视图值变化事件
     *
     * @public
     * @type {EventEmitter}
     * @memberof WFWorkListMobMDView
     */    
    @Output() public viewdataschange =new EventEmitter();

    /**
     * 视图参数
     *
     * @public
     * @type {Subject}
     * @memberof WFWorkListMobMDView
     */
    @Input() public viewdata:any;

    /**
     * 父数据对象
     *
     * @protected
     * @type {*}
     * @memberof WFWorkListMobMDView
     */
    protected srfparentdata: any = {};

    /**
     * 是否为内敛视图
     *
     * @public
     * @type {EventEmitter}
     * @memberof WFWorkListMobMDView
     */ 
    @Input() public isembeddedView:boolean =false;

    /**
     * 视图值加载完成事件
     *
     * @public
     * @type {EventEmitter}
     * @memberof WFWorkListMobMDView
     */ 
    @Output() public viewload =new EventEmitter();

    /**
     * 视图的关联试图Map
     *
     * @public
     * @type {Map}
     * @memberof WFWorkListMobMDView
     */
    public RefViewMap =new Map();

    /**
     * 视图引擎
     *
     * @private
     * @type {Engine}
     * @memberof WFWorkListMobMDView
     */
    private engine: MobMDViewEngine = new MobMDViewEngine();

    /**
     * 引擎初始化
     *
     * @private
     * @memberof WFWorkListMobMDView
     */
    private engineInit(): void {
        this.engine.init({
            view: this,
            opendata: (params: any) => {
                this.opendata(params);
            },
            mdctrl: this.mdctrl,
            newdata: (params: any) => {
                this.newdata(params);
            },
        });
    }


     /**
     * angular生命周期(在ngOnInit之后)
     *
     * @memberof WFWorkListMobMDView
     */
    public ngAfterViewInit(){
        this.engineInit();
        
        this.registerRefView();
    }

        /**
    * 新建
    *
    * @param {*} [arg={}]
    * @param {*} [params]
    * @memberof WFWorkListMobMDView
    */
    public New(args: any[], params?: any, $event?: any, xData?: any) {
         const _this: any = this;
        if (_this.newdata && _this.newdata instanceof Function) {
            const data: any = {};
            if (_this.srfparentdata) {
                Object.assign(data, _this.srfparentdata);
            }
            _this.newdata([{ ...data }], params, $event, xData);
        } else {
            this.$notification.error('错误,视图处理逻辑不存在，请添加!');
        }
    }

    /**
     * mdctrl 部件 load 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof TestEntityEditView
     */
    public mdctrl_load($event: any, $event2?: any) {
        this.engine.onCtrlEvent('mdctrl', 'load', $event);
    }

    /**
     * mdctrl 部件 click 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof TestEntityEditView
     */
    public mdctrl_click($event: any, $event2?: any) {
        this.engine.onCtrlEvent('mdctrl', 'click', $event);
    }

    /**
     * righttoolbar 部件 click 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof TestEntityEditView
     */
    public righttoolbar_click($event: any, $event2?: any) {
        if (Object.is($event.tag, 'tbitem1')) {
            this.righttoolbar_tbitem1_click($event, '', $event2);
        }
    }


    /**
     * 部件逻辑事件
     *
     * @param {*} [params={}]
     * @param {*} [tag]
     * @memberof WFWorkListMobMDView
     */
    public righttoolbar_tbitem1_click(params: any = {}, tag?: any, $event?: any) {
        // 参数

        // 取数
        let datas: any[] = [];
        let xData: any = null;
        const paramJO = {};
        xData = this.mdctrl;
        datas = [...xData.getDatas()];
        // 界面行为
        this.New(datas, paramJO,  $event, xData);
    }
    
    /**
     * 打开新建数据视图
     *
     * @param {*} [params={}]
     * @memberof WFWorkListMobMDView
     */
    public async newdata(params: any = {}) {
    }

    
    /**
     * 打开编辑数据视图
     *
     * @param {*} [params={}]
     * @memberof WFWorkListMobMDView
     */
    public async opendata(params: any = {}) {
         const data: any = { srfkey: params.srfkey, srfsourcekey: params.srfsourcekey };
        const url: string = 'mob/demo/wfworklist/redirectview/getmodel';
        this.$http.get1(url, data).then( async (response: any) => {
            if (!response) {
                this.$notification.error('错误,请求异常');
            }
            const result = response;
            if (!result) {
                return;
            }
            if(result.viewparams){
                Object.assign(params,result.viewparams);
            }
            const _this: any = this;
            if (_this.srfparentdata) {
                if (Object.is(result.openmode, 'INDEXVIEWTAB') || Object.is(result.openmode, '')) {
                    Object.assign(data, _this.srfparentdata);
                } else {
                    Object.assign(data, { srfparentdata: _this.srfparentdata });
                }
            }

            if (result.viewparams && Object.keys(result.viewparams)) {
                Object.assign(data, result.viewparams);
            }

            if (Object.is(result.openmode, 'POPUPAPP') && result.url && !Object.is(result.url, '')) {
                window.open(result.url, '_blank');
            } else if (Object.is(result.openmode, 'POPUPMODAL')) {
                if(this.RefViewMap.get(result.viewname)){
                    const modal = await this.$modalCtrl.create({
                    component:this.RefViewMap.get(result.viewname),
                    componentProps: { viewdata: {'srfkey':params.srfkey,'parentdata':this.viewdata},isModalMode:true }
                });
                await modal.present();
                const result1 = await modal.onWillDismiss();
                if(Object.is(result1.data.ret,'OK')){
                    this.viewState.next({tag:'mdctrl', action:'load', data:this.viewdata?JSON.parse(this.viewdata):{}});
                }
                }else{
                    console.info("重定向视图未配置关联视图无法以模态形式打开，请配置重定向关联视图");
                }
            } else{
                if(this.isembeddedView){
                    if(this.RefViewMap.get(result.viewname)){
                        const modal = await this.$modalCtrl.create({
                        component:this.RefViewMap.get(result.viewname),
                        componentProps: { viewdata: {'srfkey':params.srfkey,'parentdata':this.viewdata},isModalMode:true }
                    });
                    await modal.present();
                    const result1 = await modal.onWillDismiss();
                    if(Object.is(result1.data.ret,'OK')){
                        this.viewState.next({tag:'mdctrl', action:'load', data:this.viewdata?JSON.parse(this.viewdata):{}});
                    }
                    }else{
                        console.info("内嵌重定向视图未配置关联视图无法打开，请配置重定向关联视图");
                    }
                }else{
                    const viewpath = result.viewmodule.toLowerCase()+"_"+result.viewname.toLowerCase();
                    // const viewpath = result.url.toLowerCase();
                    this.$navCtrl.navigateForward([viewpath],{queryParams:{'srfkey':params.srfkey,'parentdata':this.viewdata}});
                }
            }
        }).catch((response: any) => {
            if (!response) {
                this.$notification.error('错误,系统异常！');
                return;
            }
            const _data = response;
            this.$notification.error(_data.title+","+_data.message);
        })
    }


    /**
     * 返回
     *
     * @memberof WFWorkListMobMDView
     */
    public backView() {
        let res:any;
        if(this.isModalMode){
            if(this.$activeData && this.$activeData.length >0){
                res = { ret: 'OK', result:this.$activeData };
            }else{
                res = { ret: 'NO', result:[] };
            }
            this.$modalCtrl.dismiss(res, 'close');
        }else{
            this.$navCtrl.back();
            if(this.$activeData && this.$activeData.length >0){
                res = { ret: 'OK', result:this.$activeData };
            }else{
                res = { ret: 'NO', result:[] };
            }
            this.$app.closeCallback(res);
        }
    }

    /**
     * 嵌入视图点击更多
     *
     * @public
     * @memberof WFWorkListMobMDView
     */
    public async click_more(){
        let leftopts:Array<any> =[
    ];
        let rightopts:Array<any> =[
        {text:'新建',id:'righttoolbar_tbitem1'},
    ];
        let opts:Array<any>=leftopts.concat(rightopts);
        const result: string = await this.$app.openActionSheet({items:opts});
        let _this =this;
        if(result.startsWith('righttoolbar')){
            if(_this && _this.righttoolbar_click && _this.righttoolbar_click instanceof Function){
                let firstIndex = result.indexOf('_');
                _this.righttoolbar_click({tag:result.substring(firstIndex + 1)});
            }
        }
    }

    /**
     * 点击toolbar的操作组事件
     *
     * @public
     * @memberof WFWorkListMobMDView
     */
    public  async openActionSheet(data:any){

        
    }

    /**
     * 注册关联视图
     *
     * @public
     * @memberof WFWorkListMobMDView
     */    
    public registerRefView(){
    }   

    
    /**
     * 实例化对象
     *
     * @memberof WFWorkListMobMDView
     */
    constructor(public $http:Http,public $navCtrl: NavController, public $notification: AppNotification, public $activatedRoute: ActivatedRoute,public $modalCtrl:ModalController,public $app:App) {
        this.$activatedRoute.queryParams.subscribe(params => {
        this.$route ="";
        if(params){
            this.$route =JSON.stringify(params);
        }
         this.engineInit();
        })
    }

    /**
     * angular生命周期(组件初始化)
     *
     * @memberof WFWorkListMobMDView
     */
    public ngOnInit() {
       
    }

    /**
     * 视图抛出值变化事件
     *
     * @public
     * @memberof WFWorkListMobMDView
     */
    public viewDataChanges($event:any){
        this.viewdataschange.emit($event);
    }

    /**
     * 快速搜索
     *
     * @public
     * @memberof WFWorkListMobMDView
     */
    public onQuickSearchValueChange($event:any){
        this.viewState.next({tag:'mdctrl',action:'quicksearch',data:$event.detail.value});
    }
}


