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 EditViewEngine from 'src/engine/view/edit-view-engine';
import { EditForm } from '@widget/xm/mob-form-form/mob-form-form';
import { Righttoolbar } from '@widget/xm/mob-edit-viewrighttoolbar-toolbar/mob-edit-viewrighttoolbar-toolbar';

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

       /**
    * 保存并关闭
    *
    * @param {*} [arg={}]
    * @param {*} [params]
    * @memberof XMMobEditView
    */
    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 XMMobEditView
    */
    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 {
                        _this.$activeData = [{ ...response }];
                        _this.startWorkFlow(response).then((res:any) =>{
                            if(!res){
                                return;
                            }else{
                                _this.backView();
                                return;
                            }
                        });
                    }
                });
            }
            return;
        }
        xData.save(args[0]).then((response: any) => {
            if (!response) {
                return ;
            }
            if (_this.viewdata) {
                _this.viewdataschange.emit([{ ...response }]);
            }
            _this.$activeData =[{ ...response }];
            xData.startWorkFlow(response).then((res:any) =>{
                if(!res){
                    return;
                }else{
                    _this.backView();
                    return;
                }
            });
        });
    }

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


    /**
     * 部件逻辑事件
     *
     * @param {*} [params={}]
     * @param {*} [tag]
     * @memberof XMMobEditView
     */
    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 XMMobEditView
     */
    public righttoolbar_deuiaction1_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 XMMobEditView
     */
    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 XMMobEditView
     */
    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 XMMobEditView
     */
    public  async openActionSheet(data:any){

        
    }

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

    


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


    /**
     * 实例化对象
     *
     * @memberof XMMobEditView
     */
    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 XMMobEditView
     */
    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 XMMobEditView
     */
    public editBackView() {
        if (this.form.$data.ismodify === true) {
            this.$notification.confirm('表单数据已经修改，确定要关闭？').then((res) => {
                if (res) {
                    this.backView();
                }
            })
        } else {
            this.backView();
        }
    }

}