<template>
  <div>
    <a-modal
      :destroy-on-close="true"
      title="下一环节处理人"
      :mask-closable="false"
      :visible="showSubmitSplit"
      :width="600"
      :confirm-loading="confirmLoading"
      @cancel="cancel2"
      @ok="
        () => {
          if (
            taskCandidateInfos.every((task) => {
              return sdGet(task, 'props.actionProps?.freeSplitAction') === 'true' && !task.checked
            })
          ) {
            message.warn('请至少选择一个环节')
            return
          }
          $refs.form.validate().then((valid) => {
            if (valid) {
              submit()
            }
          })
        }
      "
    >
      <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:
                (sdGet(task, 'props.actionProps?.freeSplitAction') !== 'true' || task.checked) &&
                !task.autoSubmit,
              message: '不能为空',
              trigger: ['change', 'blur'],
            },
          ]"
        >
          <a-checkbox
            v-if="sdGet(task, 'props.actionProps?.freeSplitAction') === 'true'"
            slot="label"
            :checked="task.checked"
            @change="
              (e) => {
                $set(task, 'checked', e.target.checked)
                $nextTick($refs[index][0].onFieldBlur)
              }
            "
          >
            {{ task.destStepName }}
          </a-checkbox>
          <span v-else slot="label"> {{ task.destStepName }}</span>
          <sd-select
            v-model="form[index]"
            :disabled="
              (sdGet(task, 'props.actionProps?.freeSplitAction') === 'true' && !task.checked) ||
                task.autoSubmit
            "
            :options="form[index] || []"
            option-label="name"
            option-value="code"
            mode="multiple"
            :open="false"
            :placeholder="task.autoSubmit ? '自动提交环节' : ''"
            @click.native="
              () => {
                if (
                  (sdGet(task, 'props.actionProps?.freeSplitAction') === 'true' && !task.checked) ||
                  task.autoSubmit
                ) {
                  return
                }
                task.candidates = form[index] || task.candidates
                splitNodeIndex = index
                showSubmitUser = true
              }
            "
          />
        </a-form-model-item>
        <sd-notify-type v-model="notifyType" tag="div" />
      </a-form-model>
    </a-modal>
    <a-modal
      v-if="showSubmitUser"
      :class="$style.candidate"
      :destroy-on-close="true"
      title="下一环节处理人"
      :width="890"
      :mask-closable="false"
      :visible="showSubmitUser"
      @cancel="cancel"
    >
      <!-- taskCandidateInfos是环节信息，现在是把环节信息直接丢过去，选了的人也也直接放到环节信息里-->
      <sd-next-node-candidate
        :value="[taskCandidateInfos[splitNodeIndex]]"
        :flow-data="webflow.FlowData"
        @input="
          (value) => {
            let { strategy, ...rest } = value[0] //todo这里需要优化下，现在一股脑放到taskCandidateInfos里了
            Object.assign(taskCandidateInfos[splitNodeIndex], rest)
          }
        "
      />
      <template slot="footer">
        <a-row :class="$style.footerLeft">
          <sd-notify-type v-if="!showSubmitSplit" v-model="notifyType" tag="col" :span="10" />
          <a-col
            v-if="taskCandidateInfos[splitNodeIndex].participantsStrategy === 'custom'"
            :span="14"
          >
            处理方式：
            <a-radio-group
              v-model="taskCandidateInfos[splitNodeIndex].strategy"
              :options="taskCandidateInfos[splitNodeIndex].strategyItems"
            >
            </a-radio-group>
          </a-col>
        </a-row>
        <a-button @click="cancel">
          取消
        </a-button>
        <a-button
          type="primary"
          :loading="confirmLoading"
          @click="
            () => {
              if (taskCandidateInfos.length === 1) {
                submit()
              } else {
                //分裂环节
                form[splitNodeIndex] = taskCandidateInfos[splitNodeIndex].targetNodes
                form = { ...form }
                showSubmitUser = false
                $nextTick($refs[splitNodeIndex][0].onFieldBlur)
              }
            }
          "
        >
          确定
        </a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { Message, Modal } from 'ant-design-vue'
import { sdLocalStorage } from '@/common/services/storage-service'
import axios from '@/common/services/axios-instance'
import { router } from '@/common/router-ready'
import flowService from '../flow-service'
import components from './_import-components/sd-workflow-push-import'
let resolve1
export default {
  name: 'SdWorkflowPush',

  components,
  data() {
    return {
      taskCandidateInfos: [],
      showSubmitUser: false,
      button: {},
      confirmLoading: false,
      action: '',
      removeOperators: [],
      form: {},
      showSubmitSplit: false,
      splitNodeIndex: 0,
      message: Message,
      notifyType: [],
    }
  },
  methods: {
    run({ button, action = 'dispatch', removeOperators }) {
      this.button = button
      this.action = action
      this.removeOperators = removeOperators
      if (this.webflow.FlowData.attrs.auditElement.length > 0 && !this.webflow.checkAllYS) {
        Message.warning('审核要素需勾选全选才可提交流转')
        return
      } else this.webflow.FlowData.auditElement = this.webflow.checkedYSlist
      this.webflow
        .validateFields()
        .then((flag) => {
          if (flag) {
            this.webflow.FlowData.customProps = this.webflow.customProps
            flowService
              .getNodeInfo(this.webflow.FlowData, button, this.webflow.getFormData())
              .then((taskCandidateInfos) => {
                if (taskCandidateInfos.length === 1 && taskCandidateInfos[0].autoSubmit) {
                  // 自动提交
                  this.taskCandidateInfos = taskCandidateInfos
                  this.submit()
                  return
                }
                Promise.all(
                  taskCandidateInfos.map((taskCandidateInfo) => {
                    taskCandidateInfo.strategy = taskCandidateInfo?.strategyItems?.find(
                      (item) => item.checked
                    )?.value
                    // 每个环节可能对应多个节点，例如分裂的情况，task-candidate-infos接口的返回值就是数组
                    if (!taskCandidateInfo.autoSubmit) {
                      return flowService.getTaskCandidateRoots(
                        // 获取选人树根结点
                        this.webflow.FlowData,
                        taskCandidateInfo,
                        this.webflow.getFormData()
                      )
                    } else {
                      return Promise.resolve([])
                    }
                  })
                ).then((res) => {
                  res.forEach((item, index) => {
                    taskCandidateInfos[index].rootCandidateInfo = item
                    this.form[index] = taskCandidateInfos[index].candidates
                  })
                  this.taskCandidateInfos = taskCandidateInfos
                  if (taskCandidateInfos.length === 1) {
                    this.showSubmitUser = true
                  } else {
                    if (
                      // 分裂的环节全是自动提交环节，且是不可自有勾选的,自动提交
                      taskCandidateInfos.every(
                        (task) =>
                          task.props.actionProps?.freeSplitAction !== 'true' && task.autoSubmit
                      )
                    ) {
                      this.submit()
                    } else {
                      this.showSubmitSplit = true
                    }
                  }
                })
              })
              .catch((e) => {
                if (e.response?.data?.code === '20001009') {
                  this.webflow.updatePushButtons().then(() => {
                    resolve1()
                    if (this.webflow.FlowData.pushButtons.length === 1) {
                      this.webflow.buttonClick({
                        ...this.webflow.FlowData.pushButtons[0],
                        fakeId: 'workflow-push',
                      })
                    } else {
                      Message.error('提交流转节点发送变化，请重新提交')
                    }
                  })
                  return
                } else {
                  resolve1()
                }
                throw e
              })
          } else {
            resolve1()
          }
        })
        .catch((e) => {
          resolve1()
          throw e
        })
      return new Promise((resolve, reject) => {
        resolve1 = resolve
      })
    },
    submit() {
      if (this.taskCandidateInfos.length > 1) {
        // 分裂
        this.taskCandidateInfos.forEach((task, index) => {
          task.targetNodes = this.form[index]
        })
      } else {
        if (this.taskCandidateInfos[0].targetNodes?.length === 0 && this.showSubmitUser) {
          Message.warn(`请选择下一环节处理人`)
          return
        }
      }
      // 判断选择的部门是否有接收人（配置的默认处理人才会有hasCandidateUsers属性）
      let deptNoUser = []
      this.taskCandidateInfos.forEach((task) => {
        const list = task.targetNodes
          ?.filter((t) => t.attrs?.hasCandidateUsers === 'false')
          .map((t) => t.name)
        if (list?.length > 0) {
          deptNoUser = deptNoUser.concat(list)
        }
      })
      let p1 = Promise.resolve(true)
      if (deptNoUser.length > 0) {
        p1 = new Promise((resolve) => {
          Modal.confirm({
            content: deptNoUser.join(', ') + '未配置接收人，是否继续提交？',
            onOk() {
              resolve(true)
            },
            onCancel() {
              resolve(false)
            },
          })
        })
      }
      p1.then((flag) => {
        if (flag) {
          const participantInfos = this.taskCandidateInfos
            .filter((task) => {
              if (task.props.actionProps?.freeSplitAction === 'true' && !task.checked) {
                return false
              }
              return true
            })
            .map((taskinfo) => {
              return {
                destStepName: taskinfo.destStepName,
                destStepId: taskinfo.destStepId,
                participants: taskinfo.targetNodes,
              }
            })
          this.confirmLoading = true
          let p
          // 提交操作
          if (this.action === 'toaction') {
            // 兼容减签后action干预的情况
            p = flowService.subRemoveOperator(
              this.webflow.FlowData,
              this.removeOperators,
              this.webflow.getBackendValues()
            )
          } else {
            p = this.webflow
              .sdEmit('participantsOkClick', {
                button: this.button,
                participantInfos,
                flowData: this.webflow.FlowData,
              })
              .then((evt) => {
                if (evt.defaultPrevented) {
                  this.confirmLoading = false
                  const i = 'cancel'
                  return Promise.reject(i)
                }
              })
          }
          p.then(() => {
            // 提交后的环节中有勾选“表单转PDF”
            const formToPDF = this.taskCandidateInfos.some(
              (item) => item.props?.relProps?.destStepProps?.['we-flow$formToPDF'] === 'true'
            )
            const formToPDFField = this.taskCandidateInfos.find(
              (item) => item.props?.relProps?.destStepProps?.['we-flow$formToPdfField']
            )?.props.relProps.destStepProps['we-flow$formToPdfField']

            if (formToPDF) {
              return this.webflow.doAction({ buttonId: 'form-snapshot' }).then((res) => {
                if (res) {
                  const processFormPropertyValues = this.webflow.FlowData.processFormData
                    ?.processFormPropertyValues
                  const a = (
                    processFormPropertyValues?.find((i) => i.name === formToPDFField) ||
                    processFormPropertyValues?.find((i) => i.dataType === 'attachment')
                  )?.value
                  if (!a) {
                    return Promise.resolve(true)
                  }
                  const attachmentGroupCode = JSON.parse(a).value
                  const formData = new FormData()
                  formData.append('attachmentGroupCode', attachmentGroupCode)
                  formData.append(
                    'formImage',
                    res,
                    `审批单_${this.webflow.getFieldValue('title')}.png`
                  )
                  formData.append('formId', this.webflow.FlowData.processFormData.formId)
                  formData.append('beanId', this.webflow.FlowData.processFormData.beanId)
                  formData.append('instId', this.webflow.FlowData.instId)
                  return axios.post('api/framework/v1/attachment-extend/form-to-pdf', formData)
                }
              })
            }
          })
            .then(() => {
              this.webflow.FlowData.customProps = this.webflow.customProps
              this.webflow.FlowData.inputs = this.webflow.getFormData()
              // 如果设置有流程时限，提交的时候带上
              if (this.webflow.timer) {
                this.webflow.FlowData.timer = this.webflow.timer
              }
              return this.webflow.checkLock().then(() => {
                return flowService[this.action](
                  this.webflow.FlowData,
                  this.taskCandidateInfos,
                  this.button.buttonId,
                  this.notifyType
                ).then((res) => {
                  this.showSubmitUser = false
                  // 先直接关闭，后面在优化提示状态
                  sdLocalStorage.removeItem(`Lock${this.webflow.FlowData.instId}`)
                  return this.webflow
                    .sdEmit('afterDispatch', {
                      dispatchResult: res,
                      FlowData: this.webflow.FlowData,
                    })
                    .then((evt) => {
                      if (evt.defaultPrevented) {
                        resolve1(true)
                        return
                      }
                      return Message.success({
                        content: `提交成功`,
                        duration: 1,
                      }).then(() => {
                        resolve1(true)
                        if (!isNaN(parseInt(res)) && parseInt(res) > 0) {
                          // 减签后干预待办如果有自己直接打开待办
                          router.replace(`/sd-webflow/todo-pages/${res}`)
                          return
                        }
                        this.webflow.close(true)
                      })
                    })
                })
              })
            })
            .catch((e) => {
              this.confirmLoading = false
              resolve1()
              throw e
            })
        }
      })
    },
    cancel2() {
      this.showSubmitSplit = false
      resolve1(false)
    },
    cancel() {
      this.showSubmitUser = false
      resolve1(false)
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.candidate {
  :global(.ant-modal-body) {
    padding: 12px;
  }
}
.footer-left {
  text-align: left;
}
</style>
