<template>
  <div>
    <a-modal
      :visible="isShow"
      title="操作干预"
      :confirm-loading="confirmLoading"
      :destroy-on-close="true"
      :modal-props="{ width: 800 }"
      @ok="handleOk"
      @cancel="() => (isShow = false)"
    >
      <a-form-model :model="interForm" :label-col="{ span: 7 }" :wrapper-col="{ span: 15 }">
        <a-form-model-item label="当前处理环节">
          <sd-select v-model="interForm.begin" :options="curStepOptions" @change="changeCurStep" />
        </a-form-model-item>
        <a-form-model-item label="调整后处理环节" required>
          <sd-select
            ref="select"
            v-model="interForm.end"
            :options="selectData"
            :show-arrow="false"
            :open="false"
            @click.native="
              () => {
                $refs.select.blur()
                showFlowChart = true
              }
            "
          />
        </a-form-model-item>
        <a-form-model-item label="调整后操作" required>
          <sd-select v-model="interForm.action" :options="operationData" @change="actionChange" />
        </a-form-model-item>
        <a-form-model-item label="调整后的处理人">
          <sd-user-picker
            v-model="interForm.departName"
            :single="false"
            :read-only="false"
            :secret-level="secretLevel"
          />
        </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')"
        :disabled-nodes="disabledNodes"
        :node-clickable="true"
        @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-action-import'

export default {
  name: 'SdWorkflowInterfereAction',
  metaInfo: {
    title: 'SdWorkflowInterfereAction',
  },
  components,
  data() {
    return {
      interForm: {
        layout: 'inline',
        begin: '', // 当前流程
        end: '', // 结束流程
        action: '', // 调整到的操作
        departName: [], // 流程处理人
        title: '',
      },
      confirmLoading: false,
      isShow: false,
      selectData: [],
      operationData: [],
      peopleFlag: true,
      currentButton: {},
      showFlowChart: false,
      disabledNodes: [],
      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.isShow = true
            this.currentButton = button
            this.interForm.end = ''
            this.interForm.begin = this.curStepOptions.length > 0 ? [this.curStepOptions[0]] : []
            this.interForm.departName = []
            this.interForm.action = ''
          }
        })
      })
    },
    changeCurStep() {
      // 当前环节修改了，重新请求流程环节列表更新不可选的环节
      FlowService.deliverySteps(this.webflow.FlowData, {
        activeStepId: this.interForm.begin[0].activeStepId,
      }).then((res) => {
        const disabledNodes = []
        res.datas.forEach((item) => {
          if (item.disabled || item.type === '结束') {
            disabledNodes.push(item.stepId)
          }
        })
        this.disabledNodes = disabledNodes
        this.key++
      })
      // 清除选择的调整后环节
      this.interForm.end = ''
    },
    getInterveneData() {
      // 进行初始化
      return FlowService.deliverySteps(this.webflow.FlowData).then((res) => {
        this.selectData = res.datas.map((itemData) => {
          if (itemData.disabled || itemData.type === '结束') {
            this.disabledNodes.push(itemData.stepId)
          }
          return {
            id: itemData.stepId,
            name: itemData.name,
            processId: itemData.processId,
          }
        })
        this.interForm.begin = [this.curStepOptions[0]]
      })
    },
    handleOk() {
      if (this.interForm.end === '') {
        Message.warn({ content: '请选择调整后流程' })
        return
      }
      if (this.interForm?.departName?.length === 0 && this.peopleFlag) {
        Message.warn({ content: '请选择调整后处理人' })
        return
      }
      if (this.interForm.action === '') {
        Message.warn({ content: '调整后的操作不能为空' })
        return
      }
      const handleParams = {
        activeStepId: this.interForm.begin[0].activeStepId, // 当前步骤id
        instId: this.webflow.FlowData.instId, // 当前流程Id
        stepId: this.interForm.end[0].id, // 目的流程id
        operators: this.interForm.departName ? this.interForm.departName : [],
        actionId: this.interForm.action === '' ? 0 : this.interForm.action[0].id,
        flowCallbackBeanName: 'subflowDataBinderCallback',
        thirdBean: {
          id: '',
          title: '',
          businessTypeId: '',
          businessTypeName: '',
          urgencyLevel: '',
        },
        thirdBeanIdProperty: 'id',
        thirdBeanIdType: 'long',
        thirdBeanTitleProperty: 'title',
        inputs: this.webflow.getFormData(),
      }
      // 添加缓急字段
      this.webflow.FlowData.processFormData.processFormPropertyValues.forEach((item) => {
        if (item.name === 'id') {
          handleParams.thirdBean.id = item.value
        }
        if (item.name === 'title') {
          handleParams.thirdBean.title = item.value
        }
        if (item.name === 'businessTypeId') {
          handleParams.thirdBean.businessTypeId = item.value
        }
        if (item.name === 'businessTypeName') {
          handleParams.thirdBean.businessTypeName = item.value
        }
        if (item.name === 'urgencyLevel') {
          handleParams.thirdBean.urgencyLevel = item.value
        }
      })
      this.confirmLoading = true
      FlowService.interToActions(handleParams)
        .then((res) => {
          if (res.status === 200) {
            Message.success({ content: '干扰操作成功', duration: 1 }).then(() => {
              this.webflow.close(true)
            })
          } else {
            Message.error({ content: '干扰操作失败' })
          }
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    // 获取流程实例的当前活动环节信息
    selectChanged(item) {
      this.operationData = []
      const interParams = {
        processId: item[0].processId,
        stepId: item[0].id,
        instId: this.webflow.FlowData.instId,
        activeStepId:
          this.webflow.FlowData.activeStepId === null ? 0 : this.webflow.FlowData.activeStepId,
      }
      WorkbenchService.toActions(interParams).then((data) => {
        this.operationData = data.datas
      })
      if (item[0].name === '结束') {
        this.peopleFlag = false
      } else {
        this.peopleFlag = true
      }
    },
    actionChange(val) {
      if (val.length) {
        const { instId, processId: flowId, flowFormModelRelationId } = this.webflow.FlowData
        const userParams = {
          instId,
          actionId: val[0].id,
          flowFormModelRelationId,
          flowId,
          inputs: this.webflow.getFormData(),
          props: {
            filterGroup: true,
          },
        }
        WorkbenchService.getDefaultUser(userParams).then((res) => {
          this.interForm.departName = res.data
        })
      }
    },
    selectNode(nodeId) {
      // 兼容结束/送起草人的情况
      let endStep = this.selectData.find((item) => item.id.indexOf(nodeId) !== -1)
      if (!endStep || endStep.type === '结束') {
        return
      }
      this.showFlowChart = false
      endStep = new Array(endStep)
      if (this.interForm.end && this.interForm.end[0].id === endStep[0].id) {
        return
      }
      this.interForm.end = endStep
      this.interForm.action = ''
      this.selectChanged(endStep)
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.flowchart {
  :global(.ant-modal-body) {
    padding: 0;
  }
}
</style>
