<template>
    <layout class="app-wizard">
    <el-steps class="wizard-steps" v-if="isShowStepBar"  :active="wizardForms.indexOf(activeForm)" finish-status="success" align-center>
      <el-step title="x1"></el-step>
      <el-step title="x2"></el-step>
      <el-step title="x3"></el-step>
    </el-steps>
        <i-content class="app-wizard-content">
            <view_wizardpanel_form_form1 
              v-show="activeForm == 'wizardpanel_form_form1'" 
              :key="'wizardpanel_form_form1'" 
              :viewState='wizardState'
              :context="context"
              :viewtag="viewtag"
              :viewparams="viewparams"
              updateAction="Update"
              removeAction=""
              loadAction="GetDraft"
              @save="wizardpanel_form_form1_save" 
              @load="wizardpanel_form_form1_load" 
              name='wizardpanel_form_form1' 
              ref='wizardpanel_form_form1'>
            </view_wizardpanel_form_form1>
            <view_wizardpanel_form_form2 
              v-show="activeForm == 'wizardpanel_form_form2'" 
              :key="'wizardpanel_form_form2'" 
              :viewState='wizardState'
              :context="context"
              :viewtag="viewtag"
              :viewparams="viewparams"
              updateAction="Update"
              removeAction=""
              loadAction="Get"
              @save="wizardpanel_form_form2_save" 
              @load="wizardpanel_form_form2_load" 
              name='wizardpanel_form_form2' 
              ref='wizardpanel_form_form2'>
            </view_wizardpanel_form_form2>
            <view_wizardpanel_form_form3 
              v-show="activeForm == 'wizardpanel_form_form3'" 
              :key="'wizardpanel_form_form3'" 
              :viewState='wizardState'
              :context="context"
              :viewtag="viewtag"
              :viewparams="viewparams"
              updateAction="Save"
              removeAction=""
              loadAction="GetTemp"
              @save="wizardpanel_form_form3_save" 
              @load="wizardpanel_form_form3_load" 
              name='wizardpanel_form_form3' 
              ref='wizardpanel_form_form3'>
            </view_wizardpanel_form_form3>
        </i-content>
        <footer class="app-wizard-footer">
            <i-button v-show="!isHidden('PREV')" @click="onClickPrev()" type="primary">{{$t('app.wizardPanel.back')}}</i-button>
            <i-button v-show="!isHidden('NEXT')" @click="onClickNext()" type="primary">{{$t('app.wizardPanel.next')}}</i-button>
            <i-button v-show="!isHidden('FINISH')" @click="onClickFinish()" type="primary">{{$t('app.wizardPanel.complete')}}</i-button>
        </footer>
    </layout>
</template>
// 基于 @CONTROL/向导面板/CONTROL-BASE.vue.ftl 生成
<script lang='tsx'>
import { Vue, Component, Prop, Provide, Emit, Watch, Model,Inject } from 'vue-property-decorator';
import { CreateElement } from 'vue';
import { Subject, Subscription } from 'rxjs';
import { ControlInterface } from '@/interface/control';
import { UIActionTool,Util,ViewTool } from '@/utils';
import NavDataService from '@/service/app/navdata-service';
import AppCenterService from "@service/app/app-center-service";
import IBIZOrderEntityService from '@/service/ibizorder/ibizorder-service';
import TestService from './test-wizardpanel-service';
import IBIZOrderUIService from '@/uiservice/ibizorder/ibizorder-ui-service';


@Component({
    components: {
      
    }
})
export default class TestBase extends Vue implements ControlInterface {

    /**
     * 名称
     *
     * @type {string}
     * @memberof TestBase
     */
    @Prop() public name?: string;

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

    /**
     * 应用上下文
     *
     * @type {*}
     * @memberof TestBase
     */
    @Prop() public context!: any;

    /**
     * 视图参数
     *
     * @type {*}
     * @memberof TestBase
     */
    @Prop() public viewparams!: any;

    /**
     * 视图操作参数(父级)
     *
     * @type {*}
     * @memberof TestBase
     */
    @Prop() public pViewCtx!: any;

    /**
     * 视图操作参数
     *
     * @type {*}
     * @memberof TestBase
     */
    public viewCtx: any = {};

    /**
     * 监听视图操作参数变化
     *
     * @type {*}
     * @memberof TestBase
     */
    @Watch('pViewCtx', { immediate: true })
    public onViewCtxChange(newVal: any, oldVal: any) {
        Object.assign(this.viewCtx, newVal, { xData: this, ctrl: this });
    }

    /**
     * 视图状态事件
     *
     * @public
     * @type {(Subscription | undefined)}
     * @memberof TestBase
     */
    public viewStateEvent: Subscription | undefined;

    /**
     * 获取部件类型
     *
     * @returns {string}
     * @memberof TestBase
     */
    public getControlType(): string {
        return 'WIZARDPANEL'
    }



    /**
     * 计数器服务对象集合
     *
     * @type {Array<*>}
     * @memberof TestBase
     */    
    public counterServiceArray:Array<any> = [];

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

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

    /**
     * wizardpanel_form_form1 部件 save 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof TestBase
     */
    public wizardpanel_form_form1_save($event: any, $event2?: any) {
        this.wizardpanel_formsave($event, 'wizardpanel_form_form1', $event2);
    }

    /**
     * wizardpanel_form_form1 部件 load 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof TestBase
     */
    public wizardpanel_form_form1_load($event: any, $event2?: any) {
        this.wizardpanel_formload($event, 'wizardpanel_form_form1', $event2);
    }

    /**
     * wizardpanel_form_form2 部件 save 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof TestBase
     */
    public wizardpanel_form_form2_save($event: any, $event2?: any) {
        this.wizardpanel_formsave($event, 'wizardpanel_form_form2', $event2);
    }

    /**
     * wizardpanel_form_form2 部件 load 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof TestBase
     */
    public wizardpanel_form_form2_load($event: any, $event2?: any) {
        this.wizardpanel_formload($event, 'wizardpanel_form_form2', $event2);
    }

    /**
     * wizardpanel_form_form3 部件 save 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof TestBase
     */
    public wizardpanel_form_form3_save($event: any, $event2?: any) {
        this.wizardpanel_formsave($event, 'wizardpanel_form_form3', $event2);
    }

    /**
     * wizardpanel_form_form3 部件 load 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof TestBase
     */
    public wizardpanel_form_form3_load($event: any, $event2?: any) {
        this.wizardpanel_formload($event, 'wizardpanel_form_form3', $event2);
    }
    


    /**
     * 转化数据
     *
     * @param {any} args
     * @memberof  TestBase
     */
    public transformData(args: any) {
        let _this: any = this;
        if(_this.service && _this.service.handleRequestData instanceof Function && _this.service.handleRequestData('transform',_this.context,args)){
            return _this.service.handleRequestData('transform',_this.context,args)['data'];
        }
    }

    /**
     * 关闭视图
     *
     * @param {any} args
     * @memberof TestBase
     */
    public closeView(args: any): void {
        let _this: any = this;
        _this.$emit('closeview', [args]);
    }

    /**
     *  计数器刷新
     *
     * @memberof TestBase
     */
    public counterRefresh(){
        const _this:any =this;
        if(_this.counterServiceArray && _this.counterServiceArray.length >0){
            _this.counterServiceArray.forEach((item:any) =>{
                if(item.refreshData && item.refreshData instanceof Function){
                    item.refreshData();
                }
            })
        }
    }
    /**
     *  处理部件事件
     *
     * @memberof TestBase
     */
    public async handleCtrlEvents(eventName: string, args: any = {}): Promise<boolean> {
        const actionData = {
            data: this.getData() || {},
            context: Util.deepCopy(this.context),
            viewparams: Util.deepCopy(this.viewparams),
            xData: this
        }
        let result: boolean = true;
        Object.assign(actionData, args);
        if (!result) {
            return false;
        }
        this.$emit(eventName, actionData);
        return true;
    }




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

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

    /**
     * 视图标识
     *
     * @type {string}
     * @memberof TestBase
     */
    @Prop() public viewtag!: string;

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

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

    /**
     * 显示步骤栏
     *
     * @type {Boolean}
     * @memberof TestBase
     */
    public isShowStepBar: Boolean =  true ;

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

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

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

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

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

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

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

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

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

    /**
     * Vue声明周期(处理组件的输入属性)
     *
     * @memberof TestBase
     */
    public created(): void {
        this.regFormActions();
        if(this.activeForm && !this.stateField) {
            this.historyForms.push(this.activeForm);
        }
        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 TestBase
     */
    public destroyed() {
        if (this.viewStateEvent) {
            this.viewStateEvent.unsubscribe();
        }
    }

    /**
     * 注册表单步骤行为
     *
     * @memberof TestBase
     */
    public regFormActions() {
        this.regFormAction('wizardpanel_form_form1',{loadAction:"GetDraft",saveAction:'Update',actions:['NEXT']},'x1');
        this.regFormAction('wizardpanel_form_form2',{loadAction:"Get",preAction:'Save',saveAction:'Update',actions:['PREV','NEXT']},'x2');
        this.regFormAction('wizardpanel_form_form3',{loadAction:"GetTemp",preAction:'Remove',saveAction:'Save',actions:['PREV','FINISH']},'x3');
    }

    /**
     * 注册表单步骤行为
     *
     * @memberof TestBase
     */
    public regFormAction(name: string, actionParams: any,stepTag:any) {
        this.stepActions[name] = actionParams;
        this.stepTags[name] = stepTag;
        this.wizardForms.push(name);
    }

    /**
     * 初始化行为
     *
     * @memberof TestBase
     */
    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.ibizorder){
                    Object.assign(this.context,{ibizorder:response.data.ibizorder})
                }
                this.formLoad(this.formParam);
            }
        }).catch((response: any) => {
            if (response && response.status === 401) {
                return;
            }
            this.$Notice.error({ title: (this.$t('app.commonWords.wrong') as string), desc: response.info });
        });
    }

    /**
     * 表单加载
     *
     * @memberof TestBase
     */
    public formLoad(data:any) {
        if(this.stateField) this.computedActiveForm(data);
        if(this.activeForm) {
            this.wizardState.next({ tag: this.activeForm, action:'panelaction',data: {action:this.stepActions[this.activeForm].loadAction,emitAction:'load',data:this.formParam} });
        }
    }

    /**
     * 根据状态获取当前激活表单
     *
     * @memberof TestBase
     */
    public computedActiveForm(data:any){
        if(data && 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;
                        return;
                    }
                })
            }
        }
    }

    /**
     * 完成行为
     *
     * @memberof TestBase
     */
    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.$Notice.success({ title: this.$t('app.commonWords.success') as string, desc: this.$t('app.commonWords.startsuccess') as string });
                this.$emit("finish", data);
                AppCenterService.notifyMessage({name:"IBIZOrder",action:'appRefresh',data: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 TestBase
     */
    public wizardpanel_formload(args: any, name: string, $event2?: any) {
        if(args) {
            Object.assign(this.formParam, args);
            if (Object.is(this.curState, 'NEXT') || Object.is(this.curState, 'PREV')) {
                this.$store.commit('viewaction/setViewDataChange', { viewtag: this.viewtag, viewdatachange: true });
            }
        }
    }

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

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


    /**
     * 上一步
     *
     * @memberof TestBase
     */
    public onClickPrev() {
        if(!this.stateField){
            const length = this.historyForms.length;
            if(length > 1) {
                this.curState = 'PREV';
                this.activeForm = this.historyForms[length - 1];
                setTimeout(() => {
                    this.formLoad(this.formParam);
                }, 1);
                this.historyForms.splice(length - 1, 1);
            }
        }else{
            if(this.activeForm) {
                if(this.$refs && this.$refs[this.activeForm]){
                    let form: any = this.$refs[this.activeForm];
                    this.curState = 'PREV';
                    if(!this.stepActions[this.activeForm].preAction){
                        this.$Notice.error({ title: (this.$t('app.commonWords.wrong') as string), desc:this.$t('app.wizardPanel.preactionmessage') as string  });
                        return;
                    }
                    this.wizardState.next({ tag: this.activeForm, action:'panelaction',data: {action:this.stepActions[this.activeForm].preAction,emitAction:'save',data:this.formParam} });
                }
            }
        }
    }

    /**
     * 下一步
     *
     * @memberof TestBase
     */
    public onClickNext() {
        if(this.activeForm) {
            if(this.$refs && this.$refs[this.activeForm]){
                let form: any = this.$refs[this.activeForm];
                if(form.formValidateStatus()) {
                    this.curState = 'NEXT';
                    this.wizardState.next({ tag: this.activeForm, action:'panelaction',data: {action:this.stepActions[this.activeForm].saveAction,emitAction:'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 TestBase
     */
    public onClickFinish() {
        if(this.activeForm) {
            if(this.$refs && this.$refs[this.activeForm]){
                let form: any = this.$refs[this.activeForm];
                if(form.formValidateStatus()) {
                    this.curState = 'FINISH';
                    this.wizardState.next({ tag: this.activeForm, action:'panelaction',data: {action:this.stepActions[this.activeForm].saveAction,emitAction:'save',data:this.formParam} });
                } else {
                    this.$Notice.error({ title: (this.$t('app.commonWords.wrong') as string), desc: (this.$t('app.commonWords.rulesException') as string) });
                }
            }
        }
    }

    /**
     * 是否隐藏
     *
     * @param {string} type
     * @memberof TestBase
     */
    public isHidden(type: string) {
        const actions: Array<string> = this.stepActions[this.activeForm].actions;
        if(actions && actions.indexOf(type) < 0) {
            return true;
        }
        return false;
    }
    

}
</script>

<style lang='less'>
@import './test-wizardpanel.less';
</style>