<template>
  <div class="approval-button-item countersign-button">
    <el-button :disabled="disabled" :size="btnSize" @click="handleCountersign">
      {{ name }}
    </el-button>
    <approval-dialog
      ref="approvalDialog"
      :dialog-title="$t('task.SignatureSettings')"
      is-show-user-selector
      :user-label="$t('task.Signatory')"
      :opinion-label="$t('task.SignatureDescription')"
      :dialog-before-click="dialogBeforeClick"
      :alias="alias"
      :is-get-approval-btn="isGetApprovalBtn"
      @submit-form="handleSubmitForm"
    ></approval-dialog>
  </div>
</template>

<script>
  import ApprovalDialog from './ApprovalDialog'

  import approvalButton from '@/mixins/approvalButton'

  import { savaCountersign, savaUserTaskCountersign } from '@/api/process'
  import { resultJudge } from '@/utils/event.js'
  export default {
    name: 'CountersignButton',
    components: {
      ApprovalDialog,
    },
    mixins: [approvalButton],
    methods: {
      handleCountersign() {
        if (this.beforeClick) {
          resultJudge(this.beforeClick(this.alias)).then((result) => {
            if (result) {
              this.$refs.approvalDialog.openDialog()
            }
          })
        } else {
          this.$refs.approvalDialog.openDialog()
        }
      },
      handleSubmitForm(dialogFormData, cb) {
        const { userId, files, opinion } = dialogFormData
        //用户任务加签
        const data = {
          taskId: this.taskId,
          files,
          opinion,
        }
        if (this.nodeType === 'USERTASK') {
          const params = {
            ...data,
            userIds: userId,
            action: 'back',
            cb: cb,
          }
          //提交前执行前置脚本
          this.submitBefore('addSign', params)
          this.submitAfter('addSign')
        } else {
          //会签任务加签
          const params = {
            ...data,
            userId,
          }
          this.handleJointlySignTask(params, cb)
        }
      },
      //用户任务加签
      onSubmit(params) {
        const data = {
          ...params,
          data: Base64.encode(JSON.stringify(this.data)),
        }
        delete data.cb
        savaUserTaskCountersign(data)
          .then((res) => {
            if (!res.state) return this.$message.error(res.message)
            this.$message.success(res.message)
            this.dialogModeApprovalCompletionToMyTask()
            this.dialogAfterClick(this.alias)
          })
          .finally(() => {
            params.cb()
          })
      },
      //会签任务加签
      handleJointlySignTask(params, cb) {
        savaCountersign(params)
          .then((res) => {
            if (!res.state) return this.$message.warning(res.message)
            this.$message.success(res.message)
            this.dialogAfterClick(this.alias)
          })
          .finally(() => {
            cb()
          })
      },
    },
  }
</script>

<style lang="scss" scoped></style>
