<template>
  <a-modal
    :destroy-on-close="true"
    :title="currentActionButton.buttonName"
    :body-style="{ overflow: 'auto' }"
    :width="600"
    :visible="showModal"
    :confirm-loading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form-model
      ref="form"
      layout="horizontal"
      :class="$style.form"
      :model="form"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 18 }"
      :rules="rules"
    >
      <a-form-model-item :label="`${currentActionButton.buttonName}人员`" prop="users" required>
        <sd-user-picker
          v-model="form.users"
          :single="single"
          :hierarchical="hierarchical"
          :secret-level="secretLevel"
        />
      </a-form-model-item>
      <a-form-model-item
        v-if="webflow.canWirteOpinion"
        :label="`${currentActionButton.buttonName}意见`"
        prop="content"
      >
        <sd-opinion-model
          ref="opinionModel"
          v-model="turnTodoOpinion"
          :group-id="groupId"
          @attachmentChange="attachmentChange"
        />
      </a-form-model-item>
      <sd-notify-type v-model="form.notify" />
    </a-form-model>
  </a-modal>
</template>

<script>
import storeMixin from '@/common/store-mixin'
import { message } from '@/common/one-ui'
import FlowService from '../flow-service'
import components from './_import-components/sd-workflow-turn-todo-import'

export default {
  name: 'SdWorkflowTurnTodo',
  metaInfo: {
    title: '转办',
  },
  components,
  mixins: [storeMixin],
  data() {
    return {
      currentActionButton: {},
      showModal: false,
      form: {
        users: [],
        notify: [],
        content: '',
      },
      rules: {
        users: [
          {
            required: true,
            message: '不能为空',
            trigger: 'change',
          },
        ],
        content: [
          {
            required: this.opinionRequired,
            validator: this.validator,
            trigger: 'change',
          },
        ],
      },
      hierarchical: false,
      single: false,
      secretLevel: '',
      confirmLoading: false,
      fdApproveOpinion: null,
    }
  },
  computed: {
    opinionRequired() {
      return this.fdApproveOpinion?.required || false
    },
    groupId() {
      return JSON.parse(this.fdApproveOpinion?.value || '{}')?.value?.attrs?.attachment || ''
    },
    turnTodoOpinion: {
      get() {
        return this.form.content
      },
      set(v) {
        this.form.content = v
        this.webflow.setFieldValue('approveOpinion', v)
      },
    },
  },
  methods: {
    run({ button }) {
      this.currentActionButton = button
      this.secretLevel = this.webflow.getFieldValue('secretLevel')
      this.fdApproveOpinion = this.webflow.FlowData?.processFormData?.processFormPropertyValues?.find(
        (f) => f.name === 'approveOpinion'
      )
      const flowData = this.webflow.FlowData
      const inputs = this.webflow.getFormData()
      return Promise.all([
        FlowService.getNodeInfo(flowData, { actionId: button.attrs.actionId }, inputs),
        FlowService.getActionInfo(flowData, button, inputs),
      ]).then(([taskCandidateInfos, actionInfo]) => {
        this.single = !taskCandidateInfos[0]?.multi
        this.hierarchical = actionInfo?.hierarchical !== '0'
        this.form.content = this.webflow.getFieldValue('approveOpinion')
        this.showModal = true
      })
    },
    validator(rule, value, callback) {
      const atts = this.$refs.opinionModel?.getFileList() || []
      if (atts.length && atts.some((item) => item.Completed === 0)) {
        callback(new Error('正在上传意见附件,请稍后再试'))
        return
      }
      if (atts.length === 0 && !value?.trim() && this.opinionRequired) {
        callback(new Error('不能为空'))
      } else {
        callback()
      }
    },
    handleOk() {
      this.confirmLoading = true
      this.$refs.form
        .validate()
        .then((flag) => {
          if (flag) {
            const users = this.form.users.map((item) => ({
              userAccount: item.code,
              userName: item.name,
            }))
            if (users.findIndex((item) => item.userAccount === this.userInfo.account) !== -1) {
              message.error(`不能${this.currentActionButton.buttonName}给自己`)
              return
            }
            const key = Symbol('key')
            const duration = 1
            message.loading({ content: '处理中...', key, duration: 0 })
            return this.webflow.checkLock().then(() => {
              return FlowService.transfer(
                this.webflow.FlowData,
                users,
                this.webflow.getFormData(),
                this.form.notify
              ).then(
                (res) => {
                  message.success({ content: '流程已处理', key, duration }).then(() => {
                    this.webflow.close(true)
                  })
                },
                () => {
                  message.error({
                    content: `${this.currentActionButton.buttonName}失败`,
                    key,
                    duration,
                  })
                }
              )
            })
          }
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    handleCancel() {
      this.syncWebflow()
      this.showModal = false
    },
    attachmentChange() {
      this.syncWebflow()
    },
    syncWebflow() {
      this.webflow?.$refs.form?.$refs.opinionModel?.$refs.attachment?.updateFileList?.()
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
</style>
