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 MobWFEditViewEngine from 'src/engine/view/mob-wfedit-view-engine';
import { Quicktoolbar } from '@widget/qj/qjsp-d-mob-wfedit-viewquicktoolbar-toolbar/qjsp-d-mob-wfedit-viewquicktoolbar-toolbar';
import { EditForm } from '@widget/qj/main-form/main-form';
import { Righttoolbar } from '@widget/qj/qjsp-d-mob-wfedit-viewrighttoolbar-toolbar/qjsp-d-mob-wfedit-viewrighttoolbar-toolbar';

@Component({
  selector: 'view-qjqjsp-d-mob-wfedit-view',
  templateUrl: './qjqjsp-d-mob-wfedit-view.page.html',
  styleUrls: ['./qjqjsp-d-mob-wfedit-view.page.scss']
})
export class QJQJSP_D_MobWFEditViewPage implements OnInit,AfterViewInit {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


     /**
     * angular生命周期(在ngOnInit之后)
     *
     * @memberof QJQJSP_D_MobWFEditView
     */
    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 QJQJSP_D_MobWFEditView
    */
    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 QJQJSP_D_MobWFEditView
    */
    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 QJQJSP_D_MobWFEditView
    */
    public Help(args: any[], params?: any, $event?: any, xData?: any) {
       this.$notification.info('帮助界面行为');
    }

    /**
     * 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 QJQJSP_D_MobWFEditView
     */
    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 QJQJSP_D_MobWFEditView
     */
    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 QJQJSP_D_MobWFEditView
     */
    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 QJQJSP_D_MobWFEditView
     */
    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 QJQJSP_D_MobWFEditView
     */
    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 QJQJSP_D_MobWFEditView
     */
    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 QJQJSP_D_MobWFEditView
     */    
    public registerRefView(){
        this.RefViewMap.set('QJMobWFActionView',QJMobWFActionViewPage);
        this.RefViewMap.set('QJMobWFStartView',QJMobWFStartViewPage);
    }   

    


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

    /**
     * 加载权限按钮
     *
     * @memberof QJQJSP_D_MobWFEditView
     */
    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 QJQJSP_D_MobWFEditView
     */
    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 QJQJSP_D_MobWFEditView
     */
    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 QJQJSP_D_MobWFEditView
     */
    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 QJQJSP_D_MobWFEditView
     */
    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 QJQJSP_D_MobWFEditView
     */
    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 QJQJSP_D_MobWFEditView
     */
    public ngOnInit() {
       
    }

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

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


