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 { QJUsr2MobEditViewPage } from '@pages/demo/qjusr2-mob-edit-view/qjusr2-mob-edit-view.page';

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    /**
     * 引擎初始化
     *
     * @private
     * @memberof QJMobMDView
     */
    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 QJMobMDView
     */
    public ngAfterViewInit(){
        this.engineInit();
        
        this.registerRefView();
    }

        /**
    * 新建
    *
    * @param {*} [arg={}]
    * @param {*} [params]
    * @memberof QJMobMDView
    */
    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 QJMobMDView
     */
    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 QJMobMDView
     */
    public async newdata(params: any = {}) {
        if(this.isembeddedView){
                const modal = await this.$modalCtrl.create({
                component:QJUsr2MobEditViewPage,
                componentProps: { viewdata: {'srfkey':params.srfkey,'parentdata':this.viewdata},isModalMode:true }
            });
            await modal.present();
            const result = await modal.onWillDismiss();
            if(Object.is(result.data.ret,'OK')){
                this.viewState.next({tag:'mdctrl', action:'load', data:this.viewdata?JSON.parse(this.viewdata):{}});
            }
        }else{
            this.$navCtrl.navigateForward(['demo_qjusr2mobeditview'],{queryParams:{'srfkey':params.srfkey,'parentdata':this.viewdata}});
            this.$app.nextViewCloseCallback((data:any) =>{
                if(Object.is(data.ret,'OK')){
                    this.viewState.next({tag:'mdctrl', action:'load', data:this.viewdata?JSON.parse(this.viewdata):{}});
                }
            });
        }
    }

    
    /**
     * 打开编辑数据视图
     *
     * @param {*} [params={}]
     * @memberof QJMobMDView
     */
    public async opendata(params: any = {}) {
         const data: any = { srfkey: params.srfkey, srfsourcekey: params.srfsourcekey };
        if(this.isembeddedView){
                const modal = await this.$modalCtrl.create({
                component:QJUsr2MobEditViewPage,
                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{
            this.$navCtrl.navigateForward(['demo_qjusr2mobeditview'],{queryParams:{'srfkey':params.srfkey,'parentdata':this.viewdata}});
            this.$app.nextViewCloseCallback((data:any) =>{
                if(Object.is(data.ret,'OK')){
                    this.viewState.next({tag:'mdctrl', action:'load', data:this.viewdata?JSON.parse(this.viewdata):{}});
                }
            });
        }
    }


    /**
     * 返回
     *
     * @memberof QJMobMDView
     */
    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 QJMobMDView
     */
    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 QJMobMDView
     */
    public  async openActionSheet(data:any){

        
    }

    /**
     * 注册关联视图
     *
     * @public
     * @memberof QJMobMDView
     */    
    public registerRefView(){
        this.RefViewMap.set('QJUsr2MobEditView',QJUsr2MobEditViewPage);
    }   

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

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

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


