<template>
  <!--发起沟通 -->
  <a-modal
    :destroy-on-close="true"
    :title="currentActionButton.buttonName"
    :body-style="{ overflow: 'auto' }"
    :width="600"
    :visible="showInformModal"
    @ok="handleOkInform"
    @cancel="() => (showInformModal = false)"
  >
    <a-form-model
      ref="commForm"
      layout="horizontal"
      :class="$style.inform"
      :model="commForm"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 18 }"
      :rules="informRules"
    >
      <a-form-model-item :label="`${currentActionButton.buttonName}人员`" prop="users" required>
        <sd-user-picker
          v-model="commForm.users"
          :single="false"
          :read-only="false"
          :hierarchical="hierarchical"
          :secret-level="webflow.getFieldValue('secretLevel')"
        />
      </a-form-model-item>
      <a-form-model-item :label="`${currentActionButton.buttonName}信息`" prop="content" required>
        <a-textarea
          v-model="commForm.content"
          :placeholder="`请输入${currentActionButton.buttonName}信息`"
          :auto-size="{ minRows: 4 }"
        />
        <sd-attachment
          v-if="groupId"
          ref="attachment"
          list-type="text"
          :group-id="groupId"
          :cat-num="-5"
        >
          <a>上传附件</a>
        </sd-attachment>
      </a-form-model-item>
    </a-form-model>
  </a-modal>
</template>

<script>
import { Message } from 'ant-design-vue'
import storeMixin from '@/common/store-mixin'
import FlowService from '../flow-service'
import components from './_import-components/sd-workflow-comm-import'
const duration = 1
export default {
  name: 'SdWorkflowComm',
  components,
  mixins: [storeMixin],
  data() {
    // message不支持动态设置提示语，使用validator方式
    const informValidator = (rule, value, callback) => {
      if (!value.length) {
        callback(new Error(`请选择${this.currentActionButton.buttonName}人员`))
      } else {
        callback()
      }
    }
    const commValidator = (rule, value, callback) => {
      if (!value.length) {
        callback(new Error(`请输入${this.currentActionButton.buttonName}信息`))
      } else {
        callback()
      }
    }
    return {
      groupId: '',
      currentActionButton: {},
      showInformModal: false,
      commForm: {
        users: [],
        content: '',
      },
      informRules: {
        users: [
          {
            validator: informValidator,
            trigger: 'change',
          },
        ],
        content: [
          {
            validator: commValidator,
            trigger: 'change',
          },
        ],
      },
      informUserList: [],
      hierarchical: false,
    }
  },
  methods: {
    run({ button }) {
      this.currentActionButton = button
      this.showInformModal = true
      FlowService.getGroupCode().then((res) => {
        if (res.status === 200) {
          if (res.data) {
            this.groupId = res.data.toString()
          } else {
            Message.error('获取groupId失败')
          }
        } else {
          Message.error(res.statusText)
        }
      })
      FlowService.getActionInfo(
        // 和知会保持一致
        this.webflow.FlowData,
        { ...button, buttonId: 'workflow$inform' },
        this.webflow.getFormData()
      ).then((res) => {
        this.hierarchical = res?.hierarchical !== '0'
      })
    },
    handleOkInform() {
      this.$refs.commForm.validate((valid) => {
        if (valid) {
          const communicateUsers = this.commForm.users.map((item) => ({
            userAccount: item.code,
            userName: item.name,
          }))
          const opValue = {
            value: {
              signUserName: this.userInfo.name,
              signDeptName: this.webflow.FlowData?.attrs?.userFlowDeptName,
              signContent: this.commForm.content,
              signDate: new Date().getTime(),
              attrs: { attachment: this.groupId },
            },
          }
          const opinions = [
            {
              name: 'opinion',
              value: JSON.stringify(opValue),
            },
          ]
          const key = Symbol.for()
          this.webflow.FlowData.inputs = this.webflow.getFormData()
          this.webflow.checkLock().then(() => {
            FlowService.startCommunicate(this.webflow.FlowData, communicateUsers, opinions).then(
              () => {
                this.showInformModal = false
                Message.success({
                  content: `发起沟通成功`,
                  key,
                  duration,
                }).then(() => {
                  this.webflow.close(true)
                })
                this.commForm = {
                  users: [],
                  content: '',
                }
              },
              (err) => {
                const isRepeat = communicateUsers.some(
                  (item) => item.userAccount === this.userInfo.account
                )
                if (isRepeat) Message.error({ content: '不能向自己发起沟通' })
                else Message.error({ content: err.response.data.message })
              }
            )
          })
        }
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.inform {
  :global(.ant-form-item) {
    margin-bottom: 1px;
  }
}
.zhihui {
  padding-left: 90px;
}
.uploadbtn {
  :global(.ant-list) {
    width: 510px;
    padding-left: 90px;
  }
}
</style>
