<script>
import orderApi from "@/api/business/purchase/purchase-order";
export default {
  name: "TuiHui",
  props: {
    // 主表
    mainData: {
      type: Array,
      require: true,
    },
    // 子表
    subtabulation: {
      type: Array,
      default: () => [],
    },
    // 退回类型 all-整单退回;line-行退回
    type: {
      type: String,
      default: "all",
    },
  },
  data() {
    return {};
  },
  computed: {
    title: {
      get() {
        let { type } = this.$props;
        if (type === "line") return "行退回";
        return "整单退回";
      },
      set() {},
    },
    disabled: {
      get() {
        let { mainData, subtabulation, type } = this.$props;
        if (type === "line") {
          // 行退回
          if (subtabulation.length > 0) {
            return this.judgeNot(mainData[0]);
          }
          return true;
        }
        // 整单退回
        if (mainData.length > 0) {
          let notList = mainData.filter((item) => this.judgeNot(item));
          return notList.length > 0;
        }
        return true;
      },
      set() {},
    },
  },
  methods: {
    onClick() {
      this.$prompt("请输入退回原因", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /\s*\S+?/,
        inputErrorMessage: "退回原因不能为空",
      })
        .then(async ({ value }) => {
          try {
            this.$modal.loading("处理中......");
            let { mainData, subtabulation } = this.$props;

            let data = mainData.map((item) => ({
              ...item,
              documentIds: subtabulation.map((sub) => Number(sub.id)),
              baskCause: value,
            }));

            let { code, msg } = await orderApi.documentsReturn(data);

            if (code === 200) {
              this.$emit("success");
              this.$notify.success({
                message: msg,
              });
            }
          } catch (error) {
          } finally {
            this.$modal.closeLoading();
          }
        })
        .catch(() => {});
    },
    judgeNot(source) {
      // status: 0=自由态，1=审批中，2=已审核，3=已驳回 4=提交中 9=已回退
      // source: 1=自动协议直采，2=协议直采，3=手工
      // isEnd:整单关闭标识
      return !(
        source.source != 3 &&
        source.isEnd === "N" &&
        (source.status == 0 || source.status == 3 || source.status == "9")
      );
    },
  },
  created() {},
};
</script>

<template>
  <el-button :size="$attrs.size" :disabled="disabled" @click="onClick">{{
    title
  }}</el-button>
</template>
