<template>
  <el-col :span="16" :offset="6" v-loading="loading">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="审批建议" prop="reason" style="margin-bottom: 20px">
        <el-input
          v-model="form.reason"
          type="textarea"
          :rows="3"
          maxlength="500"
          show-word-limit
          placeholder="请输入审批建议"
        />
      </el-form-item>
    </el-form>
    <div class="actions">
      <el-button
        v-click-once
        type="success"
        size="mini"
        icon="el-icon-check"
        :loading="loading"
        @click="handleAudit(1)"
      >
        通过
      </el-button>
      <el-button
        v-click-once
        type="danger"
        size="mini"
        icon="el-icon-close"
        :loading="loading"
        @click="handleAudit(0)"
      >
        驳回
      </el-button>
    </div>
  </el-col>
</template>

<script>
  import { approveTaskWithVariables, rejectTask } from '@/api/bpm/task';

  export default {
    name: 'StockBatchChangeSubmit',
    props: {
      businessId: {
        default: ''
      },
      taskId: {
        default: ''
      },
      id: {
        default: ''
      },
      taskDefinitionKey: {
        default: ''
      }
    },
    data() {
      return {
        loading: false,
        form: {
          reason: '同意'
        },
        rules: {
          reason: [
            {
              required: true,
              whitespace: true,
              message: '请输入审批建议',
              trigger: 'blur'
            }
          ]
        }
      };
    },
    methods: {
      /** 校验审批意见后执行当前流程任务。 */
      handleAudit(status) {
        this.$refs.formRef.validate((valid) => {
          if (valid) {
            this.submitTask(status);
          }
        });
      },
      async submitTask(status) {
        const API = status ? approveTaskWithVariables : rejectTask;
        this.loading = true;
        try {
          const payload = {
            id: this.taskId,
            reason: this.form.reason
          };
          if (status) {
            payload.variables = { pass: true };
          }
          const res = await API(payload);
          // 仅接口明确返回成功码时关闭处理弹窗并刷新待办。
          if (res && res.data && (res.data.code === 0 || res.data.code === '0')) {
            this.$emit('handleAudit', {
              status,
              title: status === 0 ? '驳回' : ''
            });
          }
        } finally {
          this.loading = false;
        }
      }
    }
  };
</script>

<style scoped lang="scss">
  .actions {
    margin: 0 0 20px 10%;
    font-size: 14px;
  }
</style>
