<template>
  <div>
    <a-modal
      :destroy-on-close="true"
      :visible="showInterveneStep"
      title="特送"
      :body-style="{ overflow: 'auto' }"
      :confirm-loading="confirmLoading"
      @ok="handleOkInterveneStep"
      @cancel="() => (showInterveneStep = false)"
    >
      <a-form-model :model="form" :label-col="{ span: 7 }" :wrapper-col="{ span: 15 }">
        <a-form-model-item label="当前处理环节">
          <sd-select v-model="form.begin" :options="curStepOptions" @change="changeCurStep" />
        </a-form-model-item>
        <a-form-model-item label="调整后处理环节">
          <sd-select
            ref="select"
            v-model="form.end"
            :options="selectData"
            :show-arrow="false"
            :open="false"
            @click.native="
              () => {
                $refs.select.blur()
                showFlowChart = true
              }
            "
          ></sd-select>
        </a-form-model-item>
        <a-form-model-item v-show="peopleFlag" label="调整后的处理人">
          <sd-user-picker
            v-model="form.departName"
            :single="false"
            :read-only="false"
            :secret-level="secretLevel"
            :hierarchical="hierarchical"
          />
        </a-form-model-item>
        <a-form-model-item label="特送原因">
          <a-input v-model="form.opinion" type="textarea"></a-input>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <a-modal
      :visible="showFlowChart"
      title="请选择特送环节"
      :body-style="{ overflow: 'auto' }"
      :width="1200"
      :footer="null"
      :wrap-class-name="$style.flowchart"
      @cancel="
        () => {
          showFlowChart = false
        }
      "
    >
      <sd-flowchart
        :key="key"
        :inst-id="sdGet('webflow?.FlowData?.instId')"
        :flow-id="sdGet('webflow?.FlowData?.processId')"
        :node-clickable="true"
        :disabled-nodes="disabledNodes"
        @selectNode="selectNode"
      />
    </a-modal>
  </div>
</template>

<script>
import WorkbenchService from '@/workbench/workbench-service'
import { Message } from 'ant-design-vue'
import FlowService from '../flow-service'
import components from './_import-components/sd-workflow-interfere-step-import'
export default {
  name: 'SdWorkflowInterfereStep',
  metaInfo: {
    title: 'SdWorkflowInterfereStep',
  },
  components,
  data() {
    return {
      showInterveneStep: false,
      currentButton: {},
      stepId: '',
      confirmLoading: false,
      form: {
        layout: 'inline',
        begin: '', // 当前流程
        end: '', // 结束流程
        departName: [], // 流程处理人
        title: '',
        opinion: '',
      },
      selectData: [],
      peopleFlag: true,
      showFlowChart: false,
      disabledNodes: [],
      hierarchical: true,
      key: 0,
    }
  },
  computed: {
    // 选人时要根据密级进行控制
    secretLevel() {
      return this.webflow.getFieldValue('secretLevel')
    },
    curStepOptions() {
      if (this.webflow.FlowData.processActiveLogInfo.length > 0) {
        const options = []
        this.webflow.FlowData.processActiveLogInfo.forEach((item) => {
          if (!options.find((o) => o.id === item.stepId)) {
            options.push({ id: item.stepId, name: item.stepName, activeStepId: item.activeStepId })
          }
        })
        // 从流程环节列表中获取环节对应的中文名称
        return options.map((step) => {
          const name = this.selectData.find((item) => item.id === step.id)?.name
          if (name) {
            step.name = name
          }
          return step
        })
      } else {
        return [{ id: 0, name: '已办结', activeStepId: 0 }]
      }
    },
  },
  methods: {
    run({ button }) {
      return this.getInterveneData().then(() => {
        this.webflow.validateFields().then((flag) => {
          if (flag) {
            this.showInterveneStep = true
            this.currentButton = button
            this.form.end = ''
            this.form.begin = this.curStepOptions.length > 0 ? [this.curStepOptions[0]] : []
            this.form.departName = []
          }
        })
        FlowService.getActionInfo(this.webflow.FlowData, button, this.webflow.getFormData()).then(
          (res) => {
            this.hierarchical = res?.hierarchical !== '0'
          }
        )
      })
    },
    selectChanged(value) {
      this.form.departName = value[0].operators
      if (value[0].type === '结束') {
        this.peopleFlag = false
      } else {
        this.peopleFlag = true
      }
    },
    changeCurStep() {
      // 当前环节修改了，重新请求流程环节列表更新不可选的环节
      FlowService.deliverySteps(this.webflow.FlowData, {
        activeStepId: this.form.begin[0].activeStepId,
      }).then((res) => {
        const disabledNodes = []
        res.datas.forEach((item) => {
          if (item.disabled) {
            disabledNodes.push(item.stepId)
          }
        })
        this.disabledNodes = disabledNodes
        this.key++
      })
      // 清除选择的调整后环节
      this.form.end = ''
    },
    getInterveneData() {
      return FlowService.deliverySteps(this.webflow.FlowData).then((res) => {
        this.selectData = res.datas.map((val) => {
          if (val.disabled) {
            this.disabledNodes.push(val.stepId)
          }
          return {
            id: val.stepId,
            name: val.name,
            type: val.type, // 环节类型
            processId: val.processId,
            operators: val.operators, // 默认的特送审批人
          }
        })
        this.form.begin = [this.curStepOptions[0]]
      })
    },
    handleOkInterveneStep() {
      if (this.form.end === '') {
        Message.warn({ content: '请选择调整后流程' })
        return
      }
      if (this.form?.departName?.length === 0 && this.peopleFlag) {
        Message.warn({ content: '请选择调整后处理人' })
        return
      }
      const handleParams = {
        activeStepId: this.form.begin[0].activeStepId, // 当前步骤id
        instId: this.webflow.FlowData.instId, // 当前流程Id
        stepId: this.form.end[0].id, // 目前流程id
        operators: this.form.departName ? this.form.departName : [],
        flowCallbackBeanName: 'subflowDataBinderCallback',
        beanId: this.webflow.FlowData.processFormData.beanId,
        formId: this.webflow.FlowData.processFormData.formId,
        opinion: this.form.opinion,
        thirdBean: {},
        props: { jumpActionName: '特送' },
      }
      // 传递流程表单所有参数以解决后期会丢失部门参数的问题
      const flowDataArr = this.webflow.FlowData.processFormData.processFormPropertyValues
      const thirdBean = {}
      for (const key in flowDataArr) {
        thirdBean[flowDataArr[key].name] = flowDataArr[key].value
      }
      handleParams.thirdBean = thirdBean
      this.confirmLoading = true
      FlowService.toSteps(handleParams)
        .then((res) => {
          Message.success({ content: '特送成功' })
          this.confirmLoading = false
          // 成功后关闭弹窗
          this.webflow.close(true)
          this.showInterveneStep = false
        })
        .finally(() => {
          this.confirmLoading = false
          this.showInterveneStep = false
        })
    },
    handleCancelInterveneStep() {
      this.showInterveneStep = false
    },
    selectNode(nodeId) {
      const params = {
        instId: this.webflow?.FlowData?.instId,
        destStepId: nodeId,
      }
      WorkbenchService.getDefaultStep(params).then((res) => {
        if (res.data) {
          const { instId, processId: flowId, flowFormModelRelationId } = this.webflow.FlowData
          const userParams = {
            instId,
            actionId: res.data[0].buttonId,
            flowFormModelRelationId,
            flowId,
            inputs: this.webflow.getFormData(),
            props: {
              filterGroup: true,
            },
          }
          WorkbenchService.getDefaultUser(userParams).then((res) => {
            this.form.departName = res.data
          })
        }
      })
      // 兼容结束/送起草人的情况
      let endStep = this.selectData.find((item) => item.id.indexOf(nodeId) !== -1)
      if (!endStep) {
        return
      }
      this.showFlowChart = false
      endStep = new Array(endStep)
      if (this.form.end && this.form.end[0].id === endStep[0].id) {
        return
      }
      this.form.end = endStep
      this.selectChanged(endStep)
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.content {
  margin-top: -20px;
}
.step {
  display: block;
  line-height: $input-height-base;
}
.divider {
  margin-bottom: 5px;
  line-height: $dropdown-line-height;
}
.flowchart {
  :global(.ant-modal-body) {
    padding: 0;
  }
}
</style>
