import { Component, OnInit, Input,Output,EventEmitter,ViewContainerRef, ViewChild,OnDestroy} from '@angular/core';
import { Subject } from 'rxjs';
import { Http } from '@global/service/Http';
import { AppNotification } from '@global/service/Notification';
import { NavController, ModalController } from '@ionic/angular';
import { App } from '@global/service/App';
import { ComUtil } from '@global/util/ComUtil';
import { AppEnvironment } from 'src/environments/AppEnvironment';
import { BGYPMobPickupMDViewPage } from '@pages/demo/bgypmob-pickup-mdview/bgypmob-pickup-mdview.page';

@Component({
  selector: 'ctrl-usr-treeview',
  templateUrl: './usr-treeview.html',
  styleUrls: ['./usr-treeview.scss']
})
export class Treeexpbar_tree implements OnInit,OnDestroy {

    /**
     * 名称
     *
     * @type {string}
     * @memberof Treeexpbar_tree
     */
    @Input() public name: string;

    /**
     * 视图通讯对象
     *
     * @type {Subject<ViewState>}
     * @memberof Treeexpbar_tree
     */
    @Input() public viewState: Subject<ViewState>;


    /**
     * 是否为内嵌视图
     *
     * @type {boolean}
     * @memberof Treeexpbar_tree
     */
    @Input() public isembeddedView: boolean;

    /**
     * 是否为模态模式
     *
     * @type {boolean}
     * @memberof Treeexpbar_tree
     */
    @Input() public isModalMode: boolean;

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

    constructor(private $http: Http, private $notification: AppNotification,private $navCtrl:NavController,private $app:App,private $modalCtrl: ModalController) {

    }


    /**
     * 返回
     *
     * @memberof Treeexpbar_tree
     */
    public backView() {
        if (this.isModalMode) {
            let res: any;
            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();
        }
    }


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

    /**
     * 父类型视图类型
     *
     * @type {any}
     * @memberof Treeexpbar_tree
     */
    @Input() public viewtype: string;

    @Output() public selectchangeemit =new EventEmitter();
    @Output() public clickemit =new EventEmitter();
    @Output() public loademit =new EventEmitter();
    @Output() public selectionchangeemit =new EventEmitter(); 

    /**
     * Api地址
     *
     * @type {string}
     * @memberof Treeexpbar_tree
     */
    public url: string = 'mob/ctrl/usrtreeview/';

    /**
     * 是否可选择
     *
     * @type {boolean}
     * @memberof Treeexpbar_tree
     */
    @Input() public $isEnableSelection: boolean = false;

    /**
     * 树节点集合
     *
     * @public
     * @type {Array}
     * @memberof Treeexpbar_tree
     */
    public $treeNodeList:Array<any> = [];

        /**
     * 有子节点的父节点集合
     *
     * @public
     * @memberof Treeexpbar_tree
     */
    public $trunks: Array<any> = [];

    /**
     * 可选择模式下的选中数组
     *
     * @public
     * @memberof Treeexpbar_tree
     */
    @Input()  public selectedArray:Array<any> =[];

    /**
     * 叶子节点集合
     *
     * @public
     * @memberof Treeexpbar_tree
     */
    public $leafy: Array<any> = [];

    /**
     * 树的数据(树导航)
     *
     * @type {string}
     * @memberof Treeexpbar_tree
     */
    public treedata:Array<any> = [];

    public getDatas(){
        return this.$leafy;
    }

    public getData(){
        return this.$leafy[0];
    }

    ngOnInit() {
        if (this.viewState) {
            this.viewState.subscribe(({ tag, action, data }) => {
                if (!Object.is(tag, this.name)) {
                    return;
                }
                if (Object.is(action, 'load')) {
                    this.load(data);
                }                
            });
        }
        this.initNavViewMap();
    }

    ngOnDestroy(): void {}

    /**
     * 加载数据
     *
     * @public
     * @memberof Treeexpbar_tree
     */
    public load(data:any):Promise<any>{
        return new Promise((resolve, reject) => {
        const param: any = {
            srfnodeid: data && data.id ? data.id : encodeURI('#'),
        };
        Object.assign(param, this.viewdata);
        this.$http.get1(this.url+"getnodes",param).then((res) => {
            if (!res) {
                this.$notification.error("错误，加载数据失败！");
                return;
            }
            if (res) {
                if(Object.is(this.viewtype,'TREEEXPBAR')){
                    let data = JSON.parse(JSON.stringify(res));
                    this.treedata =data;
                    resolve(data);
                    this.loademit.emit(this.formatTreeData(data[0]));
                }else{
                    this.$leafy = [];
                    this.$trunks = [];
                    resolve(res);
                    let data = JSON.parse(JSON.stringify(res));
                    if (data.length > 0) {
                        data.forEach((element) => {
                            if (element.leaf) {
                                if(this.$isEnableSelection){
                                    Object.assign(element,{isChecked:false});
                                    this.$leafy.push(element);
                                }else{
                                    this.$leafy.push(element);
                                }
                            } else {
                                this.$trunks.push(element);
                            }
                        });
                        let emitdata ={};
                        Object.assign(emitdata,{trunks:this.$trunks,leafy:this.$leafy});
                        this.loademit.emit(emitdata);
                    }
                    if (this.selectedArray.length > 0) {
                        this.selectedArray.forEach((item: any) => {
                            this.$leafy.forEach((singleLeafy: any) => {
                                if (Object.is(item.id, singleLeafy.id)) {
                                    singleLeafy.isChecked = true;
                                }
                            })
                        })
                    }                    
                }
                
            }
        });
        });
    }

    /**
     * 面包屑node点击事件
     *
     * @public
     * @memberof Treeexpbar_tree
     */
    public needTreeChange(item?: any, index?: number) {
        let opt = { ...item };
        Object.assign(opt, this.viewdata);
        this.load(opt).then((res) => {
            if (!item) {
                this.$treeNodeList = [];
            } else {
                this.$treeNodeList = this.$treeNodeList.splice(0, index + 1);
            }
        });
    }

    /**
     * 非叶子节点点击事件
     *
     * @public
     * @memberof Treeexpbar_tree
     */
    public checkboxChange(item: any) {
        let opt = { ...item };
        Object.assign(opt, this.viewdata);
        let emitdata = {};
        Object.assign(emitdata, { isleaf: false, data: item });
        this.clickemit.emit(emitdata);
        this.load(opt).then((res) => {
            if (this.$treeNodeList.length > 0) {
                let curIndex = this.$treeNodeList.findIndex((value, index, arr) => {
                    return value.srfkey = item.srfkey;
                });
                if (curIndex === -1) {
                    this.$treeNodeList.push(item);
                }
            } else {
                this.$treeNodeList.push(item);
            }
        }).catch((error) => {
            console.error('加载数据失败');
        });
    }

    /**
     * 叶子节点编辑
     *
     * @public
     * @memberof Treeexpbar_tree
     */
    public async clickedit(item: any) {
        if(item.id && item.id.startsWith('yplx')){
        const modal = await this.$modalCtrl.create({  
            component: BGYPMobPickupMDViewPage,
            componentProps: { viewdata: { 'srfkey': item.srfkey, 'parentdata': this.viewdata }, isModalMode: true }
        });
        await modal.present();
        const result = await modal.onWillDismiss();
        if (Object.is(result.data.ret, 'OK')) {
            let opt = { ...this.$treeNodeList[this.$treeNodeList.length - 1] };
            Object.assign(opt, this.viewdata);
            let emitdata ={};
            Object.assign(emitdata,{isleaf:true,data:item});
            this.clickemit.emit(emitdata);
            this.load(opt);
        }
       }
    }

    /**
     * 可选择模式下的叶子节点点击
     *
     * @public
     * @memberof Treeexpbar_tree
     */    
    public selectChange(item:any){
        let index = -1;
        if (this.selectedArray.length > 0) {
            this.selectedArray.forEach((curvalue, i) => {
                if (Object.is(item.id, curvalue.id)) {
                    index = i;
                }
            });
        }
        if (item.isChecked) {
            if (index === -1) {
                this.selectedArray.push(item);
            }
        } else {
            if (index !== -1) {
                this.selectedArray.splice(index, 1);
            }
        }
        this.selectchangeemit.emit(this.selectedArray);        
    }

    /**
     * 可选择模式下的tag删除
     *
     * @public
     * @memberof Treeexpbar_tree
     */ 
    public removeItem(index:any,value:any){
       let i = -1;
        if (this.$leafy.length > 0) {
            this.$leafy.forEach((curvalue, j) => {
                if (Object.is(value.id, curvalue.id)) {
                    i = j;
                }
            });
        }
        if (i !== -1) {
            this.$leafy[i].isChecked = false;
        }
        this.selectedArray.splice(index, 1);
        this.selectchangeemit.emit(this.selectedArray);
    }

    /**
     * 数据选中事件(树导航部件下)
     *
     * @public
     * @memberof Treeexpbar_tree
     */
    public slectedChange(data:any){
        this.selectionchangeemit.emit(this.formatTreeData(data));
    }

    /**
     * 导航参数Map
     *
     * @public
     * @memberof Treeexpbar_tree
     */    
    public navViewParamMap = new Map();

    /**
     * 初始化导航参数Map
     *
     * @public
     * @memberof Treeexpbar_tree
     */ 
    public initNavViewMap(){
        this.navViewParamMap.set('yplx','{"n_yplx_eq":"%srfkey%"}');
    }

    /**
     * 格式化树数据，处理导航参数
     *
     * @public
     * @memberof Treeexpbar_tree
     */
    public formatTreeData(data:any){
        if(this.navViewParamMap.size >0){   
            let tempParam =JSON.parse(this.navViewParamMap.get(data.srfnodetype));
            let keys =  Object.keys(tempParam);
            if(keys.length>0){
                let tempFlag = false;
                keys.forEach((item:any) =>{
                    let itemValue = tempParam[item];
                    if(itemValue && itemValue.startsWith('%') && itemValue.endsWith('%')){
                        let tempKey = itemValue.substring(1, itemValue.length - 1);
                        tempParam[item]=data[tempKey];
                        tempFlag = true;
                    }
                });
                if(tempFlag){
                    Object.assign(data,{param:tempParam});
                }
            }
        }
        return data;
    }


}