<template>
  <div class="workflow-create">
    <a-card :body-style="{ padding: 0, height: '80vh' }">
      <a-tabs v-model="activeTab" default-active-key="baseSetting" type="line">
        <a-tab-pane key="baseSetting" tab="①基础信息">
          <FormBaseSetting ref="baseSettingRef" :group-id="groupId" :is-edit="!isNew" />
        </a-tab-pane>
        <a-tab-pane key="formDesign" tab="②审批表单">
          <FormDesign ref="formDesignRef" />
        </a-tab-pane>
        <a-tab-pane key="processDesign" tab="③审批流程">
          <ProcessDesign ref="processDesignRef" />
        </a-tab-pane>
        <a-tab-pane key="proSetting" tab="④拓展设置">
          <FormProSetting ref="proSettingRef" />
        </a-tab-pane>
        <template slot="tabBarExtraContent">
          <div class="publish">
            <a-button size="small" @click="preview">
              <a-icon type="eye" />
              预览
            </a-button>
            <a-button size="small" type="primary" @click="publishProcess">
              <a-icon type="rocket" />
              发布
            </a-button>
          </div>
        </template>
      </a-tabs>
    </a-card>
    <a-modal
      v-model="validVisible"
      title="设置项检查"
      :width="600"
      :footer="null"
      @cancel="validVisible = false"
    >
      <a-steps :current="validStep" status="process">
        <a-step
          v-for="(item, index) in validOptions"
          :key="index"
          :title="item.title"
          :status="item.status"
          :description="item.description"
        />
      </a-steps>
      <a-result :title="errTitle" :status="validIcon" :sub-title="validResult.desc">
        <div slot="extra" class="flex flex-col justify-center items-center">
          <div class="err-info">
            <div v-for="(err, i) in validResult.errs" :key="i + '_err'" class="err-info__item">
              <a-icon type="warning" style="font-size: 14px; vertical-align: middle; margin-right: 5px;" />
              <span style="font-size: 12px; vertical-align: middle">{{ err }}</span>
            </div>
          </div>
          <a-button
            v-if="validResult.finished"
            type="primary"
            size="small"
            style="width: 70px; margin-top: 20px"
            @click="doAfter"
          >
            {{ validResult.action }}
          </a-button>
        </div>
        <a-icon v-if="!validResult.finished" slot="icon" type="loading" class="loading-icon" />
      </a-result>
    </a-modal>
  </div>
</template>

<script>
import { mapActions } from 'vuex';
import FormBaseSetting from '@/views/workFlow/designer/components/FormBaseSetting/index.vue';
import FormDesign from '@/views/workFlow/designer/components/FormDesign/index.vue';
import ProcessDesign from '@/views/workFlow/designer/components/ProcessDesign/index.vue';
import FormProSetting from '@/views/workFlow/designer/components/FormProSetting/index.vue';
import { getAction, postAction, putAction } from '@api/manage'
import { isEmpty } from '@/utils/util'

export default {
  name: 'DesignerCreate',
  components: {
    FormBaseSetting,
    FormDesign,
    ProcessDesign,
    FormProSetting,
  },
  data() {
    return {
      groupId: null,
      isNew: true,
      activeTab: 'baseSetting',
      validStep: 0,
      validResult: {
        errs: [],
        finished: false,
        success: false,
        title: '检查中...',
        action: '处理',
        desc: '正在检查设置项',
      },
      timer: null,
      validVisible: false,
      validOptions: [
        { title: '基础信息', description: '', icon: '', status: '' },
        { title: '审批表单', description: '', icon: '', status: '' },
        { title: '审批流程', description: '', icon: '', status: '' },
        { title: '拓展设置', description: '', icon: '', status: '' },
      ],
      baseSettingRef: null,
      formDesignRef: null,
      processDesignRef: null,
      proSettingRef: null,
    };
  },
  computed: {
    validComponents() {
      return [this.$refs.baseSettingRef, this.$refs.formDesignRef, this.$refs.processDesignRef, this.$refs.proSettingRef];
    },
    errTitle() {
      if (this.validResult.finished && !this.validResult.success) {
        return `${this.validResult.title} (${this.validResult.errs.length}项错误)`;
      }
      return this.validResult.title;
    },
    validIcon() {
      return this.validResult.success ? 'success' : 'warning';
    },
  },
  methods: {
    ...mapActions('workflow', ['loadForm']),
    getNodeKey() {
      return `flk_${new Date().getTime().toString().substring(5)}${Math.round(Math.random() * 9000 + 1000)}`;
    },
    loadInitFrom() {
      this.loadForm({
        templateId: null,
        templateName: '未命名流程',
        templateKey: '',
        settings: {
          sign: false,
        },
        groupId: undefined,
        formItems: [],
        process: {
          id: 'node_start',
          parentId: null,
          type: 0,
          nodeName: '发起人',
          nodeKey: this.getNodeKey(),
          nodeAssigneeList: [],
          childNode: {
            id: 'node_end',
            parentId: 'node_root',
            type: -1,
            nodeName: '结束',
            nodeAssigneeList: [],
          },
        },
        remark: '',
      });
    },
    stopTimer() {
      if (this.timer) {
        clearInterval(this.timer);
      }
    },
    validateDesign() {
      this.validVisible = true
      this.validStep = 0
      this.showValiding()
      this.stopTimer()
      this.timer = setInterval(() => {
        if(this.validStep === 1 && this.validComponents[1] === undefined) {
          this.activeTab = 'formDesign';
          this.$nextTick(()=>{
            this.validComponents[1]=this.$refs.formDesignRef;
          })
        }
        if(this.validStep === 3 && this.validComponents[3] === undefined) {
          this.activeTab = 'proSetting';
          this.$nextTick(()=>{
            this.validComponents[3]=this.$refs.proSettingRef;
          })
        }
        this.validResult.errs = this.validComponents[this.validStep].validate()
        if (Array.isArray(this.validResult.errs) && this.validResult.errs.length === 0) {
          this.validStep++
          if (this.validStep >= this.validOptions.length) {
            this.stopTimer()
            this.showValidFinish(true)
          }
        } else {
          this.stopTimer()
          this.validOptions[this.validStep].status = 'error'
          this.showValidFinish(false, this.getDefaultValidErr())
        }
      }, 300)
    },
    getDefaultValidErr() {
      switch (this.validStep) {
        case 0:
          return '请检查基础设置项';
        case 1:
          return '请检查审批表单相关设置';
        case 2:
          return '请检查审批流程，查看对应标注节点错误信息';
        case 3:
          return '请检查拓展设置';
        default:
          return '未知错误';
      }
    },
    showValidFinish(success, err) {
      this.validResult.success = success;
      this.validResult.finished = true;
      this.validResult.title = success ? '校验完成' : '校验失败';
      this.validResult.desc = success ? '设置项校验成功，是否提交？' : err || '';
      this.validResult.action = success ? '提交' : '去修改';
    },
    showValiding() {
      this.validResult = {
        errs: [],
        finished: false,
        success: false,
        title: '检查中...',
        action: '处理',
        desc: '正在检查设置项',
      };
      this.validStep = 0;
      this.validOptions.forEach((op) => {
        op.status = '';
        op.icon = '';
        op.description = '';
      });
    },
    publishProcess() {
      this.validateDesign();
    },
    doAfter() {
      if (this.validResult.success) {
        this.doPublish();
      } else {
        this.activeTab = ['baseSetting', 'formDesign', 'processDesign', 'proSetting'][this.validStep];
        this.validVisible = false;
      }
    },
    doPublish() {
      const design = this.$store.state.workflow.design;
      const processNew = JSON.parse(JSON.stringify(design.process));
      this.conditionRecursion(processNew);

      const template = {
        templateId: design.templateId,
        templateName: design.templateName,
        templateKey: design.templateKey,
        templateVersion: design.templateVersion,
        settings: JSON.stringify(design.settings),
        groupId: design.groupId,
        formItems: JSON.stringify(design.formItems),
        process: JSON.stringify(processNew),
        remark: design.remark,
      };

      if (this.isNew || isEmpty(design.templateId)) {
        postAction('/workflow/template',template)
          .then((res) => {
            if(res.success) {
              this.$message.success('创建流程模版成功');
              this.$router.push('/workFlow/designer');
            }else {
              this.$message.error('创建失败！')
            }
          })
          .catch((err) => {
            console.error(err);
          });
      } else {
        putAction('/workflow/template/update',template)
          .then((res) => {
            if(res.success) {
              this.$message.success('更新流程模版成功');
              this.$router.push('/workFlow/designer');
            }else {
              this.$message.error('更新失败！')
            }

          })
          .catch((err) => {
            console.error(err);
          });
      }
    },
    conditionRecursion(process) {
      if (process != null && process !== undefined) {
        if (process.branchs != null && process.branchs !== undefined) {
          process.branchs.forEach((item, i) => {
            item.typeElse = i === process.branchs.length - 1;
            if (item.childNode != null && item.childNode !== undefined) {
              this.conditionRecursion(item.childNode);
            }
          });
        } else {
          this.conditionRecursion(process.childNode);
        }
      }
    },
    loadTemplateDetail(templateId) {
      getAction('/workflow/template/detail',{templateId:templateId}).then((res) => {
        const detail = res.result;
        detail.logo = JSON.parse(detail.logo);
        detail.settings = JSON.parse(detail.settings);
        detail.formItems = JSON.parse(detail.formItems);
        detail.process = JSON.parse(detail.process);
        this.groupId = detail.groupId;
        this.loadForm(detail);
      });
    },
    preview() {
      this.$message.info('敬请期待...');
    },
  },
  created() {
    this.loadInitFrom();
    this.groupId = `${this.$route.query.groupId}`;
    if (Number.isNaN(this.groupId)) {
      this.groupId = null;
    }
    if (!isEmpty(this.$route.query.templateId)) {
      this.isNew = false;
      this.loadTemplateDetail(this.$route.query.templateId);
    }
  },
  beforeDestroy() {
    this.stopTimer();
  },
};
</script>

<style scoped lang="less">
.workflow-create {
  .publish .ant-btn {
    margin-right: 12px;
  }

  .ant-tabs-nav {
    padding: 16px 16px 0;
  }

  .ant-tabs-tabpane {
    display: flex;
    justify-content: center;
  }
}

/* 定义旋转动画 */
@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.loading-icon {
  animation: rotate 1.5s infinite linear;
  font-size: 30px;
}

.err-info {
  max-height: 180px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.err-info__item {
  padding: 2px;
  margin: 2px 0;
  width: 220px;
  text-align: left;
  border-radius: 3px;
  color: #606266;
  background: #f2f2f2;
}
</style>
