<template>
  <div class="approval-button-item agree-button">
    <el-button
      :type="buttonType[alias]"
      :disabled="disabled"
      :size="btnSize"
      :plain="alias === 'oppose' ? true : false"
      :class="{ 'plain-danger-btn': alias === 'oppose' }"
      :title="name.length > 4 ? name : ''"
      @click="handleAgree"
    >
      {{ name.length > 4 ? `${name.substring(0, 4)}...` : name }}
    </el-button>

    <el-drawer
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      :append-to-body="true"
      :modal="false"
      :close-on-click-modal="false"
      :size="380"
      :wrapper-closable="false"
      class="right-drawer-wrap"
      :class="{
        'dialog-model-drawer': isDialog && !isFromTaskManager,
        'horizontal-layout-drawer': layout === 'horizontal',
        'flow-module-drawer': isFromApplicationModule,
      }"
    >
      <div class="dialog__content">
        <el-form
          v-form="{ inputsDisplay: 'block' }"
          :model="formData"
          label-width="100px"
          :data-vv-scope="formScope"
          @submit.native.prevent
        >
          <ht-form-item
            :label="$t('taskToComplete.ApprovedComments')"
            class="opinion-label"
          >
            <approval-comments
              :approval-opinion="approvalOpinion"
              :approval-maxlength="approvalMaxlength"
              @get-opinion="getOpinion"
            ></approval-comments>
          </ht-form-item>
          <ht-form-item
            v-if="isShowSignature"
            :label="$t('taskToComplete.SignatureAndPassword')"
          >
            <ht-input
              v-model="signaturePassword"
              validate="required"
              show-password
            ></ht-input>
          </ht-form-item>
          <ht-form-item :label="$t('taskToComplete.ApprovedUpload')">
            <ht-file
              v-model="fileList"
              :uploading.sync="fileUploading"
              type="list"
              :downloadable="false"
            />
          </ht-form-item>
        </el-form>
      </div>
      <div class="dialog-footer__btns">
        <el-button
          type="primary"
          :loading="loading || fileUploading"
          @click="confirm"
        >
          {{ $t('Common.Confirm') }}
        </el-button>
        <el-button :disabled="loading || fileUploading" @click="handleClose">
          {{ $t('Common.Cancel') }}
        </el-button>
      </div>
    </el-drawer>

    <!-- 选择领导代审批弹窗 -->
    <leader-dialog ref="leaderDialog" />
    <!-- 选择路径跳转 -->
    <select-path-to-jump
      ref="selectPathJump"
      :alias="alias"
      :opinion-field="opinionField"
      :data="data"
    />

    <el-dialog
      title="执行人为空时由发起人指定"
      :visible.sync="executorIsEmptyDialog"
      :close-on-click-modal="false"
      :show-close="false"
      append-to-body
    >
      <el-form v-form>
        <ht-form-item label="审批人员">
          <ht-user-selector-input
            v-model="userSelectValue"
            permission="b"
            :config="{ id: 'user.id', fullname: 'user.fullname' }"
            :append-to-body="true"
            single
          ></ht-user-selector-input>
        </ht-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="confirmOk">
          {{ $t('Common.Confirm') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import req from '@/utils/request'
  import approvalButton from '@/mixins/approvalButton'
  import { BUTTON_TYPE, BUTTON_NAME_MAP, ACTION_MAP } from './const'
  import SelectPathToJump from './SelectPathToJump.vue'
  import { resultJudge } from '@/utils/event.js'
  import { getCurrentSeal } from '@/api/uc.js'

  export default {
    name: 'AgreeButton',
    components: { SelectPathToJump },
    mixins: [approvalButton],
    data() {
      return {
        buttonType: BUTTON_TYPE,
        buttonNameMap: BUTTON_NAME_MAP,
        formData: {},
        dialogTitle: '审批同意',
        executorIsEmptyDialog: false,
        user: {
          id: '',
          fullname: '',
        },
        userSelectValue: '',
        EipUserSelectorData: {},
        executorIsEmptyInsts: {},
        executorIsEmptyRow: {},
        fileUploading: false,
        approvalMaxlength: 500,
      }
    },
    computed: {
      formScope() {
        return `${this.alias}Form`
      },
    },
    methods: {
      handleAgree() {
        if (this.beforeClick) {
          resultJudge(this.beforeClick(this.alias)).then((result) => {
            if (result) {
              this.getTaskIsLock('agree')
            } else {
              this.loading = false
            }
          })
        } else {
          this.getTaskIsLock('agree')
        }
      },

      //打开弹窗
      openAgreeDialog() {
        let aliasList = ['opposeTrans', 'agreeTrans']
        this.dialogVisible = true
        this.loading = false
        this.setDialogTitle()
        this.afterOpenDialog()
      },
      //设置弹窗标题
      setDialogTitle() {
        this.dialogTitle = `审批${ACTION_MAP[this.alias]}`
        //获取表单数据,审批意见
      },
      //获取表单，审批意见
      getData() {
        //completaData,opinionField,boData,appendOptinion
      },
      //打开弹窗后获取审批意见
      afterOpenDialog() {
        this.getApprovalOpinionByInstIdAndTaskId()
      },

      //点击确定按钮
      confirm(alias) {
        this.$root.$validator.validateAll(this.formScope).then((result) => {
          this.loading = true
          if (!result) {
            this.loading = false
            return this.$message.error('有必填的内容未填写。')
          }
          // if (this.beforeClick) {

          if (this.dialogBeforeClick) {
            // resultJudge(this.beforeClick(alias)).then((result) => {
            resultJudge(this.dialogBeforeClick(this.alias)).then((result) => {
              if (result) {
                this.doSubmit()
              } else {
                this.loading = false
              }
            })
          } else {
            this.doSubmit()
          }
        })
      },
      doSubmit(alias) {
        if (this.alias === 'agree' && this.signatureField) {
          this.handleSignature()
        }
        if (this.isShowSignature) {
          getCurrentSeal(this.signaturePassword, this.secretFree).then(
            (res) => {
              if (res.state) {
                setTimeout(() => {
                  this.submitBefore('agree', 'agreeForm')
                }, 500)
              } else {
                this.loading = false
                this.$message.error(res.message)
              }
              this.submitAfter('agree')
            }
          )
        } else {
          setTimeout(() => {
            this.submitBefore('agree', 'agreeForm')
          }, 500)
          this.submitAfter('agree')
        }
      },
      //处理人配置审批人后确认事件
      confirmOk() {
        if (!(this.user.fullname && this.user.id)) {
          this.$message.warning('请选择审批人员')
          return
        }
        let map = {
          userId: this.user.id,
          userName: this.user.fullname,
          taskId: this.executorIsEmptyRow.assignTaskId,
          instId: this.instId,
        }
        req
          .post(
            window.context.bpmRunTime + '/runtime/instance/v1/assignBpmTask',
            map
          )
          .then((res) => {
            if (res.state) {
              this.$message.success(res.message)
              this.$nextTick(() => {
                this.getNextTaskByDefKeyAndDefId()
              })
            } else {
              this.$message.error(res.message)
            }
            this.executorIsEmptyDialog = false
          })
          .catch((e) => {
            this.executorIsEmptyDialog = false
            // this.getNextTaskByDefKeyAndDefId()
          })
      },
    },
  }
</script>

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