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 { QJMobWFStartViewPage } from '@pages/demo/qjmob-wfstart-view/qjmob-wfstart-view.page';

import EditViewEngine from 'src/engine/view/edit-view-engine';
import { EditForm } from '@widget/qj/mob-form-form/mob-form-form';
import { Righttoolbar } from '@widget/qj/mob-edit-viewrighttoolbar-toolbar/mob-edit-viewrighttoolbar-toolbar';

@Component({
  selector: 'view-qjmob-edit-view',
  templateUrl: './qjmob-edit-view.page.html',
  styleUrls: ['./qjmob-edit-view.page.scss']
})
export class QJMobEditViewPage implements OnInit,AfterViewInit {

    /**
     * 子组件EditForm
     *
     * @public
     * @type {Subject}
     * @memberof QJMobEditView
     */
    @ViewChild(EditForm)
    private form: EditForm;

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

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

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

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

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

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

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

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

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

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

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

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

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

    /**
     * 引擎初始化
     *
     * @private
     * @memberof QJMobEditView
     */
    private engineInit(): void {
        this.engine.init({
            view: this,
            form: this.form,
        });
    }


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

       /**
    * 保存并关闭
    *
    * @param {*} [arg={}]
    * @param {*} [params]
    * @memberof QJMobEditView
    */
    public SaveAndExit(args: any[], params?: any, $event?: any, xData?: any) {
        const _this: any = this;
        if (!xData || !(xData.save instanceof Function)) {
            if (_this && _this.save instanceof Function) {
                _this.save(args).then((response: any) => {
                    if (!response) {
                        return;
                    } else {
                        _this.$activeData = [{ ...response }];
                        _this.backView();
                        return;
                    }
                });
            }
            return;
        }
        xData.save().then((response: any) => {
            if (!response) {
                return ;
            }
            if (_this.viewdata) {
                _this.viewdataschange.emit([{ ...response }]);
            }
            _this.$activeData =[{ ...response }];
            _this.backView();
        });
    }
        public async QJSPv1_WFStartWizard(args: any[], params?: any, $event?: any, xData?: any) {
        const data: any = { srfparentdata: {} };
        const _this: any = this;
        if (_this.srfparentdata) {
            Object.assign(data.srfparentdata, _this.srfparentdata);
        }
        
        if (args.length === 0) {
            return;
        }
        Object.assign(data, { srfkey: args[0].srfkey,srfwfiatag:'WFStartWizard' });
        //打开模态
        const modal = await this.$modalCtrl.create({
            component:QJMobWFStartViewPage,
            componentProps: { viewdata:data,isModalMode:true
        }});
        await modal.present();
        const result = await modal.onWillDismiss();
        if(Object.is(result.data.ret,"OK")){
            this.$navCtrl.back();
        }
    }
        /**
    * 开始
    *
    * @param {*} [arg={}]
    * @param {*} [params]
    * @memberof QJMobEditView
    */
    public SaveAndStart(args: any[], params?: any, $event?: any, xData?: any) {
        const _this: any = this;
        Object.assign(args[0],{iscancelnotice:true});
        if (!xData || !(xData.save instanceof Function)) {
            if (_this && _this.save instanceof Function) {
                _this.save(args[0]).then((response: any) => {
                    if (!response) {
                        return;
                    } else {
                        if (_this.QJSPv1_WFStartWizard && _this.QJSPv1_WFStartWizard instanceof Function) {
                            _this.QJSPv1_WFStartWizard([{ ...response }], params, $event, xData);
                        }
                    }
                });
            }
            return;
        }
        xData.save(args[0]).then((response: any) => {
            if (!response) {
                return ;
            }
            if (_this.viewdata) {
                _this.viewdataschange.emit([{ ...response }]);
            }
            _this.$activeData =[{ ...response }];
                if (_this.QJSPv1_WFStartWizard && _this.QJSPv1_WFStartWizard instanceof Function) {
                    _this.QJSPv1_WFStartWizard([{ ...response }], params, $event, xData);
                }
        });
    }

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

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

    /**
     * form 部件 load 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof TestEntityEditView
     */
    public form_load($event: any, $event2?: any) {
        this.engine.onCtrlEvent('form', 'load', $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);
        }
        if (Object.is($event.tag, 'deuiaction1_saveandstart')) {
            this.righttoolbar_deuiaction1_saveandstart_click($event, '', $event2);
        }
    }


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

        // 取数
        let datas: any[] = [];
        let xData: any = null;
        const paramJO = {};
        xData = this.form;
        datas = [...xData.getDatas()];
        // 界面行为
        this.SaveAndExit(datas, paramJO,  $event, xData);
    }
    /**
     * 部件逻辑事件
     *
     * @param {*} [params={}]
     * @param {*} [tag]
     * @memberof QJMobEditView
     */
    public righttoolbar_deuiaction1_saveandstart_click(params: any = {}, tag?: any, $event?: any) {
        // 参数

        // 取数
        let datas: any[] = [];
        let xData: any = null;
        const paramJO = {};
        xData = this.form;
        datas = [...xData.getDatas()];
        // 界面行为
        this.SaveAndStart(datas, paramJO,  $event, xData);
    }

    /**
     * 返回
     *
     * @memberof QJMobEditView
     */
    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 QJMobEditView
     */
    public async click_more(){
        let leftopts:Array<any> =[
    ];
        let rightopts:Array<any> =[
        {text:'保存',id:'righttoolbar_tbitem1'},
        {text:'开始',id:'righttoolbar_deuiaction1_saveandstart'},
    ];
        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 QJMobEditView
     */
    public  async openActionSheet(data:any){

        
    }

    /**
     * 注册关联视图
     *
     * @public
     * @memberof QJMobEditView
     */    
    public registerRefView(){
        this.RefViewMap.set('QJMobWFStartView',QJMobWFStartViewPage);
    }   

    


    /**
     * meditview9状态下发变量
     *
     * @memberof QJMobEditView
     */
    @Input() public panelState:Subject<ViewState> = new Subject();


    /**
     * 实例化对象
     *
     * @memberof QJMobEditView
     */
    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);
        }
        })
    }

    /**
     * angular生命周期(组件初始化)
     *
     * @memberof QJMobEditView
     */
    public ngOnInit() {
        if(this.panelState){
            this.panelState.subscribe((res) =>{
            if(Object.is(res.tag,'meditviewpanel')){
                if(Object.is(res.action,'save')){
                    this.viewState.next({ tag:'form', action: 'save', data:res.data });
                }
                if(Object.is(res.action,'remove')){
                    this.viewState.next({ tag:'form', action: 'remove', data:res.data });
                }
            }
        });
        }
    }

    /**
     * 编辑视图返回
     *
     * @memberof QJMobEditView
     */
    public editBackView() {
        if (this.form.$data.ismodify === true) {
            this.$notification.confirm('表单数据已经修改，确定要关闭？').then((res) => {
                if (res) {
                    this.backView();
                }
            })
        } else {
            this.backView();
        }
    }

}