import { Component, OnInit,EventEmitter, AfterViewInit,Input,Output,OnDestroy,ViewContainerRef, ViewChild} 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 { Mdctrl_itempanel } from '@widget/xm/mob-panel/mob-panel';
import { ComUtil } from '@global/util/ComUtil';
import { AppEnvironment } from 'src/environments/AppEnvironment';


@Component({
  selector: 'ctrl-mob-mobmdctrl',
  templateUrl: './mob-mobmdctrl.html',
  styleUrls: ['./mob-mobmdctrl.scss']
})
export class Mdctrl implements OnInit,AfterViewInit,OnDestroy{

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

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


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

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

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

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

    }


    /**
     * 返回
     *
     * @memberof Mdctrl
     */
    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();
        }
    }

    /**
     * 查询action
     *
     * @type {string}
     * @memberof Mdctrl
     */
    @Input() public searchAction: string;
    /**
     * updateaction
     *
     * @type {string}
     * @memberof Mdctrl
     */
    @Input() public updateAction:string;
    /**
     * removeaction
     *
     * @type {string}
     * @memberof Mdctrl
     */
    @Input() public removeAction:string;
    /**
     * loadaction
     *
     * @type {string}
     * @memberof Mdctrl
     */
    @Input() public loadAction:string;
    /**
     * createaction
     *
     * @type {string}
     * @memberof Mdctrl
     */
    @Input() public createAction:string;

    /**
     * 输入选中值
     *
     * @type {boolean}
     * @memberof Mdctrl
     */
    @Input() set oldSelected(val: any) {
        if (val) {
            this.selectedArray = val;
            this.selectedArray.forEach((data:any) =>{
                Object.assign(data, { isChecked: true });
            });
        }
    }

    /**
     * 是否多选
     *
     * @type {boolean}
     * @memberof Mdctrl
     */
    @Input() public isMulti;

    /**
     * 加载更多 1或者2
     *
     * @type {boolean}
     * @memberof Mdctrl
     */    
    @Input() public loadMode:number = 1;

    /**
     * 监听当前列表数据变化
     *
     * @type {Subject}
     * @memberof Mdctrl
     */  
    public curValueSubject = new Subject();

    /**
     * 是否为选择视图
     *
     * @type {boolean}
     * @memberof Mdctrl
     */     
    @Input() public isSelectedView:boolean = false;

    /**
     * 加载状态管理
     *
     * @type {string}
     * @memberof Mdctrl
     */
    public loadState: boolean = false;

    /**
     * 分组项
     *
     * @type {string}
     * @memberof Mdctrl
     */
    public grounpItem:any ;

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


    /**
     * Api地址
     *
     * @type {string}
     * @memberof Mdctrl
     */
    public url: string = 'mob/demo/xm/mobmobmdctrl/';

    /**
     * 获取多项数据
     *
     * @returns {any[]}
     * @memberof Mdctrl
     */
    public getDatas(): any[] {
        return this.selectedArray;
    }

    /**
     * 获取单项树
     *
     * @returns {*}
     * @memberof Mdctrl
     */
    public getData(): any {
        return this.selectedArray[0];
    }

    /**
     * 当前页
     *
     * @type {number}
     * @memberof Mdctrl
     */
    public pageNumber: number = 1;

    /**
     * 数据
     *
     * @type {any[]}
     * @memberof Mdctrl
     */
    public items: any[] = [];

    /**
     * 分页条数
     *
     * @type {number}
     * @memberof Mdctrl
     */
    public pageSize: number = 1000;

    /**
     * 总条数
     *
     * @type {number}
     * @memberof Mdctrl
     */
    public totalRecord: number = 0;

    /**
     * 选中数组
     * @type {Array<any>}
     * @memberof Mdctrl
     */
    public selectedArray: Array<any> = [];

    /**
     * 多项数据加载
     *
     * @private
     * @param {*} [arg={}]
     * @memberof Mdctrl
     */
    private load(opt: any = {}, event?: any,showloading?: boolean):Promise<any> {
        return new Promise((resolve, reject) =>{
            const arg: any = { ...opt };
            const parentdata: any = {};
            //this.$emit('beforeload', parentdata);加载之前抛出事件
            Object.assign(arg, parentdata);
            setTimeout(() => {
                this.loadState = false;
            }, 0);
            const post: any = this.$http.post(this.url + this.searchAction, arg,showloading);
            post.then((response: any) => {
                if (!response) {
                    if (response.errorMessage) {
                        this.$notification.error('错误' + response.message);
                    }
                    setTimeout(() => {
                        this.loadState = false;
                    }, 0);
                    return;
                }
                const data: any = response;
                if (Object.keys(data).length > 0) {
                    let tempitems = [];
                    tempitems = JSON.parse(JSON.stringify(data.records));
                    if(event){
                        if (data.current * data.size > this.items.length) {
                            if (tempitems.length > 0) {
                                tempitems.forEach((item: any) => {
                                    this.items.push(item);
                                })
                            }
                        } else {
                            this.items.splice(this.items.length - this.pageSize, this.pageSize);
                            if (tempitems.length > 0) {
                                tempitems.forEach((item: any) => {
                                    this.items.push(item);
                                })
                            }
                        }
                    }else{
                        this.items = tempitems;
                    }
                    this.items.map((item: any) => {
                        Object.assign(item, { isselected: false });
                    });
                    if(this.grounpItem){
                        this.grounpItems();
                    }
                    if(this.selectedArray.length >0){
                        this.selectedArray.forEach((data:any) =>{
                            this.items.forEach((item:any) =>{
                                if(Object.is(item.srfkey,data.srfkey)){
                                    item.isChecked =true;
                                }
                            })
                        });
                        this.selectchangeemit.emit(this.selectedArray);
                    }
                    this.totalRecord = data.total;
                }
                this.loademit.emit(this.items);
                this.curValueSubject.next(this.items);
                setTimeout(() => {
                    this.loadState = false;
                }, 0);
                resolve(this.items);
            }).catch((error: any) => {
                setTimeout(() => {
                    this.loadState = false;
                }, 0);
                this.$notification.error('错误' + error.message);
            });
        })
    }

    /**
     * 多项数据删除行数据
     *
     * @private
     * @param {*} [arg={}]
     * @memberof Mdctrl
     */
    private remove(opt: any = {}):Promise<any>{
        return new Promise((resolve, reject) =>{
            const arg: any = { ...opt };
            const parentdata: any = {};
            Object.assign(arg, parentdata);
            setTimeout(() => {
                this.loadState = true;
            }, 0);
            const post: any = this.$http.post(this.url + this.removeAction, {srfkeys:arg.srfkey});
            post.then((response:any) =>{
                if(response){
                    this.$notification.info('删除成功');
                    this.load();
                    setTimeout(() => {
                        this.loadState = false;
                    }, 0);
                    resolve(response);
                }
            }).catch((error: any) => {
                setTimeout(() => {
                    this.loadState = false;
                    }, 0);
                this.$notification.error('错误' + error.message);
                reject(error);
            });
        })
    }

    /**
     * 刷新数据
     * @memberof Mdctrl
     *
     */
    public refresh():Promise<any>{
        return new Promise((resolve, reject) =>{
            this.load().then((res) =>{
                resolve(res);
            })
        });
    }

    /**
     * 多数据行选中
     * @memberof Mdctrl
     *
     */
    public mdctrl_click(tag:any,item:any){
        this.selectedArray = [];
        this.selectedArray.push(item);
    }    

    /**
     * 选择数据
     * @memberof Mdctrl
     *
     */
    public loadhandle(args: any,action?:any) {
        this.loademit.emit(args);
    }
    public clickhandle(args: any,action?:any) {
        this.clickemit.emit(args);
    }

    /**
     * 选中数据变化
     * @memberof Mdctrl
     *
     */
    public selectChange(data:any){
                //单选
        if (!this.isMulti) {
            if (data.isChecked) {
               if(this.selectedArray.length >0){
                let tempArray = this.selectedArray.filter((item:any) =>{
                    return data.srfkey === item.srfkey;
                });
                if(tempArray.length === 0){
                    this.selectedArray.push(data);
                }
               }else{
                this.selectedArray.push(data);
               }
            }else{
                if(this.selectedArray.length >0){
                    this.selectedArray.forEach((item:any,index:number) =>{
                        if(item.srfkey === data.srfkey){
                            this.selectedArray.splice(index,1);
                        }
                    })
                }
            }
        } else {
            //多选
            if (data.isChecked) {
                if(this.selectedArray.length >0){
                    let tempArray = this.selectedArray.filter((item:any) =>{
                        return data.srfkey === item.srfkey;
                    });
                    if(tempArray.length === 0){
                        this.selectedArray.push(data);
                    }
                   }else{
                    this.selectedArray.push(data);
                   }
            } else {
                this.selectedArray=this.selectedArray.filter((item: any) => {
                    return item.srfkey !== data.srfkey;
                });
            }
        }
        this.selectchangeemit.emit(this.selectedArray);
    }

    /**
     * 选中全部数据
     * @memberof Mdctrl
     *
     */
    public  checkAll(){
        if(this.items && this.items.length >0){
            this.items.forEach((item:any) =>{
                item.isChecked =true;
            });
            this.selectedArray = JSON.parse(JSON.stringify(this.items));
        }
    }

    /**
     * 是否正在加载
     * @memberof Mdctrl
     *
     */
    public isSendingRequest() {
        return this.loadState;
    }

    /**
     * 是否还有更多数据
     * @memberof Mdctrl
     *
     */
    public isInfinite() {
         //是否分组
        let itemsnumber =0;
        if(this.grounpItem){
            if(this.items.length >0){
                this.items.forEach((item) =>{
                    itemsnumber += this.items.length;
                });
            }
         }else{
             itemsnumber =this.items.length;
         }
        if (itemsnumber > 0 && itemsnumber < this.totalRecord) {
            return itemsnumber <= this.totalRecord;
        } else {
            return false;
        }
    }

    /**
     * 是否加载更多
     * @memberof Mdctrl
     *
     */
    public async loadMore(event: any): Promise<any> {
        //是否分组
        let itemsnumber =0;
        if(this.grounpItem){
            if(this.items.length >0){
                this.items.forEach((item) =>{
                    itemsnumber += this.items.length;
                });
            }
        }else{
            itemsnumber =this.items.length;
        }
        if (itemsnumber >= this.totalRecord) {
            if (event && event.target && Object.is(event.type,'ionInfinite')) {
                event.target.complete();
            }
            return;
        }
        this.pageNumber++;
        await this.load({page: { current: this.pageNumber, size: this.pageSize }}, event);
        if (event && event.target && Object.is(event.type,'ionInfinite')) {
            event.target.complete();
        }
    }

    /**
     * 格式化分组数据
     * @memberof Mdctrl
     *
     */
    public grounpItems() {
        let dest = [];
        for (let i = 0; i < this.items.length; i++) {
            let tempObj = this.items[i];
            if(dest.length === 0){
                dest.push({name:tempObj[this.grounpItem],items:[tempObj]});
            }else{
                let tempFlag = true;
                dest.forEach((ele) =>{
                    if(Object.is(ele.name,tempObj[this.grounpItem])){
                        ele.items.push(tempObj);
                        tempFlag =false;
                    }
                });
                if(tempFlag){
                    dest.push({name:tempObj[this.grounpItem],items:[tempObj]});
                }
            }
        }
        this.items = JSON.parse(JSON.stringify(dest));
    }


    ngOnInit(): void {
        if (this.viewState) {
            this.viewState.subscribe(({ tag, action, data }) => {
                if (!Object.is(this.name, tag)) {
                    return;
                }
                this.pageNumber =1;
                if (Object.is(action,'load')) {
                    this.load(Object.assign(data,{page: { current: this.pageNumber, size: this.pageSize }}));
                }
                if (Object.is(action,'search')) {
                    this.load(Object.assign(data,{page: { current: this.pageNumber, size: this.pageSize }}));
                }
                if (Object.is(action,'quicksearch')) {
                    this.load(Object.assign({query:data},{page: { current: this.pageNumber, size: this.pageSize }}),null,false);
                }
            });
        }
    }

    public ngAfterViewInit(): void {}

    public ngOnDestroy(): void {
        this.curValueSubject.unsubscribe();
    }

}