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

import MobWFEditView3Engine from 'src/engine/view/mob-wfedit-view3-engine';
import { DRTab } from '@widget/qj/default-drtab/default-drtab';
import { Quicktoolbar } from '@widget/qj/mob-wfedit-view3quicktoolbar-toolbar/mob-wfedit-view3quicktoolbar-toolbar';
import { EditForm } from '@widget/qj/mob-form-form/mob-form-form';
import { Righttoolbar } from '@widget/qj/mob-wfedit-view3righttoolbar-toolbar/mob-wfedit-view3righttoolbar-toolbar';

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

    /**
     * 子组件DRTab
     *
     * @public
     * @type {Subject}
     * @memberof QJMobWFEditView3
     */
    @ViewChild(DRTab)
    private drtab: DRTab;

    /**
     * 子组件Quicktoolbar
     *
     * @public
     * @type {Subject}
     * @memberof QJMobWFEditView3
     */
    @ViewChild(Quicktoolbar)
    private quicktoolbar: Quicktoolbar;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

        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 QJMobWFEditView3
    */
    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);
                }
        });
    }
       /**
    * 保存并关闭
    *
    * @param {*} [arg={}]
    * @param {*} [params]
    * @memberof QJMobWFEditView3
    */
    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();
        });
    }
        /**
    * 帮助
    *
    * @param {*} [arg={}]
    * @param {*} [params]
    * @memberof QJMobWFEditView3
    */
    public Help(args: any[], params?: any, $event?: any, xData?: any) {
       this.$notification.info('帮助界面行为');
    }

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

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

    /**
     * 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, 'tbitem4')) {
            this.righttoolbar_tbitem4_click($event, '', $event2);
        }
    }


    /**
     * 部件逻辑事件
     *
     * @param {*} [params={}]
     * @param {*} [tag]
     * @memberof QJMobWFEditView3
     */
    public quicktoolbar_tbitem2_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);
    }
    /**
     * 部件逻辑事件
     *
     * @param {*} [params={}]
     * @param {*} [tag]
     * @memberof QJMobWFEditView3
     */
    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 QJMobWFEditView3
     */
    public righttoolbar_tbitem4_click(params: any = {}, tag?: any, $event?: any) {
        // 参数

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

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

        if(Object.is(data,'tbitem2')){
            let opts={items:[
                            {id:'tbitem4',text:'帮助'}
            ]};
            if(opts.items.length === 0){
                return;
            }
            const tag: string = await this.$app.openActionSheet(opts);
            this.righttoolbar_click({tag:tag});
        }
        
    }

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

    


    /**
     * 权限按钮数据
     *
     * @memberof QJMobWFEditView3
     */ 
   public actionBtns: Array<any> =[];

    /**
     * 加载权限按钮
     *
     * @memberof QJMobWFEditView3
     */
    public loadWFLinks(): void {
        let _this:any = this;
        const url = 'mob/demo/qj/wflinks';
        const arg: any = {};
        if (_this.engine && _this.engine.viewdata && _this.engine.viewdata.srfkey) {
            Object.assign(arg, { srfkey: _this.engine.viewdata.srfkey });
        }
        if (!arg.srfkey || Object.is(arg.srfkey, '')) {
            return;
        }
        const get: Promise<any> = this.$http.get1(url, arg);
        get.then((response: any) => {
            if (!response) {
                return;
            }
           this.actionBtns = response;
        }).catch((response: any) => {
            console.log(response);
        });
    }

    /**
     * 工作流动态按钮 点击事件
     *
     * @param {*} item
     * @param {*} $event
     * @memberof QJMobWFEditView3
     */
    public wflink_click(item: any, $event: any): void {
        if (Object.is(item.type, 'FRONT')) {
            this.wflink_front(item, $event);
        } else if (Object.is(item.type, 'BACKEND')) {
            this.wflink_backend(item, $event);
        }
    }

    /**
     *  前台界面行为
     *
     * @param {*} item
     * @param {*} $event
     * @memberof QJMobWFEditView3
     */
    public async wflink_front(item: any, $event: any) {
        if (!item.mobpage || Object.is(item.mobpage, '')) {
            return;
        }
        const mobpage: any = {};
        try {
            Object.assign(mobpage, JSON.parse(item.mobpage));
        } catch (error) {
        }
        if (Object.keys(mobpage).length === 0) {
            return;
        }
        const arg: any = { srfparentdata: {} };
        const _this: any = this;
        if (_this.srfparentdata) {
            Object.assign(arg.srfparentdata, _this.srfparentdata);
        }
        if (_this.engine && _this.engine.viewdata && _this.engine.viewdata.srfkey) {
            Object.assign(arg, { srfkey: _this.engine.viewdata.srfkey });
        }
        if (!arg.srfkey || Object.is(arg.srfkey, '')) {
            return;
        }
        Object.assign(arg,{item:item});
        //打开模态
        const modal = await this.$modalCtrl.create({
            component: this.RefViewMap.get(mobpage.viewname),
            componentProps: {
                viewdata: arg, isModalMode: true
            }
        });
        await modal.present();
        const result = await modal.onWillDismiss();
        if (Object.is(result.data.ret, "OK")) {
            this.$navCtrl.back();
        }
    }

    /**
     * 后台界面行为
     *
     * @param {*} item
     * @param {*} $event
     * @param {*} [data]
     * @memberof QJMobWFEditView3
     */
    public wflink_backend(item: any, $event: any, data?: any): void {
        this.wf_Step(item, $event, data).then((response: any) => {
            if (response && response.ret !== "0") {
                if (response.errorInfo) {
                    this.$notification.error('错误'+response.errorInfo);
                }
                return;
            }
            this.$notification.success(item.name + '操作成功');
            this.backView();
        }).catch((response: any) => {
            if (response && response.status === 401) {
                return;
            }
            this.$notification.error('错误'+ response.errorMessage);
        });
    }

    /**
     * 工作流步骤
     *
     * @private
     * @param {*} item
     * @param {*} $event
     * @param {*} [data]
     * @returns {Promise<any>}
     * @memberof QJMobWFEditView3
     */
    private async wf_Step(item: any, $event: any, data?: any): Promise<any> {
        let _this:any = this;
        const arg: any = { args: {} };
        if (data) {
            Object.assign(arg, data);
        }
        if (_this.engine && _this.engine.viewdata && _this.engine.viewdata.srfkey) {
            Object.assign(arg, { srfkey: _this.engine.viewdata.srfkey });
        }
        if (!arg.srfkey || Object.is(arg.srfkey, '')) {
            return;
        }
        Object.assign(arg, { link: item.id });
        if (!arg.link || Object.is(arg.link, '')) {
            return;
        }

        const url: string = 'mob/demo/qj/wflink';
        const post: Promise<any> = this.$http.post(url, arg);
        return post;
    }

    /**
     * 实例化对象
     *
     * @memberof QJMobWFEditView3
     */
    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 QJMobWFEditView3
     */
    public ngOnInit() {
       
    }

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

    public currentTabPage: string = "";

    public ctrlDatasChange($event: any) {
        if (Object.is($event.type, 'drtab')) {
            this.currentTabPage = $event.value;
        }
    }
}


