<template>
  <div class="approval-form">
    <el-button
      size="mini"
      style="margin: 0 10px 0; width: calc((100% - 20px) / 2)"
      type="primary"
      icon="el-icon-check"
      @click.native="handleCheck(AGREE)"
      >同意</el-button
    >
    <el-popover placement="top" width="400" trigger="click" ref="popover">
      <el-form :model="dialogForm" size="mini" ref="form" :rules="rules">
        <el-form-item prop="remark">
          <el-input
            type="textarea"
            placeholder="驳回意见"
            v-model="dialogForm.remark"
            size="mini"
            :rows="2"
          >
          </el-input
        ></el-form-item>
        <el-form-item>
          <el-button @click.native="handleCancel" plain>取消</el-button>
          <el-button type="primary" @click.native="handleCheck(DISAGREE)"
            >确定</el-button
          >
        </el-form-item>
      </el-form>
      <el-button
        slot="reference"
        size="mini"
        style="margin: 0; width: calc((100% - 20px) / 2)"
        type="danger"
        icon="el-icon-close"
        plain
        @click.native="() => (popoverVisible = true)"
        >驳回</el-button
      >
    </el-popover>
  </div>
</template>

<script>
import { putFlowCheck } from "@/api/approval";
export default {
  props: {
    // 流程id
    flowId: {
      type: String,
      default: "",
    },
  },
  inject: ["handleClosePreviewDialog", "loadData"],
  data() {
    return {
      AGREE: 1,
      DISAGREE: -2,
      checkStatus: 1, //1同意 -2驳回
      dialogForm: {
        remark: "", //驳回意见
      },
      rules: {
        remark: [
          {
            required: true,
            message: "请输入驳回意见",
            trigger: "blur",
          },
        ],
      },
      popoverVisible: false,
    };
  },
  methods: {
    handleCheck(checkStatus) {
      if (checkStatus == this.DISAGREE) {
        this.$refs.form.validate(async (valid) => {
          if (valid) {
            const { remark } = this.dialogForm;
            this.submit(checkStatus, remark);
          }
        });
      } else {
        this.submit(checkStatus);
      }
    },
    handleCancel() {
      this.$refs.popover.doClose();
      this.handleClosePreviewDialog();
      this.$refs.form.resetFields();
    },

    async submit(checkStatus, remark) {
      const params = {
        checkStatus,
        remark,
        id: this.flowId,
      };
      if (!remark) {
        params.remark = "";
      }
      let res = await putFlowCheck(params);
      if (res.code == 0) {
        this.$message.success("操作成功！");
        // 关闭弹窗
        this.handleClosePreviewDialog();
        // 重新加载审批列表
        this.loadData();
        // 重置数据
        this.$refs.form.resetFields();
        if (this.$refs.popover) {
          this.$refs.popover.doClose();
        }
      }
    },
  },
};
</script>
