<template>
  <div>
    <x-add-form
      :json-data="xAddFormDefine"
      :modify-model-data="xAddFormData"
      :visible.sync="xAddFormVisible"
      @onSubmit="xAddFormSubmit"/>
    <!--   上方流程显示   -->
    <a-card :bordered="false" :loading="loading" title="项目进度">
      <!--  项目进度流程  -->
      <work-flow-timeline
        :current-step-id="currentStepId"
        :active-step-id="activeStepId"
        :workflow-id="workflowId"
        :steps="stepsForChild"
        :state="workflowState"
        change-able
        @activeStep="activeStep"/>
    </a-card>
    <!--  如果不是当前步骤，显示历史记录  -->
    <a-tabs default-active-key="1" @change="note = ''">
      <a-tab-pane key="1" :tab="!beforeStepActive && !workflowState ? '表单' : '进度详情'">
        <a-card :bordered="false" :loading="loadingHistory">
          <div v-if="beforeStepActive || workflowState">
            <!--   当前步骤无记录   -->
            <div v-show="!formCompletedDataPreview" style="text-align: center">
              <h1>该步骤暂无记录</h1>
            </div>
            <!--   当前步骤历史记录   -->
            <div v-if="formCompletedDataPreview">
              <a-descriptions
                v-show="formCompletedDataPreview.data"
                :column="{ xxl: 4, xl: 3, lg: 3, md: 3, sm: 2, xs: 1 }"
                title="历史记录"
                bordered
              >
                <a-descriptions-item
                  v-for="(value,key) in formCompletedDataPreview.data"
                  :key="key"
                >
                  <span slot="label" style="color: #000">{{ key }}</span>
                  <div style="white-space: pre-wrap">{{ value }}</div>
                </a-descriptions-item>
              </a-descriptions>
              <div v-if="formCompletedDataPreview.note">
                <div class="ant-descriptions-title complete-data-title">备注</div>
                <p style="white-space: pre-wrap">{{ formCompletedDataPreview.note }}</p>
              </div>
              <div v-if="formCompletedDataPreview.images.length">
                <div class="ant-descriptions-title complete-data-title">图片</div>
                <image-item :images="formCompletedDataPreview.images" @preview="handlePreviewFile" />
              </div>
              <div v-if="formCompletedDataPreview.files.length">
                <div class="ant-descriptions-title complete-data-title">附件</div>
                <file-item :files="formCompletedDataPreview.files" @preview="handlePreviewFile" />
              </div>
            </div>
          </div>
          <!-- 如果是当前步骤，填写表单，控制流程等 -->
          <div v-if="!beforeStepActive && !workflowState">
            <div v-if="canSubmit">
              <!-- 退回提示 -->
              <a-alert v-if="currentStep && currentStep.back" type="info" show-icon style="margin-bottom: 14px">
                <div slot="message">
                  <span style="color: #000">被退回</span>
                  <span style="margin-left: 14px; font-size: 14px; color: rgba(0, 0, 0, 0.65)">{{ currentStep.back.f_desc }}</span>
                </div>
                <div slot="description">
                  <div>操作人：{{ currentStep.back.f_operator }}</div>
                  <div>操作时间：{{ currentStep.back.f_date }}</div>
                  <div>退回原因：{{ currentStep.back.f_notes }}</div>
                </div>
              </a-alert>
              <!-- 任务时间提示 -->
              <a-alert
                v-if="taskIsOverdue"
                type="warning"
                message="当前任务已超过限定完成时间，联系发起人修改完成时间后即可提交"
                show-icon
                style="margin-bottom: 14px" />
              <!--    当前步骤，填写表单    -->
              <x-add-native-form
                v-if="stepDefine.length > 0"
                ref="xAddForm"
                :json-data="stepDefine"
                :modify-model-data="formCompletedData"
                @onSubmit="submitForm">
                >
              </x-add-native-form>
              <a-form v-if="!lastStep" label-align="left" :label-col="{ span: 3 }" :wrapper-col="{ span: 13 }">
                <a-form-item v-if="showStepNextBtn" label="操作类型" required>
                  <a-radio-group v-model="operationType" @change="handleOperationTypeChange">
                    <a-radio value="submit">到下一步</a-radio>
                    <a-radio value="skip">{{ stepNextBtnTitle }}</a-radio>
                  </a-radio-group>
                </a-form-item>
                <a-form-item label="指定下一环节处理人" required>
                  <a-select
                    v-model="checkedChargePerson"
                    placeholder="请选择或搜索"
                    :options="chargePersonOptions"
                    show-search
                    style="width: 195px"
                  />
                </a-form-item>
                <a-form-item label="下一环节截止时间" :validate-status="deadlineValidateStatus" :help="deadlineHelp" required>
                  <a-date-picker
                    v-model="deadline"
                    value-format="YYYY-MM-DD HH:mm"
                    format="YYYY-MM-DD HH:mm"
                    :allow-clear="false"
                    :show-today="false"
                    show-time
                    placeholder="请选择"
                    @change="checkDeadline" />
                </a-form-item>
              </a-form>
              <!--     备注信息    -->
              <div class="line"></div>
              <a-textarea
                v-model="note"
                :auto-size="{ minRows: 3, maxRows: 5 }"
                placeholder="添加备注"
              />
              <!--  当前步骤完成后，控制流程按钮  -->
              <div style="text-align: center">
                <a-radio-group style="margin-top: 20px">
                  <a-space>
                    <a-popover v-if="operationType === 'submit'">
                      <template slot="content">
                        <p>{{ nextBtnTitle }}</p>
                      </template>
                      <a-button
                        v-show="!lastStep"
                        :disabled="!showNextBtn && !stepDone"
                        type="primary"
                        @click="nextClick"
                      >
                        提交
                        <a-icon type="right"/>
                      </a-button>
                    </a-popover>
                    <a-popover v-else :title="stepNextBtnTitle">
                      <template slot="content">
                        <p v-for="(item,index) in stepNextBtnText" :key="index">{{ item }}</p>
                      </template>
                      <a-button
                        v-if="showStepNextBtn && !lastStep"
                        type="primary"
                        @click="stepNextClick"
                      >
                        跳跃
                      </a-button>
                    </a-popover>
                    <a-button
                      v-show="lastStep"
                      type="primary"
                      @click="lastStepNextClick"
                    >
                      确认完工
                    </a-button>
                  </a-space>
                </a-radio-group>
              </div>
            </div>
            <p v-else style="font-size:16px">
              <a-icon type="info-circle" />
              <span style="margin-left:6px">无权操作</span>
            </p>
          </div>
        </a-card>
      </a-tab-pane>
      <!-- 退回 -->
      <a-tab-pane v-if="canSubmit && !beforeStepActive && showPrevBtn && !workflowState" key="2" tab="退回">
        <a-form layout="vertical">
          <a-form-item label="退回原因" :wrapper-col="{ span: 10 }" required>
            <a-textarea
              v-model="note"
              :auto-size="{ minRows: 4, maxRows: 10 }"
              placeholder="请填写退回原因 / 备注"
            />
          </a-form-item>
          <a-form-item :wrapper-col="{ offset: 4 }">
            <a-popover :title="preBtnTitle">
              <template slot="content">
                <p v-for="(item,index) in preBtnText" :key="index">{{ item }}</p>
              </template>
              <a-button
                type="danger"
                @click="preClick"
              >
                <a-icon type="left"/>
                退回
              </a-button>
            </a-popover>
          </a-form-item>
        </a-form>
      </a-tab-pane>
      <a-tab-pane v-if="currentStepSubTableDefine" key="2" tab="当前步骤子表">
        <!--   子表内容   -->
        <a-card :bordered="false">
          <x-form-table
            ref="xFormTable"
            :queryParamsJson="currentStepSubTableDefine"
            title="业务名称"
          >
          </x-form-table>
        </a-card>
      </a-tab-pane>
      <a-tab-pane v-if="canSubmit && !beforeStepActive && showPrevBtn && !workflowState" key="3" tab="工单拆分">
        <!--   分配工单   -->
        <workflow-list-resolution :workflow-project-id="workflowId" :details="details"></workflow-list-resolution>
      </a-tab-pane>
    </a-tabs>
    <!-- 文件预览 -->
    <a-modal v-model="previewFileVisible" :footer="null" :dialog-style="{ top: '20px' }" width="85%" :z-index="1001">
      <file-preview :path="filePath" />
    </a-modal>
  </div>
</template>

<script>
import XAddNativeForm from '@vue2-client/base-client/components/common/XAddNativeForm/XAddNativeForm'
import XFormTable from '@vue2-client/base-client/components/common/XFormTable/XFormTable'
import XAddForm from '@vue2-client/base-client/components/common/XAddForm/XAddForm'
import { post, postByServiceName } from '@vue2-client/services/api/restTools'
import { workFlowViewApi } from '@vue2-client/services/api/workFlow'
import { formatDate } from '@vue2-client/utils/util'
import { commonApi } from '@vue2-client/services/api/common'
import { mapState } from 'vuex'
import moment from 'moment'
import FilePreview from '@vue2-client/components/FilePreview'
import { FileItem, ImageItem } from '@vue2-client/components/FileImageItem'
import WorkflowListResolution from './WorkflowListResolution'

export default {
  name: 'ApplyHandle',
  components: {
    WorkflowListResolution,
    XAddNativeForm,
    XFormTable,
    XAddForm,
    FilePreview,
    FileItem,
    ImageItem
  },
  computed: {
    ...mapState('account', { currUser: 'user' }),
    canSubmit () {
      if (isDevelopment) {
        return true
      }
      const step = this.stepsForChild.find(item => item.id === this.currentStepId)
      if (step && step.handler) {
        return step.handler.includes(this.currUser.name)
      }
      return false
    }
  },
  data () {
    return {
      // 子表查询配置
      queryParamsJson: {},
      // 显示供用户填写的当前步骤表单
      showForm: false,
      // 当前步骤表单标题
      formTitle: '',
      // 当前步骤表单定义Json
      stepDefine: [],
      // 当前步骤
      currentStep: undefined,
      // 当前步骤完成状态
      stepDone: false,
      // 所有节点连通数据
      directions: [],
      // 所有流程定义数据
      stepsDefine: [],
      // 当前步骤能通向的节点
      currentDirections: [],
      // 当前节点id
      currentStepId: undefined,
      // 当前活动节点 id
      activeStepId: 1,
      // 下一步按钮显示
      showNextBtn: false,
      // 回退按钮显示
      showPrevBtn: false,
      // 跳过按钮显示
      showStepNextBtn: false,
      // 定义三个按钮气泡提示内容
      preBtnTitle: '',
      preBtnText: [],
      nextBtnTitle: '',
      stepNextBtnTitle: '',
      stepNextBtnText: [],
      // 控制三个按钮跳转目标
      preBtnTo: undefined,
      nextBtnTo: undefined,
      stepNextBtnTo: undefined,
      // 控制当前标签页显示
      activeKey: '1',
      // 之前的节点是否激活
      beforeStepActive: false,
      // 之前节点中的数据
      beforeStepData: [],
      // 用于将已有数据，填回x-add表单中
      formCompletedData: {},
      // 用于展示提交的数据
      formCompletedDataPreview: null,
      // 切换至目标流程时，目标流程定义
      targetStepDefine: [],
      // 控制历史记录加载
      loadingHistory: true,
      // 控制表单校验
      formValid: false,
      // 备忘
      note: '',
      // 是否是最后一步
      lastStep: false,
      // 存储每一步骤填表人和时间数据
      stepsExtraInfo: [],
      // 控制基础信息页流程展示加载
      loading: true,
      // 当前步骤子表定义
      currentStepSubTableDefine: null,
      // 子表定义
      subTableDefine: {},
      subTableName: '',
      xAddFormVisible: false,
      xAddFormData: {},
      xAddFormDefine: [],
      subTableData: {},
      // 修改子表数据，对应的id
      editSubTableId: undefined,
      // 激活的步骤名
      activeStepName: '',
      stepsParse: undefined,
      // 下一步处理人选择框数据
      chargePersonOptions: [],
      // 已选择下一步处理人
      checkedChargePerson: undefined,
      // 下一步截止时间
      deadline: this.getDefaultDeadline(),
      deadlineValidateStatus: '',
      deadlineHelp: '',
      // 当前任务是否延期
      taskIsOverdue: moment().isAfter(this.completeTime, 'day'),
      // 人员信息
      empTree: [],
      // 预览图片弹框
      previewFileVisible: false,
      filePath: '',
      // 操作类型，提交到下一步或跳过
      operationType: 'submit',
      // 获取微信推送是否成功信息
      information: []
    }
  },
  async mounted () {
    this.init()
    this.checkDeadline()
  },
  props: {
    workflowId: {
      type: String,
      required: true
    },
    visible: {
      type: Boolean,
      default: false
    },
    stepsForChild: {
      type: Array,
      required: true
    },
    workflowState: {
      type: [Boolean, Number],
      required: true
    },
    completeTime: {
      type: String,
      required: true
    },
    taskName: {
      type: String,
      required: true
    },
    details: {
      type: Object,
      required: true
    }
  },
  methods: {
    init () {
      this.getCurrentStep()
    },
    onClose () {
      this.activeStepId = this.currentStepId
      this.checkedChargePerson = undefined
      this.loadingHistory = true
      this.currentStepId = undefined
      this.directions = []
      this.currentDirections = []
      this.preBtnText = []
      this.stepNextBtnText = []
      this.stepsExtraInfo = []
      this.editSubTableId = undefined
      this.currentStepSubTableDefine = null
      this.loading = true
      this.showNextBtn = false
      this.showStepNextBtn = false
      this.showPrevBtn = false
      this.stepDone = false
      this.subTableName = ''
      this.formCompletedData = {}
      this.formCompletedDataPreview = null
      this.operationType = 'submit'
    },
    // 修改模态框，提交
    xAddFormSubmit (source) {
      if (source.valid) {
        const form = source.form
        const formatForm = []
        const keys = Object.keys(form)
        const values = Object.values(form)
        for (let i = 0; i < keys.length; i++) {
          const temp = {}
          temp.label = keys[i]
          temp.value = values[i]
          formatForm.push(temp)
        }
      }
    },
    // 获取单个步骤的定义
    getSingleStepDefine (name) {
      for (const step of this.stepsDefine) {
        if (name === step.name) {
          return step.properties.formData
        }
      }
    },
    // 日期格式化
    format (date, format) {
      return formatDate(date, format)
    },
    // 获取当前步骤
    getCurrentStep () {
      return postByServiceName(workFlowViewApi.getWorkFlowCurrentSubState, {
        workflowId: this.workflowId
      })
        .then(res => {
          res.state = this.stepsForChild.find(item => item.id === res.id)?.name
          this.currentStep = res
          this.getDirection()
        }, err => {
          console.log(err)
        })
    },
    // 判断id是否为流程中最后一个
    isLastStep (stepId) {
      const lastStepId = this.stepsDefine[this.stepsDefine.length - 1].id
      this.lastStep = stepId === lastStepId
    },
    // 完工按钮
    async lastStepNextClick () {
      await this.$refs.xAddForm.onSubmit()
      if (this.formValid) {
        return postByServiceName(workFlowViewApi.afterWorkFlowFinalStepSubmit, {
          workflowId: this.workflowId
        })
          .then(
            res => {
              this.saveWorkflowLog('确认完工', '最后一步: ' + this.getStepNameByStepId(this.currentStepId), { notes: this.note.trim() })
              this.$message.success('已完工！')
              this.loading = true
              this.loadingHistory = true
              this.onClose()
              this.init()
              this.$emit('refresh')
            },
            err => {
              this.$message.error('提交失败！')
              console.log(err)
            }
          )
      }
    },
    // 三个按钮点击后逻辑
    async nextClick () {
      const extraData = this.getApplyStepExtraData(this.nextBtnTo)
      if (!extraData) {
        return
      }
      await new Promise(resolve => {
        this.$confirm({
          title: '提交确认',
          content: '确定提交么？提交之后数据不可更改！',
          onOk () {
            resolve()
            return Promise.resolve()
          }
        })
      })
      await this.$refs.xAddForm.onSubmit()
      if (this.formValid) {
        return postByServiceName(workFlowViewApi.submitToNextStep, extraData)
          .then(
            res => {
              const extra = {
                setHandler: this.getStepHandler(),
                setDeadline: this.deadline,
                notes: this.note.trim()
              }
              console.log('备注')
              console.log(this.note.trim())
              console.log(this.nextBtnTo)
              this.saveWorkflowLog('提交', this.generateStepChangeText(this.currentStepId, this.nextBtnTo), extra)
              this.$message.success('提交成功')
              this.loading = true
              this.loadingHistory = true
              this.$emit('refresh')
              this.onClose()
              this.init()
              console.log('提交人' + this.checkedChargePerson)
            },
            err => {
              this.$message.error('提交失败！')
              console.log(err)
            }
          )
      }
    },
    async preClick () {
      const notes = this.note.trim()
      if (!notes) {
        this.$message.error('退回请在备注中填写理由')
        return
      }
      return postByServiceName(workFlowViewApi.updateApplySubState, {
        stepId: this.preBtnTo,
        workflowId: this.workflowId
      })
        .then(
          res => {
            this.sendBackPush()
            this.saveWorkflowLog('退回', this.generateStepChangeText(this.currentStepId, this.preBtnTo), { notes })
            this.$message.success('退回成功')
            this.loading = true
            this.loadingHistory = true
            this.$emit('refresh')
            this.onClose()
            this.init()
          },
          err => {
            this.$message.error('退回失败！')
            console.log(err)
          }
        )
    },
    // 退回推送
    sendBackPush () {
      const dataPush = this.stepsForChild
      let backName = null
      let backNameId = null
      this.currentDirections.forEach(res => {
        if (res.type === 'back') {
          backNameId = (parseInt(res.tail) - 1)
        }
      })
      backName = dataPush[backNameId].handler
      // 微信推送
      postByServiceName(workFlowViewApi.saveWatchData, {
        first: '工单退回',
        keyword1: this.workflowId + '(' + this.details.f_entry_name + ')',
        keyword2: this.details.f_workflow_define_name + '-' + this.details.f_sub_state,
        keyword3: '',
        keyword4: this.currUser.name + '工单退回给' + backName,
        remark: this.note.trim(),
        name: backName,
        operator: this.currUser.name
      }).then(res => {
        this.information = res
        if (this.information.code === 200) {
          this.$message.success(this.information.msg)
        } else {
          this.$message.info(this.information.msg)
        }
      })
    },
    async stepNextClick () {
      const extraData = this.getApplyStepExtraData(this.stepNextBtnTo)
      if (!extraData) {
        return
      }
      await this.$refs.xAddForm.onSubmit()
      if (this.formValid) {
        return postByServiceName(workFlowViewApi.submitToNextStep, extraData)
          .then(
            res => {
              const extra = {
                setHandler: this.getStepHandler(),
                setDeadline: this.deadline,
                notes: this.note.trim()
              }
              this.saveWorkflowLog('跳过', this.generateStepChangeText(this.currentStepId, this.stepNextBtnTo), extra)
              this.$message.success('提交成功')
              this.loading = true
              this.loadingHistory = true
              this.$emit('refresh')
              this.onClose()
              this.init()
            },
            err => {
              this.$message.error('提交失败！')
              console.log(err)
            }
          )
      }
    },
    // 获取当前步骤节点，连通的节点
    getDirection () {
      // 获取流程定义
      return postByServiceName(workFlowViewApi.getApplyWorkflowDefine, {
        id: this.workflowId
      })
        .then(res => {
          console.log('res====', res)
          console.log('res====', res.data)
          console.log('res====', res.data.value)
          console.log('res====', res.data.value.directions)
          this.directions = res.data.value.directions
          this.stepsDefine = res.data.value.steps
          this.resolveDirections()
          this.resolveStep()
        }, err => {
          console.log(err)
        })
    },
    // 分析当前节点，能通向的节点
    resolveDirections () {
      for (let i = 0; i < this.stepsDefine.length; i++) {
        if (this.stepsDefine[i].name === this.currentStep.state) {
          this.currentStepId = this.stepsDefine[i].id
        }
      }
      this.getSubTableDefine(this.currentStepId)
      let hasBack = false
      this.currentDirections = this.directions.filter((item) => {
        if (item.head === this.currentStepId && item.type === 'back') {
          hasBack = true
        }
        return item.head === this.currentStepId
      })
      // 默认可退回到上一步
      if (!hasBack && this.currentStepId !== 1) {
        this.currentDirections.push({ head: this.currentStepId, tail: this.currentStepId - 1, type: 'back' })
      }
      this.isLastStep(this.currentStepId)
      if (!this.lastStep) {
        this.setChargePersonOptions(this.currentStepId + 1)
      }
      this.workflowControl()
    },
    // 根据步骤id获取步骤名称
    getStepNameByStepId (stepId) {
      return this.stepsDefine.find(item => item.id === stepId)?.name
    },
    // 表单提交的回调
    submitForm (obj) {
      if (!obj.valid) {
        // 这里返回false是在表单校验不通过时，打断步骤的跳转
        this.formValid = false
      } else {
        this.formValid = true
        const formData = obj.form
        const time = this.format(new Date(), 'yyyy-MM-dd hh:mm:ss')
        return postByServiceName(workFlowViewApi.saveApplyStepFormData, {
          workflowId: this.workflowId,
          stepId: this.currentStepId,
          form: formData,
          data: time,
          handler: this.currUser.name,
          note: this.note.trim()
        })
          .then(
            res => {
              console.log('表单提交成功')
              this.note = ''
              this.showForm = false
              this.stepDone = true
            },
            err => {
              this.$message.error('保存失败，请检查后重试')
              console.log(err)
            }
          )
      }
    },
    // 打开填写表单，获取当前步骤定义内容，生成表单
    openForm () {
      const define = this.getSingleStepDefine(this.currentStep.state)
      return postByServiceName(commonApi.getColumnsJson, { queryObject: define }).then(res => {
        this.stepDefine = res.formJson
        this.showForm = true
      })
        .then(res => {
          this.loadingHistory = false
        })
    },
    // 获取子表定义
    getSubTableDefine (stepId) {
      const stepName = this.getStepNameByStepId(stepId)
      const define = this.getSubTableDefineLocal(stepName)
      if (define !== undefined) {
        if (define.tableName !== undefined) {
          this.subTableName = define.tableName.split(' ')[0]
          this.currentStepSubTableDefine = define
          // 为配置参数添加当前报建ID和步骤名称
          this.currentStepSubTableDefine.workflowId = this.workflowId
          this.currentStepSubTableDefine.stepName = this.activeStepName
        }
      }
    },
    // 根据当前节点，判断之后流程，以及按钮的显示
    workflowControl () {
      for (const direction of this.currentDirections) {
        if (direction.type === 'submit') {
          this.showNextBtn = true
          this.nextBtnTo = direction.tail
          this.nextBtnTitle = '进行下一环节：' + this.getStepNameByStepId(direction.tail)
        } else if (direction.type === 'skip') {
          this.showStepNextBtn = true
          this.stepNextBtnTo = direction.tail
          this.stepNextBtnTitle = '跳至：' + this.getStepNameByStepId(direction.tail) + '环节'
          this.stepNextBtnText.push('将跳过以下环节：')
          for (let i = this.currentStepId; i < direction.tail - 1; i++) {
            this.stepNextBtnText.push(this.stepsDefine[i].name)
          }
        } else if (direction.type === 'back') {
          for (let i = this.currentStepId - 1; i > 0; i--) {
            if (direction.tail >= i && this.stepsForChild.find(item => item.id === i)?.handler) {
              this.preBtnTo = i
              this.preBtnTitle = '回退至：' + this.getStepNameByStepId(i) + '环节'
              this.showPrevBtn = true
              break
            } else {
              this.preBtnText.push(this.getStepNameByStepId(i))
            }
          }
          if (this.preBtnText.length) {
            this.preBtnText.unshift('将跳过以下环节：')
          }
        }
      }
    },
    // 加载完成
    resolveStep () {
      this.loading = false
    },
    // 流程图组件给当前组件传值用，stepNo为用户点击的非当前步骤
    async activeStep (stepId) {
      // 开启加载
      this.loadingHistory = true
      // 获取激活节点的步骤名
      this.activeStepName = this.getStepNameByStepId(stepId)
      // 清空回显数据
      this.formCompletedData = {}
      // 获取激活节点历史数据，和字段定义
      await this.getCompletedFormData(stepId)
      this.getStepDefine(stepId)
      // 获取当前激活节点子表
      this.currentStepSubTableDefine = undefined
      await this.getSubTableDefine(stepId)
      // 将回显数据拷贝，避免引用传递
      let formCompletedDataPreview = JSON.parse(JSON.stringify(this.formCompletedData))
      // 判断激活的节点，是不是待完成节点
      if (this.activeStepName !== this.currentStep.state || this.workflowState) {
        // 使用字段定义中内容，将回显数据的列名，替换为定义的中文名
        const formData = formCompletedDataPreview.data
        for (const key in formData) {
          for (let i = 0; i < this.targetStepDefine.length; i++) {
            const stepDefine = this.targetStepDefine[i]
            if (key === stepDefine.key) {
              if (!['FilesId', 'Images'].includes(key)) {
                let value = formData[key]
                // 读取字典值
                if (stepDefine.formType === 'select') {
                  let dictList
                  if (stepDefine.selectType === 'key') {
                    dictList = await this.$appdata.getDictByKeyAsync(stepDefine.selectKey)
                  } else if (stepDefine.selectType === 'config') {
                    const configName = stepDefine.selectKey.substring(7)
                    dictList = await this.$appdata.getDictByKeyAsync(configName)
                  }
                  const dictItem = dictList.find(item => item.value === value)
                  value = dictItem ? dictItem.label : value
                }
                formData[stepDefine.title] = value
              }
              if (key !== stepDefine.title) {
                delete formData[key]
              }
              break
            }
          }
        }
        if (!Object.keys(formCompletedDataPreview.data).length) {
          formCompletedDataPreview.data = null
        }
        // 备注
        formCompletedDataPreview.note = this.stepsForChild.find(item => item.id === stepId)?.note
        if (!formCompletedDataPreview.data && !formCompletedDataPreview.files.length && !formCompletedDataPreview.images.length && !formCompletedDataPreview.note) {
          formCompletedDataPreview = null
        }
        this.formCompletedDataPreview = formCompletedDataPreview
        // 完成
        this.loadingHistory = false
        this.beforeStepActive = this.activeStepName !== this.currentStep.state
      } else {
        this.loadingHistory = false
        this.beforeStepActive = false
      }
    },
    // 获取已经完成步骤的数据
    getCompletedFormData (stepId) {
      return postByServiceName(workFlowViewApi.getApplyCompletedStepData, {
        workflowId: this.workflowId,
        stepId: stepId
      })
        .then(
          res => {
            this.formCompletedData = res
            this.openForm()
          },
          err => {
            console.log(err)
          }
        )
    },
    // 获取步骤定义表中，当前步骤定义
    getStepDefine (stepId) {
      const stepName = this.getStepNameByStepId(stepId)
      this.targetStepDefine = this.getSingleStepDefine(stepName).column
    },
    // 获取指定步骤额外数据
    getApplyStepExtraData (stepId) {
      if (!this.checkDeadline(true)) {
        return false
      }
      const stepHandler = this.getStepHandler()
      if (!stepHandler) {
        this.$message.error('请设置下一环节处理人')
        return false
      }
      return {
        workflowId: this.workflowId,
        stepId,
        name: this.getStepNameByStepId(stepId),
        handler: stepHandler,
        deadline: this.deadline
      }
    },
    // 获取当前选择的负责人
    getStepHandler () {
      let stepHandler
      if (this.checkedChargePerson) {
        stepHandler = this.checkedChargePerson.split('_')[0]
      }
      return stepHandler
    },
    // 生成工作流日志步骤变化描述
    generateStepChangeText (formStepId, toStepId) {
      return `第${formStepId}步: ${this.getStepNameByStepId(formStepId)} --> 第${toStepId}步: ${this.getStepNameByStepId(toStepId)}`
    },
    // 保存工作流日志
    saveWorkflowLog (operation, desc, extra) {
      postByServiceName(workFlowViewApi.saveApplyWorkflowLog, {
        workflowId: this.workflowId,
        operation,
        desc,
        operator: this.currUser.name,
        notes: '',
        setHandler: '',
        setDeadline: '',
        ...extra
      })
    },
    // 文件预览
    handlePreviewFile (url) {
      this.filePath = url
      this.previewFileVisible = true
    },
    // 获取默认截止时间
    getDefaultDeadline () {
      const date = new Date()
      date.setDate(date.getDate() + 1)
      date.setHours(date.getHours() + 2)
      return formatDate(date, 'yyyy-MM-dd hh:mm')
    },
    // 验证截止时间
    checkDeadline (alert) {
      const deadline = moment(this.deadline)
      if (deadline.isAfter(this.completeTime, 'day')) {
        this.deadlineValidateStatus = 'error'
        this.deadlineHelp = '不能超过任务限定完成时间'
        if (alert) {
          this.$message.error('下一环节截止时间不能超过任务限定完成时间，如需设置，请联系发起人修改任务完成时间', 5)
        }
        return false
      }
      if (deadline.diff(moment(), 'hours') < 1) {
        this.deadlineValidateStatus = 'error'
        this.deadlineHelp = '下一环节截止时间只能在1小时之后'
        return false
      }
      this.deadlineValidateStatus = 'success'
      this.deadlineHelp = ''
      return true
    },
    // 操作类型单选按钮改变时重新设置负责人选择框
    handleOperationTypeChange (event) {
      this.checkedChargePerson = undefined
      if (event.target.value === 'submit') {
        this.setChargePersonOptions(this.nextBtnTo)
      } else {
        this.setChargePersonOptions(this.stepNextBtnTo)
      }
    },
    // 从指定步骤设置负责人下拉选择框
    async setChargePersonOptions (stepId) {
      this.checkedChargePerson = undefined
      const defineProperties = this.stepsDefine.find(item => item.id === stepId).properties
      const chargePerson = defineProperties.chargePerson
      let chargePersonOptions = []
      // 获取所有用户信息
      const allUser = await post(commonApi.getAllUserOptionList, {})
      if (chargePerson.role) {
        // 根据角色获取人员
        chargePersonOptions = allUser.filter(item => item.rolestr && item.rolestr.includes(chargePerson.role)).map(item => {
          return { label: item.label, value: item.label }
        })
      } else if (chargePerson.department) {
        // 根据部门获取人员
        chargePersonOptions = allUser.filter(item => item.depname === chargePerson.department).map(item => {
          return { label: item.label, value: item.label }
        })
      }
      this.chargePersonOptions = chargePersonOptions
      // 默认选中下一环节负责人
      if (this.chargePersonOptions.length === 1) {
        this.checkedChargePerson = this.chargePersonOptions[0].key
      }
    }
  },
  watch: {
    visible (newVal) {
      if (newVal) {
        this.init()
      }
    }
  }
}
// 是否开发环境
const isDevelopment = process.env.NODE_ENV === 'development'
</script>
<style lang="less" scoped>
.line {
  width: 100%;
  height: 5px;
  border-bottom: rgb(240, 240, 240) solid 1px;
  margin-bottom: 30px;
}
.complete-data-title {
  margin-top: 8px;
  margin-bottom: 8px;
}
</style>
