<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 :label="`${currentActionButton.buttonName}意见`" prop="content">
        <sd-opinion-model ref="opinionModel" v-model="turnTodoOpinion" :group-id="groupId" />
      </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 axios from '@/common/services/axios-instance'
import components from './_import-components/sd-workflow-turn-todo-import'
import todoListService from '@/todo/todo-list-service'

export default {
  name: 'SdWorkflowTurnTodo',
  metaInfo: {
    title: '转办',
  },
  components,
  mixins: [storeMixin],
  data() {
    return {
      currentActionButton: { buttonName: '转办' },
      showModal: false,
      todos: [],
      handlerCallback: null,
      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: {
    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 = 30
            message.loading({ content: '处理中...', key, duration: 0 })
            console.log(this.todos)
            const content = this.form.content
            this.showModal = false
            this.todos.forEach((todo) => {
              axios
                .get(`api/framework/v1/task-form-process/${todoListService.makePath(todo, 'todo')}`)
                .then((res) => {
                  console.log(res.data)
                  if (
                    res.data.processId === 'G_1_QUESTION_FEED_BACK' &&
                    (res.data.attrs.stepN === 0 ||
                      res.data.processActiveLogInfo[0].stepId === 'G_1_QUESTION_FEED_BACK.1') // 流程处于开始环节
                  ) {
                    var { instId, activeStepId } = res.data
                    const handleParams = {
                      activeStepId: activeStepId, // 当前步骤id
                      instId: instId, // 当前流程Id
                      stepId: 'G_1_QUESTION_FEED_BACK.1', // 目前流程id
                      operators: [
                        {
                          type: 'User',
                          code: users[0].userAccount,
                          name: users[0].userName,
                          attrs: null,
                          attrNames: [],
                        },
                      ],
                      flowCallbackBeanName: 'subflowDataBinderCallback',
                      beanId: res.data.processFormData.beanId,
                      formId: res.data.processFormData.formId,
                      opinion: content,
                      thirdBean: {},
                      props: { jumpActionName: '特送' },
                    }
                    // 传递流程表单所有参数以解决后期会丢失部门参数的问题
                    const flowDataArr = res.data.processFormData.processFormPropertyValues
                    const thirdBean = {}
                    for (const key in flowDataArr) {
                      thirdBean[flowDataArr[key].name] = flowDataArr[key].value
                    }
                    handleParams.thirdBean = thirdBean
                    FlowService.toSteps(handleParams)
                      .then((res) => {
                        message.success({ content: '特送成功' })
                        axios
                          .get(
                            'api/xcoa-mobile/v1/spic-common/removeTodoItemByTodoId?todoId=' +
                              todo.id
                          )
                          .then((res) => {
                            console.log(res.data)
                            message.success({ content: '删除待办成功' })
                            this.handlerCallback()
                          })
                      })
                      .finally(() => {})
                  } else {
                    const inputs = []
                    res.data.processFormData.processFormPropertyValues.forEach((v) => {
                      inputs.push({ name: v.name, value: v.value })
                    })
                    inputs.push({
                      name: 'approveOpinion',
                      value:
                        '{"value":{"signContent":"' + content + '","attrs":{"attachment":""}}}',
                    })
                    FlowService.transfer(res.data, users, inputs, this.form.notify).then(
                      (res) => {
                        message.success({ content: '流程已处理', key, duration })
                        this.handlerCallback()
                      },
                      (res) => {
                        message.error({
                          content: `${res.response.data.message}失败`,
                          key,
                          duration,
                        })
                      }
                    )
                  }
                })
                .catch((e) => {
                  message.error({
                    content: `转发失败`,
                    key,
                    duration,
                  })
                })
            })
          }
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    handleCancel() {
      this.syncWebflow()
      this.showModal = false
    },
    show() {
      this.showModal = true
    },
    setTodos(todos) {
      this.todos = todos
    },
    syncWebflow() {
      this.webflow?.$refs.form?.$refs.opinionModel?.$refs.attachment?.updateFileList?.()
    },
    setHandlerCallback(callback) {
      this.handlerCallback = callback
    },
  },
}
</script>

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