<template>
  <div>
    <a-modal
      :destroy-on-close="true"
      title="请选择"
      :mask-closable="false"
      :visible="showSubmitSplit"
      :width="600"
      :confirm-loading="confirmLoading"
      @cancel="cancel2"
      @ok="okClick"
    >
      <a-form-model ref="form" :model="form" layout="vertical">
        <a-form-model-item
          v-for="(task, index) in taskCandidateInfos"
          :key="index"
          :ref="index + ''"
          :prop="index + ''"
          :rules="[
            {
              required: task.checked,
              message: '不能为空',
              trigger: ['change', 'blur'],
            },
          ]"
        >
          <a-checkbox
            slot="label"
            :checked="task.checked"
            @change="
              (e) => {
                $set(task, 'checked', e.target.checked)
                $nextTick($refs[index][0].onFieldBlur)
              }
            "
          >
            {{ task.destStepName }}
          </a-checkbox>
          <sd-select
            v-model="form[index]"
            :disabled="!task.checked"
            :options="form[index] || []"
            option-label="name"
            option-value="code"
            mode="multiple"
            :open="false"
            @click.native="
              () => {
                if (task.checked) {
                  task.candidates = form[index] || task.candidates
                  splitNodeIndex = index
                  showSubmitUser = true
                }
              }
            "
          />
        </a-form-model-item>
        <div
          v-for="(item, index) in curStepsInfoClass"
          :key="index + item.name"
          :class="$style.curstepinfo"
        >
          <label>已选{{ item.name }}</label
          >：
          <span v-for="operator in item.operators" :key="operator.code" :class="$style.operator">{{
            operator.name
          }}</span>
        </div>
      </a-form-model>
    </a-modal>
    <a-modal
      :class="$style.candidate"
      :destroy-on-close="true"
      title="下一环节处理人"
      :width="890"
      :mask-closable="false"
      :visible="showSubmitUser"
      :confirm-loading="confirmLoading"
      @ok="
        () => {
          if (taskCandidateInfos.length === 1) {
            submit()
          } else {
            //分裂环节
            form[splitNodeIndex] = taskCandidateInfos[splitNodeIndex].targetNodes
            form = { ...form }
            showSubmitUser = false
            $nextTick($refs[splitNodeIndex][0].onFieldBlur)
          }
        }
      "
      @cancel="cancel"
    >
      <sd-next-node-candidate
        :value="[taskCandidateInfos[splitNodeIndex]]"
        :flow-data="webflow.FlowData"
        @input="(value) => Object.assign(taskCandidateInfos[splitNodeIndex], value[0])"
      />
    </a-modal>
  </div>
</template>

<script>
import { Message } from 'ant-design-vue'
import FlowService from '../flow-service'
import components from './_import-components/sd-workflow-add-operator-import'
let resolve1
export default {
  name: 'SdWorkflowAddOperator',
  metaInfo: {
    title: 'SdWorkflowAddOperator',
  },
  components,
  data() {
    return {
      button: {},
      taskCandidateInfos: [],
      confirmLoading: false,
      showSubmitUser: false,
      form: {},
      showSubmitSplit: false,
      splitNodeIndex: 0,
      curStepsInfo: null,
      isMainSponsorStep: false,
    }
  },
  computed: {
    curStepsInfoClass() {
      const infos = []
      ;(this.curStepsInfo || []).forEach((item) => {
        let info = infos.find((_) => _.name === item.operatorAttrs?.['propagate_branch_name'])
        if (!info) {
          info = { name: item.operatorAttrs?.['propagate_branch_name'], operators: [] }
          infos.push(info)
        }
        info.operators.push({
          code: item.operatorCode,
          name: item.operator,
          type: item.operatorType,
        })
      })
      return infos
    },
  },
  methods: {
    run({ button }) {
      this.button = button
      this.form = {}
      this.isMainSponsorStep = button.attrs?.mainSponsorStep === 'true'
      // 主协办的加签
      if (this.isMainSponsorStep) {
        FlowService.getCurrentStepsInfo(this.webflow.FlowData.instId).then((res) => {
          this.curStepsInfo = res.data
        })
        FlowService.getNodeInfo(
          this.webflow.FlowData,
          button,
          this.webflow.getFormData(),
          'addOperator'
        ).then((taskCandidateInfos) => {
          Promise.all(
            taskCandidateInfos.map((taskCandidateInfo) => {
              return FlowService.getAddOperatorCandicateRoots(
                this.webflow.FlowData,
                this.webflow.getFormData(),
                taskCandidateInfo
              )
            })
          ).then((res) => {
            res.forEach((item, index) => {
              taskCandidateInfos[index].rootCandidateInfo = item.candidates
            })
            this.taskCandidateInfos = taskCandidateInfos
            this.showSubmitSplit = true
          })
        })
      } else {
        FlowService.getAddOperatorCandicateRoots(
          this.webflow.FlowData,
          this.webflow.getFormData()
        ).then((data) => {
          // 为了适用提交选人组件，构造一个假的taskCandidateInfos
          const { candidates: rootCandidateInfo, props } = data
          this.taskCandidateInfos = [
            {
              rootCandidateInfo,
              actionName: button.buttonName,
              multi: true,
              props,
              actionId: this.webflow.FlowData.attrs.actionId,
            },
          ]
          this.showSubmitUser = true
        })
      }
      return new Promise((resolve, reject) => {
        resolve1 = resolve
      })
    },
    submit() {
      const duration = 1
      const addOperatorUsers = this.taskCandidateInfos
        .map((item) => item.targetNodes || [])
        .reduce((a, b) => a.concat(b))
      if (addOperatorUsers.length === 0) {
        Message.warn('请选择加签人员')
        return
      }
      this.confirmLoading = true
      FlowService.hasOperator(this.webflow.FlowData, this.button.buttonId).then((data) => {
        // 验证加签人员是否已在加签队列中
        const operators = addOperatorUsers.filter((i) => {
          return (
            data
              .filter((item) => item.status !== 'COMPLETED')
              .map((item) => item.code)
              .indexOf(i.code) >= 0
          )
        })
        if (operators.length) {
          Message.warn(
            `${operators.map((item) => item.name).join(',')}${
              this.isMainSponsorStep ? '正在处理' : '已经发起会签,并且会签未结束'
            }，不能加签`
          )
          this.confirmLoading = false
          return
        }
        const key = Symbol.for()
        Message.loading({ content: '处理中...', key })
        let f = 'addSubOperator'
        if (this.button.buttonId === 'workflow$addOperator') {
          f = 'addOperator'
        }
        FlowService[f](this.webflow.FlowData, addOperatorUsers)
          .then(
            () => {
              Message.success({ content: '已提交处理人', key, duration }).then(() => {
                this.showSubmitUser = false
                this.showSubmitSplit = false
                // 先直接关闭，后面在优化提示状态
                this.webflow.updateFlow()
                resolve1(true)
              })
            },
            () => {
              resolve1(false)
              Message.error('处理失败')
            }
          )
          .finally(() => {
            this.confirmLoading = false
          })
      })
    },
    cancel() {
      this.showSubmitUser = false
      this.confirmLoading = false
      resolve1(false)
    },
    cancel2() {
      this.showSubmitSplit = false
      resolve1(false)
    },
    okClick() {
      if (
        this.taskCandidateInfos.every((task) => {
          return !task.checked
        })
      ) {
        Message.warn('请至少选择一个环节')
        return
      }
      this.$refs.form.validate().then((valid) => {
        if (valid) {
          this.taskCandidateInfos.forEach((task, index) => {
            task.targetNodes = this.form[index]
          })
          this.submit()
        }
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.candidate {
  :global(.ant-modal-body) {
    padding: 12px;
  }
}
.curstepinfo {
  margin-bottom: 10px;
  .operator:not(:last-child)::after {
    content: ', ';
  }
}
</style>
