<template>
  <div>
    <el-dialog
      fullscreen
      :visible="dialogVisible"
      custom-class="simple-flow-dialog"
      :show-close="false"
    >
      <div class="simple-flow-header" slot="title">
        <el-button
          @click="closeDialog"
          type="primary"
          icon="el-icon-arrow-left"
          circle
          class="simple-flow-header_left"
        ></el-button>
        <ul>
          <li
            v-for="(item, index) in headerTabs"
            :key="index"
            :class="{active: activeName === item.key}"
            @click="handleTab(item)"
          >
            {{ item.text }}
          </li>
        </ul>
      </div>
      <div class="simple-flow-content">
        <!--建模表单-->
        <business-obj-dialog-simple
          ref="objDialog"
          :clickTree="clickTree"
          v-show="activeName == 'model'"
          :modelAlias="modelAlias"
          :data="modelDetail"
          :dataView="dataView"
          @publishSuccess="publishSuccess"
        ></business-obj-dialog-simple>
        <!-- 表单 -->
        <form-designer-simple
          v-if="activeName == 'form' && isFormShow"
          :form-type="formType"
          :form-id.sync="formId"
          :form-def-id.sync="formDefId"
          :add-bpm-form="bpmForm"
          :bos="bpmForm.bos"
          :formAlias="formAlias"
          ref="formDesignerSimpleRef"
          class="simple-form-designer"
          @switchForm="switchForm"
          @updateForm="updateForm"
        />
        <!-- 流程新增 -->

        <BpmnEdit
          v-if="activeName == 'flow'"
          :flowData="flowData"
          class="simple-flow"
          :defId="curSelectDefId"
          design-pattern="simple"
          @def-deploy-success="handleDefDeploySuccess"
          @switch-config-refresh="handleDefSignSuccess"
        />
        <!-- 流程配置 -->
        <simple-flow-config
          v-if="activeName == 'flowConfig'"
          :defId="curSelectDefId"
          :pcFormData="pcFormData"
          :mobileFormData="mobileFormData"
        ></simple-flow-config>
      </div>
    </el-dialog>
    <form-template-dialog
      v-if="dialogVisible"
      @onConfirm="confirmTemplate"
      formType="pc"
      ref="formTemplateDialog"
    />
  </div>
</template>

<script>
import form from '@/api/form.js'
import flow from '@/api/flow.js'
const BusinessObjDialogSimple = () =>
  import('@/views/form/BusinessObjDialogSimple.vue')
const FormDesignerSimple = () =>
  import('@/components/form/FormDesignerSimple.vue')
const SimpleFlowConfig = () =>
  import('@/views/flow/simpleFlow/SimpleFlowConfig.vue')
const BpmnEdit = () => import('@/components/VueBpmn/BpmnEdit.vue')
const FormTemplateDialog = () =>
  import('@/components/dialog/FormTemplateDialog.vue')

export default {
  components: {
    BusinessObjDialogSimple,
    FormDesignerSimple,
    SimpleFlowConfig,
    BpmnEdit,
    FormTemplateDialog
  },
  props: {
    flowData: Object
  },
  data() {
    return {
      isFlowPublish: false,
      isFormShow: true,
      formType: 'pc',
      mobileFormData: null,
      pcFormData: null, // 表单详情
      dataView: {id: '', type: ''},
      modelDetail: null, // 建模具体数据
      currentStep: 1,
      curSelectDefId: '', // 流程id
      bpmForm: {
        formKey: '',
        bos: '',
        desc: '',
        templateConf: {},
        formType: 'pc'
      },
      formId: '',
      formDefId: '',
      formEditorDialogVisible: false,
      clickTree: {id: '', name: ''},
      opretaId: '',
      dialogVisible: false,
      headerTabs: [
        {text: '①建模', key: 'model', step: 1},
        {text: '②表单设计', key: 'form', step: 2},
        {text: '③流程设计', key: 'flow', step: 3},
        {text: '④流程配置', key: 'flowConfig', step: 4}
      ],
      activeName: ''
    }
  },
  computed: {
    modelAlias() {
      return this.flowData.alias + 'BoDef'
    },
    formAlias() {
      return this.flowData.alias + 'Form'
    }
  },
  created() {
    this.initData()
  },
  methods: {
    // 选择生成表单的模板
    confirmTemplate(templateModel) {
      // 已选择模板
      if(templateModel){
        this.bpmForm.bos = [this.modelDetail]
        this.bpmForm.templateConf = templateModel
      }else{
        // 空模板
        this.bpmForm.bos = [this.modelDetail]
        this.bpmForm.templateConf = {}
      }
      this.bpmForm.formType = 'pc'
      this.activeName = 'form'
    },
    closeDialog() {
      this.dialogVisible = false
      this.$emit('update:isSimpleFlowShow', false)
    },
    updateForm(data) {
      if (this.formType == 'pc') {
        this.pcFormData = data
        this.formId = data.id
        this.formDefId = data.defId
      }
      if (this.formType == 'mobile') {
        this.mobileFormData = data
        this.formId = data.id
        this.formDefId = data.defId
      }
    },
    // 流程保存成功
    handleDefSignSuccess(data) {},
    // 发布流程成功
    handleDefDeploySuccess() {
      this.isFlowPublish = true
      this.getFlowDetail('reset')
    },
    async switchForm() {
      // 如果是pc 切换移动端表单 需掉用接口生成移动端表单
      if (this.formType == 'pc') {
        let result = await this.getMobileDetail()
        if (result) {
          this.formType = 'mobile'
          this.bpmForm = result
          this.formId = this.mobileFormData.formId || this.mobileFormData.id
          this.formDefId = this.mobileFormData.defId
          this.reloadForm()
        }
        return
      }
      if (this.formType == 'mobile') {
        let pcResult = await this.getFormDetail()
        if (pcResult) {
          this.formType = 'pc'
          this.bpmForm = pcResult
          this.formId = this.pcFormData.formId || this.pcFormData.id
          this.formDefId = this.pcFormData.defId
          this.reloadForm()
        }
      }
    },
    reloadForm() {
      this.isFormShow = false
      this.$nextTick(() => {
        this.isFormShow = true
      })
    },
    async getMobileDetail() {
      return new Promise(resolve => {
        flow.getMobileDetailByAlias(this.pcFormData.formKey).then(res => {
          if (res.data) {
            this.mobileFormData = res.data
            resolve(res.data)
          } else {
            resolve(false)
          }
        })
      })
    },
    // 建模成功
    publishSuccess(data) {
      // 发布成功
      if (data && data.state) {
        // 获取建模具体数据
        form.getEntData(data.message, resp => {
          if (resp.data) {
            this.modelDetail = resp.data
            // 建模成功后弹出是否初始化模板
            this.$refs.formTemplateDialog.showDialog(this.modelDetail.id);
          }
        })
      }
      // 保存成功需要重新获取最新数据
      if (!data) {
        this.$message.success('保存成功!')
        this.getModelDetail()
      }
    },
    initData() {
      this.getModelDetail()
      this.activeName = ''
      this.dialogVisible = true
      this.$nextTick(() => {
        this.handleTab(this.headerTabs[0])
      })
      // 获取表单数据
      this.getFormDetail('init')
    },
    // 获取建模详情
    getModelDetail() {
      return new Promise(resolve => {
        flow.getModelDetailByAlias(this.modelAlias).then(res => {
          if (res && res.data) {
            // 如果已存在建模数据 就为编辑
            this.dataView = {id: res.data.id, type: 'edit'}
            this.modelDetail = res.data
            return
          }
          this.dataView = {id: '', type: ''}
        })
      })
    },
    async handleTab(item) {
      if (this.activeName === item.key) {
        return
      }
      if (item.key === 'form') {
        // 判断是否可以点form并赋值
        if (!this.modelDetail) {
          this.$message('请先发布建模！')
          return
        }
        // 判断是否已经存在表单
        let result = await this.getFormDetail()
        // 如果存在就是编辑 否则是新增
        if (result) {
          this.bpmForm.bos = []
        } else {
          this.$refs.formTemplateDialog.showDialog(this.modelDetail.id)
          return
        }
      }
      // 需判断是否已存在发布的表单，才能编辑流程
      if (item.key === 'flow') {
        if (!this.pcFormData) {
          this.$message('请先编辑发布表单！')
          return
        }
        // 判断是否已经发布流程
        await this.getFlowDetail()
      }
      // 需判断流程是否存在且已发布
      if (item.key === 'flowConfig') {
        await this.getFlowDetail()
        if (
          (!this.curSelectDefId ||
            (this.flowDetail && this.flowDetail.version < 1)) &&
          !this.isFlowPublish
        ) {
          this.$message.info('请先发布流程!')
          return
        }
      }
      this.activeName = item.key
    },
    // 获取表单详情
    async getFormDetail(type) {
      return new Promise(resolve => {
        if (this.pcFormData) {
          resolve(this.pcFormData)
          return
        }
        flow.getFormDetailByAlias(this.formAlias).then(res => {
          if (res && res.data) {
            this.pcFormData = res.data
            this.formId = res.data.formId
            this.formDefId = res.data.defId
            if (type == 'init') {
              this.getMobileDetail()
            }
            resolve(res.data)
            return
          }
          // 表单新增
          resolve(false)
        })
      })
    },
    // 获取流程详情
    async getFlowDetail(type = '') {
      return new Promise(resolve => {
        if (this.flowDetail && type != 'reset') {
          this.curSelectDefId = this.flowDetail.defId
          resolve(this.flowDetail)
          return
        }
        flow.getFlowImageByAlias(this.flowData.alias).then(res => {
          if (res && res.data) {
            this.flowDetail = res.data
            this.curSelectDefId = this.flowDetail.defId
            resolve(res.data)
            return
          }
          // 表单新增
          resolve(false)
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .simple-flow-dialog {
  background: #e8e8e8;
  > .el-dialog__header {
    padding: 0;
  }
  .el-dialog__body {
    padding: 0;
    height: calc(100% - 62px);
  }
  .simple-flow-header {
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    background: #fff;

    .simple-flow-header_left {
      position: absolute;
      left: 20px;
    }
    ul {
      list-style: none;
      display: flex;
      align-items: center;
      li {
        border-bottom: 2px solid transparent;
        color: #909399;
        padding: 0 20px;
        height: 60px;
        line-height: 60px;
        cursor: pointer;
        &.active {
          border-bottom-color: rgb(64, 158, 255);
          color: rgb(64, 158, 255);
        }
      }
    }
  }
  .simple-flow-content {
    height: 100%;
    .simple-form-designer {
      height: 100%;
      background: #fff;
      .container__body {
        height: calc(100% - 48px);
      }
    }
  }
}
</style>
