import { Prop, Provide, Emit, Model } from 'vue-property-decorator';
import { Subject, Subscription } from 'rxjs';
import { UIActionTool,Util,ViewTool } from '@/utils';
import { Watch, MainControlBase } from '@/studio-core';
import Purchase_requisitionService from '@/service/purchase-requisition/purchase-requisition-service';
import StateService from './state-statewizardpanel-service';
import Purchase_requisitionUIService from '@/uiservice/purchase-requisition/purchase-requisition-ui-service';


/**
 * statewizardpanel部件基类
 *
 * @export
 * @class MainControlBase
 * @extends {StateStatewizardpanelBase}
 */
export class StateStatewizardpanelBase extends MainControlBase {

    /**
     * 获取部件类型
     *
     * @protected
     * @type {string}
     * @memberof StateStatewizardpanelBase
     */
    protected controlType: string = 'STATEWIZARDPANEL';

    /**
     * 建构部件服务对象
     *
     * @type {StateService}
     * @memberof StateStatewizardpanelBase
     */
    public service: StateService = new StateService({ $store: this.$store });

    /**
     * 实体服务对象
     *
     * @type {Purchase_requisitionService}
     * @memberof StateStatewizardpanelBase
     */
    public appEntityService: Purchase_requisitionService = new Purchase_requisitionService({ $store: this.$store });

    /**
     * 应用实体名称
     *
     * @protected
     * @type {string}
     * @memberof StateStatewizardpanelBase
     */
    protected appDeName: string = 'purchase_requisition';

    /**
     * 应用实体中文名称
     *
     * @protected
     * @type {string}
     * @memberof StateStatewizardpanelBase
     */
    protected appDeLogicName: string = '采购申请';

    /**
     * 界面UI服务对象
     *
     * @type {Purchase_requisitionUIService}
     * @memberof StateBase
     */  
    public appUIService:Purchase_requisitionUIService = new Purchase_requisitionUIService(this.$store);

    /**
     * statewizardpanel_form_cancel 部件 save 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof StateStatewizardpanelBase
     */
    public statewizardpanel_form_cancel_save($event: any, $event2?: any) {
        this.statewizardpanel_formsave($event, 'statewizardpanel_form_cancel', $event2);
    }

    /**
     * statewizardpanel_form_cancel 部件 load 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof StateStatewizardpanelBase
     */
    public statewizardpanel_form_cancel_load($event: any, $event2?: any) {
        this.statewizardpanel_formload($event, 'statewizardpanel_form_cancel', $event2);
    }

    /**
     * statewizardpanel_form_done 部件 save 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof StateStatewizardpanelBase
     */
    public statewizardpanel_form_done_save($event: any, $event2?: any) {
        this.statewizardpanel_formsave($event, 'statewizardpanel_form_done', $event2);
    }

    /**
     * statewizardpanel_form_done 部件 load 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof StateStatewizardpanelBase
     */
    public statewizardpanel_form_done_load($event: any, $event2?: any) {
        this.statewizardpanel_formload($event, 'statewizardpanel_form_done', $event2);
    }

    /**
     * statewizardpanel_form_in_progress 部件 save 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof StateStatewizardpanelBase
     */
    public statewizardpanel_form_in_progress_save($event: any, $event2?: any) {
        this.statewizardpanel_formsave($event, 'statewizardpanel_form_in_progress', $event2);
    }

    /**
     * statewizardpanel_form_in_progress 部件 load 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof StateStatewizardpanelBase
     */
    public statewizardpanel_form_in_progress_load($event: any, $event2?: any) {
        this.statewizardpanel_formload($event, 'statewizardpanel_form_in_progress', $event2);
    }

    /**
     * statewizardpanel_form_open 部件 save 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof StateStatewizardpanelBase
     */
    public statewizardpanel_form_open_save($event: any, $event2?: any) {
        this.statewizardpanel_formsave($event, 'statewizardpanel_form_open', $event2);
    }

    /**
     * statewizardpanel_form_open 部件 load 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof StateStatewizardpanelBase
     */
    public statewizardpanel_form_open_load($event: any, $event2?: any) {
        this.statewizardpanel_formload($event, 'statewizardpanel_form_open', $event2);
    }

    /**
     * statewizardpanel_form_ongoing 部件 save 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof StateStatewizardpanelBase
     */
    public statewizardpanel_form_ongoing_save($event: any, $event2?: any) {
        this.statewizardpanel_formsave($event, 'statewizardpanel_form_ongoing', $event2);
    }

    /**
     * statewizardpanel_form_ongoing 部件 load 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof StateStatewizardpanelBase
     */
    public statewizardpanel_form_ongoing_load($event: any, $event2?: any) {
        this.statewizardpanel_formload($event, 'statewizardpanel_form_ongoing', $event2);
    }

    /**
     * statewizardpanel_form_draft 部件 save 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof StateStatewizardpanelBase
     */
    public statewizardpanel_form_draft_save($event: any, $event2?: any) {
        this.statewizardpanel_formsave($event, 'statewizardpanel_form_draft', $event2);
    }

    /**
     * statewizardpanel_form_draft 部件 load 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof StateStatewizardpanelBase
     */
    public statewizardpanel_form_draft_load($event: any, $event2?: any) {
        this.statewizardpanel_formload($event, 'statewizardpanel_form_draft', $event2);
    }


    /**
     * 部件行为--init
     *
     * @type {string}
     * @memberof StateBase
     */
    @Prop() public initAction!: string;
    
    /**
     * 部件行为--finish
     *
     * @type {string}
     * @memberof StateBase
     */
    @Prop() public finishAction!: string;

    /**
     * 显示处理提示
     *
     * @type {boolean}
     * @memberof StateBase
     */
    @Prop({ default: true }) public showBusyIndicator?: boolean;

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

    /**
      * 获取单项数据
      *
      * @returns {*}
      * @memberof StateBase
      */
    public getData(): any {
        return this.formParam;
    }

    /**
     * 视图状态订阅对象
     *
     * @public
     * @type {Subject<{action: string, data: any}>}
     * @memberof StateBase
     */
    public wizardState: Subject<ViewState> = new Subject();

    /**
     * 当前激活表单
     *
     * @type {string}
     * @memberof StateBase
     */
    public activeForm: string = '';

    /**
     * 第一个向导表单
     *
     * @type {string}
     * @memberof StateBase
     */
    public firstForm: string = 'statewizardpanel_form_draft';

    /**
     * 状态属性
     *
     * @type {string}
     * @memberof StateBase
     */
    public stateField: string = 'state';

    /**
     * 当前显示表单
     *
     * @type {string}
     * @memberof StateBase
     */
    public curShow:string ="";

    /**
     * 向导表单参数
     *
     * @type {*}
     * @memberof StateBase
     */
    public formParam: any = {};

    /**
     * 执行过的表单
     *
     * @public
     * @type {Array<string>}
     * @memberof StateBase
     */
    public historyForms: Array<string> = [];

    /**
     * 步骤行为集合
     *
     * @type {*}
     * @memberof StateBase
     */
    public stepActions: any = {};

    /**
     * 步骤标识集合
     *
     * @type {*}
     * @memberof StateBase
     */
    public stepTags: any = {};

    /**
     * 步骤是否显示集合
     *
     * @type {*}
     * @memberof StateBase
     */
    public stepVisiable:any = {};

    /**
     * 向导表单集合
     *
     * @type {Array<any>}
     * @memberof StateBase
     */
    public wizardForms: Array<any> = [];

    /**
     * 当前状态
     *
     * @memberof StateBase
     */
    public curState = '';

    /**
     * 抽屉状态
     *
     * @memberof StateBase
     */
    public drawerOpenStatus:any = {
        isOpen:false,
        formName:""
    }

    /**
     * Vue声明周期(处理组件的输入属性)
     *
     * @memberof StateBase
     */
    public created(): void {
        this.regFormActions();
        this.doInit();
        if (this.viewState) {
            this.viewStateEvent = this.viewState.subscribe(({ tag, action, data }) => {
                if (Object.is(tag, this.name)) {
                    if (Object.is('load', action)) {
                        this.doInit(data);
                    }
                }
            });
        }
    }

    /**
     * vue 生命周期
     *
     * @memberof StateBase
     */
    public destroyed() {
        if (this.viewStateEvent) {
            this.viewStateEvent.unsubscribe();
        }
    }

    /**
     * 注册表单步骤行为
     *
     * @memberof StateBase
     */
    public regFormActions() {
        this.regFormAction('statewizardpanel_form_draft', ['NEXT'],'draft');
        this.regFormAction('statewizardpanel_form_ongoing', ['PREV','NEXT'],'ongoing');
        this.regFormAction('statewizardpanel_form_in_progress', ['PREV','NEXT'],'in_progress');
        this.regFormAction('statewizardpanel_form_open', ['PREV','NEXT'],'open');
        this.regFormAction('statewizardpanel_form_done', ['PREV','NEXT','FINISH'],'done');
        this.regFormAction('statewizardpanel_form_cancel', ['PREV','NEXT','FINISH'],'cancel');
    }

    /**
     * 注册表单步骤行为
     *
     * @memberof StateBase
     */
    public regFormAction(name: string, actions: Array<string>,stepTag:any) {
        this.stepActions[name] = actions;
        this.stepTags[name] = stepTag;
        this.stepVisiable[name] = false;
        this.wizardForms.push(name);
    }

    /**
     * 计算激活表单
     *
     * @memberof StateBase
     */
    public computedActiveForm(data:any){
        if(data[this.stateField]){
            if(Object.keys(this.stepTags).length >0){
                Object.keys(this.stepTags).forEach((name:string) =>{
                    if(this.stepTags[name] === data[this.stateField]){
                        this.activeForm = name;
                    }
                })
            }
            if(!this.activeForm){
                this.activeForm = this.firstForm;
            }
        }else{
            this.activeForm = this.firstForm;
        }
        if(this.activeForm) {
            let index = this.wizardForms.indexOf(this.activeForm);
            this.wizardForms.forEach((item:any,inx:number) =>{
                if(inx <= index){
                    this.historyForms.push(item);
                }
            })
        }
    }

    /**
     * 初始化行为
     *
     * @memberof StateBase
     */
    public doInit(opt: any = {}) {
        const arg: any = { ...opt };
        Object.assign(arg,{viewparams:this.viewparams});
        const post: Promise<any> = this.service.init(this.initAction, JSON.parse(JSON.stringify(this.context)), arg, this.showBusyIndicator);
        post.then((response: any) => {
            if (response && response.status === 200) {
                this.formParam = response.data;
                if(response.data.purchase_requisition){
                    Object.assign(this.context,{purchase_requisition:response.data.purchase_requisition})
                }
                this.computedActiveForm(response.data);
            }
        }).catch((response: any) => {
            if (response && response.status === 401) {
                return;
            }
            this.$Notice.error({ title: (this.$t('app.commonWords.wrong') as string), desc: response.info });
        });
    }

    /**
     * 表单加载
     *
     * @memberof StateBase
     */
    public formLoad(name:string) {
        if(name) {
            this.wizardState.next({ tag: name, action: 'load', data: this.formParam });
        }
    }

    /**
     * 完成行为
     *
     * @memberof StateBase
     */
    public doFinish() {
        let arg: any = {};
        Object.assign(arg, this.formParam);
        Object.assign(arg,{viewparams:this.viewparams});
        const post: Promise<any> = this.service.finish(this.finishAction, JSON.parse(JSON.stringify(this.context)), arg, this.showBusyIndicator);
        post.then((response: any) => {
            if (response && response.status === 200) {
                const data = response.data;
                this.$emit("finish", data);
            }
        }).catch((response: any) => {
            if (response && response.status === 401) {
                return;
            }
            this.$Notice.error({ title: (this.$t('app.commonWords.wrong') as string), desc: response.info });
        });
    }

    /**
     * 向导表单加载完成
     *
     * @param {*} args
     * @param {string} name
     * @memberof StateBase
     */
    public statewizardpanel_formload(args: any, name: string, $event2?: any) {
        if(args) {
            Object.assign(this.formParam, args);
        }
    }

    /**
     * 向导表单保存完成
     *
     * @param {*} args
     * @param {string} name
     * @memberof StateBase
     */
    public statewizardpanel_formsave(args: any, name: string, $event2?: any) {
        Object.assign(this.formParam, args);
        if(Object.is(this.curState, 'NEXT')) {
            if(this.historyForms.indexOf(name) === -1){
                this.historyForms.push(name);
            }
            this.setPopVisiable(name,false);
            if (this.getNextForm(name)) {
                this.activeForm = this.getNextForm(name);
                this.setPopVisiable(this.activeForm,true);
                setTimeout(() => {
                    this.formLoad(this.activeForm);
                }, 1);
            } else {
                this.doFinish();
            }
        }else if(Object.is(this.curState, 'FINISH')) {
            this.doFinish();
        }
    }

    /**
     * 打开链接
     *
     * @memberof StateBase
     */
    public handleOPen(name:string){
        this.handleClose(name);
        this.drawerOpenStatus.isOpen = true;
        this.drawerOpenStatus.formName = name;
    }

    /**
     * 关闭
     *
     * @memberof StateBase
     */
    public handleClose(name:string){
        this.setPopVisiable(name,false);
    }

    /**
     * 设置popover是否显示
     *
     * @memberof StateBase
     */
    public setPopVisiable(name:string,isVisiable:boolean){
        this.stepVisiable[name] = isVisiable;
        (this.$refs[name+'_popover'] as any).showPopper = isVisiable;
        this.curShow = isVisiable?name:"";
    }

    /**
     *  导航条点击事件
     *
     * @memberof StateBase
     */
    public hanleClick(name:string){
        let activeIndex:number = this.wizardForms.indexOf(this.activeForm);
        let curIndex:number = this.wizardForms.indexOf(name);
        if(curIndex > activeIndex){
            setTimeout(() =>{
                (this.$refs[name+'_popover'] as any).showPopper = false;
                this.curShow = "";
            },0)
            return;
        }
        this.stepVisiable[name] = !this.stepVisiable[name];
        if(this.stepVisiable[name]){
            this.curShow = name;
            this.formLoad(name);
        }else{
            this.curShow = "";
        }
    }

    /**
     * 获取下一步向导表单
     *
     * @memberof StateBase
     */
    public getNextForm(name:string) {
        let index = this.wizardForms.indexOf(name);
        if(index >= 0) {
            if(this.wizardForms[index + 1]) {
                return this.wizardForms[index + 1];
            }
        }
        return undefined;
    }


    /**
     * 上一步
     *
     * @memberof StateBase
     */
    public onClickPrev(name:string) {
        const length = this.historyForms.length;
        if(length > 1) {
            this.curState = 'PREV';
            let curIndex:number = this.wizardForms.indexOf(name);
            this.setPopVisiable(name,false);
            setTimeout(() => {
                this.setPopVisiable(this.historyForms[curIndex - 1],true);
                this.formLoad(this.historyForms[curIndex - 1]);
            }, 1);
        }
    }

    /**
     * 下一步
     *
     * @memberof StateBase
     */
    public onClickNext(name:string) {
        if(name) {
            if(this.$refs && this.$refs[name]){
                let form: any = this.$refs[name];
                if(form.formValidateStatus()) {
                    this.curState = 'NEXT';
                    this.wizardState.next({ tag: name, action: 'save', data: this.formParam });
                } else {
                    this.$Notice.error({ title: (this.$t('app.commonWords.wrong') as string), desc: (this.$t('app.commonWords.rulesException') as string) });
                }
            }
        }
    }

    /**
     * 完成
     *
     * @memberof StateBase
     */
    public onClickFinish(name:string) {
        if(name) {
            if(this.$refs && this.$refs[name]){
                let form: any = this.$refs[name];
                if(form.formValidateStatus()) {
                    this.curState = 'FINISH';
                    this.wizardState.next({ tag: name, action: 'save', data: this.formParam });
                } else {
                    this.$Notice.error({ title: (this.$t('app.commonWords.wrong') as string), desc: (this.$t('app.commonWords.rulesException') as string) });
                }
            }
        }
    }

    /**
     * 左右两侧点击事件
     *
     * @memberof StateBase
     */
    public handleClick(mode:string){
        if(Object.is(this.curShow,"")){
            return;
        }
        let curIndex:number = this.wizardForms.indexOf(this.curShow);
        if(Object.is(mode,"PRE") && (curIndex !== 0)){
            this.setPopVisiable(this.wizardForms[curIndex],false);
            setTimeout(() => {
                this.setPopVisiable(this.wizardForms[curIndex-1],true);
                this.formLoad(this.wizardForms[curIndex-1]);
            }, 0);
        }
        if(Object.is(mode,"NEXT") && (curIndex < (this.wizardForms.length - 1) && this.historyForms.includes(this.wizardForms[curIndex+1]))){
            this.setPopVisiable(this.wizardForms[curIndex],false);
            setTimeout(() => {
                this.setPopVisiable(this.wizardForms[curIndex+1],true);
                this.formLoad(this.wizardForms[curIndex+1]);
            }, 0);
        }
    }

    /**
     * 是否显示
     *
     * @memberof StateBase
     */
    public isVisiable(name:string,type: string) {
        const actions: Array<string> = this.stepActions[name];
        if(actions && actions.indexOf(type) !== -1 && Object.is(name,this.activeForm)) {
            return true;
        }else{
            return false;
        }
    }
    /**
     * 抽屉状态改变
     *
     * @memberof StateBase
     */
    public onVisibleChange(value:any){
        if(!value){
            this.drawerOpenStatus.isOpen = false;
        }
    }

}

