<template>
  <div style="width: 100%; padding: 0px 15px">
    <byForm
      :formConfig="formConfig"
      :formOption="formOption"
      v-model="formData.data"
      :rules="rules"
      ref="submit"
    >
      <template #deadline>
        <div style="width: 100%">
          <el-date-picker
            v-model="formData.data.deadline"
            type="date"
            placeholder="请选择付款期限"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </div>
      </template>
      <template #receiptsNum>
        <div style="width: 100%">
          <el-input-number
            onmousewheel="return false;"
            v-model="formData.data.receiptsNum"
            placeholder="请输入单据数量"
            :min="0"
            :precision="0"
            :controls="false"
            style="width: 100%"
          />
        </div>
      </template>
      <template #rate>
        <div style="width: 100%">
          <el-input-number
            onmousewheel="return false;"
            v-model="formData.data.rate"
            placeholder="请输入税率"
            :min="0"
            :max="100"
            :precision="2"
            :controls="false"
            style="width: 100%"
          />
        </div>
      </template>
      <template #fileList>
        <div style="width: 100%">
          <el-upload
            v-model:fileList="fileList"
            action="https://winfaster.obs.cn-south-1.myhuaweicloud.com"
            multiple
            :data="uploadData"
            :before-upload="uploadFile"
            :on-preview="onPreviewFile"
          >
            <el-button>选择</el-button>
          </el-upload>
        </div>
      </template>
      <template #payDetailList>
        <div style="width: 100%">
          <el-button type="primary" @click="clickAdd()">添加行</el-button>
          <el-table
            :data="formData.data.payDetailList"
            style="width: 100%; margin-top: 16px"
          >
            <el-table-column label="采购合同" width="220">
              <template #default="{ row, $index }">
                <div style="width: 100%">
                  <el-form-item
                    :prop="'payDetailList.' + $index + '.purchaseId'"
                    :rules="rules.purchaseId"
                    :inline-message="true"
                  >
                    <el-select
                      v-model="row.purchaseId"
                      placeholder="请选择采购合同"
                      style="width: 100%"
                      @change="changePurchaseId(row, true)"
                    >
                      <el-option
                        v-for="item in contractList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="合同金额" width="140" />
            <el-table-column
              prop="sumPayMoney"
              label="已付款金额"
              width="140"
            />
            <el-table-column
              prop="sumInvoiceMoney"
              label="已收发票金额"
              width="140"
            />
            <el-table-column label="款项说明">
              <template #default="{ row, $index }">
                <div style="width: 100%">
                  <el-form-item
                    :prop="'payDetailList.' + $index + '.remark'"
                    :rules="rules.remark"
                    :inline-message="true"
                  >
                    <el-input
                      v-model="row.remark"
                      placeholder="请输入款项说明"
                      style="width: 100%"
                    />
                  </el-form-item>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="付款金额" width="180">
              <template #default="{ row, $index }">
                <div style="width: 100%">
                  <el-form-item
                    :prop="'payDetailList.' + $index + '.money'"
                    :rules="rules.money"
                    :inline-message="true"
                  >
                    <el-input-number
                      onmousewheel="return false;"
                      v-model="row.money"
                      placeholder="请输入金额"
                      style="width: 100%"
                      :precision="2"
                      :controls="false"
                      :min="0"
                      :disabled="row.id"
                      @change="changeMoney()"
                    />
                  </el-form-item>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="{ row, $index }">
                <el-button type="primary" link @click="handleRemove($index)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <br />
        </div>
      </template>
    </byForm>
  </div>
</template>

<script setup>
import byForm from "@/components/byForm/index";
import { ElMessage } from "element-plus";
import useUserStore from "@/store/modules/user";
import { useRoute } from "vue-router";

const route = useRoute();
const { proxy } = getCurrentInstance();
const supplierList = ref([]);
const invoiceType = ref([]);
const fundsPaymentMethod = ref([]);
const accountList = ref([]);
const contractList = ref([]);
let formData = reactive({
  data: {
    supplyId: "",
    amount: "",
    invoiceType: "",
    remark: "",
    deadline: "",
    receiptsNum: undefined,
    payType: "",
    currency: "",
    accountManagementId: "",
    userName: "",
    payDetailList: [],
    fileList: [],
    advanceCode: "",
    type: "",
    rate: undefined,
  },
});
const submit = ref(null);
const judgeStatus = () => {
  if (route.query.processType == 20 || route.query.processType == 10) {
    return true;
  }
  if (props.queryData.recordList && props.queryData.recordList.length > 0) {
    let data = props.queryData.recordList.filter(
      (item) => item.status === 2 && item.nodeType !== 1
    );
    if (data && data.length > 0) {
      return true;
    }
  }
  return false;
};
const payMethod = ref([]);
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
  disabled: false,
});
const formConfig = computed(() => {
  return [
    {
      type: "title",
      title: "基础信息",
      label: "",
    },
    {
      type: "select",
      label: "归属公司",
      prop: "corporationId",
      data: companyData.value,
      itemWidth: 33,
      style: "width: 100%",
    },
    {
      type: "select",
      label: "供应商",
      prop: "supplyId",
      data: supplierList.value,
      fn: (val) => {
        changeSupply(val);
      },
      itemWidth: 35,
      style: "width: 94%",
    },
    {
      type: "slot",
      prop: "deadline",
      slotName: "deadline",
      label: "付款期限",
      itemWidth: 33,
    },
    {
      type: "select",
      label: "付款类型",
      prop: "type",
      data: payMethod.value,
      itemWidth: 33,
      style: "width: 100%",
      fn: () => {
        formData.data.advanceCode = "";
      },
    },
    // {
    //   type: "select",
    //   label: "预付款单号",
    //   prop: "advanceCode",
    //   data: advanceCode.value,
    //   itemWidth: 34,
    //   style: "width: 100%",
    //   isShow: formData.data.type == "1",
    // },
    {
      type: "input",
      prop: "remark",
      label: "付款说明",
      itemType: "textarea",
    },
    {
      type: "slot",
      prop: "receiptsNum",
      slotName: "receiptsNum",
      label: "单据数量",
      itemWidth: 33,
    },
    {
      type: "select",
      label: "发票类型",
      prop: "invoiceType",
      data: invoiceType.value,
      itemWidth: 33,
      style: "width: 100%",
      fn: (val) => {
        if (val == "1") {
          formData.data.rate = 13;
        } else if (val == "2") {
          formData.data.rate = 6;
        } else {
          formData.data.rate = undefined;
        }
      },
    },
    {
      type: "slot",
      prop: "rate",
      slotName: "rate",
      label: "税率 (%)",
      itemWidth: 34,
      isShow:
        formData.data.invoiceType == "1" || formData.data.invoiceType == "2",
    },
    {
      type: "slot",
      prop: "fileList",
      slotName: "fileList",
      label: "上传附件",
    },
    {
      type: "slot",
      prop: "payDetailList",
      slotName: "payDetailList",
      label: "付款明细",
    },
    {
      type: "input",
      prop: "amount",
      label: "付款总额",
      required: true,
      itemType: "text",
      disabled: true,
      itemWidth: 50,
    },
    {
      label: "收款信息",
    },
    {
      type: "select",
      label: "付款方式",
      prop: "payType",
      data: fundsPaymentMethod.value,
      itemWidth: 50,
    },
    {
      type: "select",
      label: "付款账户",
      prop: "accountManagementId",
      data: accountList.value,
      itemWidth: 50,
      fn: (val) => {
        changeAccount(val);
      },
    },
    {
      type: "input",
      prop: "name",
      label: "户名",
      required: true,
      itemType: "text",
      itemWidth: 50,
    },
    {
      type: "input",
      prop: "accountOpening",
      label: "银行账号",
      required: true,
      itemType: "text",
      itemWidth: 50,
    },
    {
      type: "input",
      prop: "openingBank",
      label: "开户银行",
      required: true,
      itemType: "text",
      itemWidth: 50,
    },
    {
      type: "input",
      prop: "interbankNumber",
      label: "联行号",
      required: true,
      itemType: "text",
      itemWidth: 50,
    },
  ];
});
const rules = ref({
  supplyId: [{ required: true, message: "请选择供应商", trigger: "change" }],
  invoiceType: [
    { required: true, message: "请选择发票类型", trigger: "change" },
  ],
  payType: [{ required: true, message: "请选择付款方式", trigger: "change" }],
  // accountManagementId: [{ required: true, message: "请选择付款账户", trigger: "change" }],
  purchaseId: [
    { required: true, message: "请选择采购合同", trigger: "change" },
  ],
  money: [{ required: true, message: "请输入付款金额", trigger: "blur" }],
  name: [{ required: true, message: "请输入户名", trigger: "blur" }],
  advanceCode: [
    { required: true, message: "请选择预付款单号", trigger: "change" },
  ],
  type: [{ required: true, message: "请选择付款类型", trigger: "change" }],
  rate: [{ required: true, message: "请输入税率", trigger: "blur" }],
  corporationId: [
    { required: true, message: "请选择归属公司", trigger: "change" },
  ],
});
const fileList = ref([]);
const uploadData = ref({});
const companyData = ref([]);
const getDict = () => {
  proxy
    .post("/corporation/page", { pageNum: 1, pageSize: 9999 })
    .then((res) => {
      companyData.value = res.rows.map((x) => ({
        ...x,
        label: x.name,
        value: x.id,
      }));
    });

  proxy
    .post("/dictTenantData/page", {
      pageNum: 1,
      pageSize: 999,
      dictCode: "invoice_type",
      tenantId: useUserStore().user.tenantId,
    })
    .then((res) => {
      if (res.rows && res.rows.length > 0) {
        invoiceType.value = res.rows.map((item) => {
          return {
            label: item.dictValue,
            value: item.dictKey,
          };
        });
      }
    });
  proxy
    .post("/dictTenantData/page", {
      pageNum: 1,
      pageSize: 999,
      dictCode: "funds_payment_method",
      tenantId: useUserStore().user.tenantId,
    })
    .then((res) => {
      if (res.rows && res.rows.length > 0) {
        fundsPaymentMethod.value = res.rows.map((item) => {
          return {
            label: item.dictValue,
            value: item.dictKey,
          };
        });
      }
    });
  proxy
    .post("/dictTenantData/page", {
      pageNum: 1,
      pageSize: 999,
      dictCode: "pay_method",
      tenantId: useUserStore().user.tenantId,
    })
    .then((res) => {
      if (res.rows && res.rows.length > 0) {
        payMethod.value = res.rows.map((item) => {
          return {
            label: item.dictValue,
            value: item.dictKey,
          };
        });
      }
    });
  proxy
    .post("/supplierInfo/page", { pageNum: 1, pageSize: 999 })
    .then((res) => {
      if (res.rows && res.rows.length > 0) {
        supplierList.value = res.rows.map((item) => {
          return {
            label: item.name,
            value: item.id,
          };
        });
      }
    });
  proxy
    .post("/accountManagement/page", { pageNum: 1, pageSize: 999 })
    .then((res) => {
      accountList.value = res.rows.map((item) => {
        return {
          bankName: item.name,
          accountOpening: item.accountOpening,
          openingBank: item.openingBank,
          interbankNumber: item.interbankNumber,
          label: item.alias,
          value: item.id,
        };
      });
    });
};
getDict();
const uploadFile = async (file) => {
  const res = await proxy.post("/fileInfo/getSing", { fileName: file.name });
  uploadData.value = res.uploadBody;
  file.id = res.id;
  file.fileName = res.fileName;
  file.fileUrl = res.fileUrl;
  return true;
};
const onPreviewFile = (file) => {
  window.open(file.raw.fileUrl, "_blank");
};
const changeSupply = async (val) => {
  if (val) {
    await proxy
      .get("/purchase/getListBySupplyId", { supplyId: val })
      .then((res) => {
        if (res.data && res.data.length > 0) {
          contractList.value = res.data.map((item) => {
            return {
              value: item.id,
              label: item.code,
              amount: item.amount,
              sumPayMoney: item.sumPayMoney,
              sumInvoiceMoney: item.sumInvoiceMoney,
            };
          });
        } else {
          contractList.value = [];
        }
      });
  } else {
    contractList.value = [];
  }
  formData.data.payDetailList = [];
  getDecisionAids();
};
const clickAdd = () => {
  if (formData.data.payDetailList && formData.data.payDetailList.length > 0) {
    formData.data.payDetailList.push({
      purchaseId: "",
      money: undefined,
      remark: "",
    });
  } else {
    formData.data.payDetailList = [
      { purchaseId: "", money: undefined, remark: "" },
    ];
  }
};
const handleRemove = (index) => {
  formData.data.payDetailList.splice(index, 1);
  getDecisionAids();
};
const changeAccount = (val) => {
  if (val) {
    let data = accountList.value.filter((item) => item.value === val);
    if (data && data.length > 0) {
      formData.data.bankName = data[0].bankName;
      formData.data.accountOpening = data[0].accountOpening;
      formData.data.openingBank = data[0].openingBank;
      formData.data.interbankNumber = data[0].interbankNumber;
    }
  }
};
const changePurchaseId = (row, status) => {
  let data = contractList.value.filter((item) => item.value === row.purchaseId);
  if (data && data.length > 0) {
    row.amount = data[0].amount;
    row.sumPayMoney = data[0].sumPayMoney;
    row.sumInvoiceMoney = data[0].sumInvoiceMoney;
  } else {
    row.amount = "";
    row.sumPayMoney = "";
    row.sumInvoiceMoney = "";
  }
  if (status) {
    getDecisionAids();
  }
};
const changeMoney = () => {
  let money = 0;
  for (let i = 0; i < formData.data.payDetailList.length; i++) {
    if (formData.data.payDetailList[i].money) {
      money = parseFloat(
        Number(money) + Number(formData.data.payDetailList[i].money)
      ).toFixed(2);
    }
  }
  formData.data.amount = money;
};
const handleSubmit = async () => {
  let status = await submit.value.handleSubmit(() => {});
  if (status) {
    if (formData.data.payDetailList && formData.data.payDetailList.length > 0) {
      if (fileList.value && fileList.value.length > 0) {
        formData.data.fileList = fileList.value.map((item) => {
          return {
            id: item.raw.id,
            fileName: item.raw.fileName,
            fileUrl: item.raw.fileUrl,
          };
        });
      }
      return true;
    } else {
      ElMessage("请添加至少一条付款明细");
    }
    return false;
  }
  return status;
};
// 接收父组件的传值
const props = defineProps({
  queryData: Object,
});
watch(
  props.queryData,
  () => {
    formOption.disabled = judgeStatus();
    if (
      props.queryData &&
      ["10", "20", "30"].includes(route.query.processType)
    ) {
      for (var text in props.queryData) {
        formData.data[text] = props.queryData[text];
      }
      if (formData.data.fileList && formData.data.fileList.length > 0) {
        fileList.value = formData.data.fileList.map((item) => {
          return {
            raw: item,
            name: item.fileName,
            url: item.fileUrl,
          };
        });
      } else {
        fileList.value = [];
      }
      if (
        route.query.processType !== "30" &&
        formData.data.payDetailList &&
        formData.data.payDetailList.length
      ) {
        let ids = formData.data.payDetailList.map((item) => item.purchaseId);
        if (ids && ids.length > 0) {
          proxy.post("/purchase/getListInId", ids).then((res) => {
            if (res && res.length > 0) {
              contractList.value = res.map((item) => {
                return {
                  value: item.id,
                  label: item.code,
                };
              });
            } else {
              contractList.value = [];
            }
          });
        }
      }
      getDecisionAids();
    }
  },
  {
    deep: true,
  }
);
onMounted(async () => {
  if (props.queryData.supplyIdTwo) {
    formData.data.supplyIdTwo = props.queryData.supplyIdTwo;
    await changeSupply(formData.data.supplyIdTwo);
    if (props.queryData.ids) {
      let ids = props.queryData.ids.split(",");
      if (ids && ids.length > 0) {
        for (let i = 0; i < ids.length; i++) {
          if (contractList.value && contractList.value.length > 0) {
            let data = contractList.value.filter(
              (item) => item.value === ids[i]
            );
            if (data && data.length > 0) {
              if (
                formData.data.payDetailList &&
                formData.data.payDetailList.length > 0
              ) {
                formData.data.payDetailList.push({
                  purchaseId: ids[i],
                  money: undefined,
                  remark: "",
                });
              } else {
                formData.data.payDetailList = [
                  { purchaseId: ids[i], money: undefined, remark: "" },
                ];
              }
            }
          }
        }
        if (
          formData.data.payDetailList &&
          formData.data.payDetailList.length > 0
        ) {
          for (let i = 0; i < formData.data.payDetailList.length; i++) {
            changePurchaseId(formData.data.payDetailList[i]);
          }
          getDecisionAids();
        }
      }
    }
  }
});
// 判断当前用户有无销售合同页面权限
const isHave = ref(false);
if (
  useUserStore().permissions &&
  useUserStore().permissions.includes("contract")
) {
  isHave.value = true;
}
// 判断当前用户有无采购合同页面权限
const isHavePurchase = ref(false);
if (
  useUserStore().permissions &&
  useUserStore().permissions.includes("alreadyPurchase")
) {
  isHavePurchase.value = true;
}

const getFormData = () => {
  return proxy.deepClone(formData.data);
};
// 向父组件暴露
defineExpose({
  getFormData,
  handleSubmit,
});
let auxiliaryData = ref([
  {
    label: "关联销售合同",
    data: [],
  },
  {
    label: "到货数据",
    data: [],
  },
  {
    label: "质检数据",
    data: [],
  },
]);
const emit = defineEmits(["auxiliaryChange"]);
const getDecisionAids = () => {
  let data = {
    purchaseIdList: [],
  };
  if (formData.data.payDetailList && formData.data.payDetailList.length > 0) {
    data.purchaseIdList = formData.data.payDetailList.map(
      (item) => item.purchaseId
    );
  }
  proxy.post("/contract/payDecisionAid", data).then((res) => {
    if (res.contractList && res.contractList.length > 0) {
      auxiliaryData.value[0].data = res.contractList.map((item) => {
        return [
          {
            label: "合同编号",
            value: item.code,
            style: {
              color: "#0084FF",
              cursor: isHave.value ? "pointer" : "revert",
            },
            fn: isHave.value ? handlePushRoute : () => {},
            id: item.id,
            num: 1,
          },
          {
            label: "下单日期",
            value: item.createTime,
            id: item.id,
            num: 1,
          },
        ];
      });
    } else {
      auxiliaryData.value[0].data = [];
    }
    if (res.purchaseInfoList && res.purchaseInfoList.length > 0) {
      auxiliaryData.value[1].data = res.purchaseInfoList.map((item) => {
        return [
          {
            label: "合同编号",
            value: item.purchaseCode,
            style: {
              color: "#0084FF",
              cursor: isHavePurchase.value ? "pointer" : "revert",
            },
            fn: isHavePurchase.value ? handlePushRouteOne : () => {},
            id: item.purchaseId,
            num: 1,
          },
          {
            label: "物品编码",
            value: item.productCode,
            id: item.productId,
            num: 1,
          },
          {
            label: "物品名称",
            value: item.productName,
            id: item.productId,
            num: 1,
          },
          {
            label: "采购数量",
            value: item.purchaseQuantity,
            id: item.productId,
            num: 1,
          },
          {
            label: "到货数量",
            value: item.invoiceQuantity,
            id: item.productId,
            num: 1,
          },
        ];
      });
      auxiliaryData.value[2].data = res.purchaseInfoList.map((item) => {
        let odds = 0;
        if (item.invoiceQuantity && item.qualifiedCount) {
          odds = parseFloat(
            (Number(item.qualifiedCount) / Number(item.invoiceQuantity)) * 100
          ).toFixed(2);
        }
        return [
          {
            label: "合同编号",
            value: item.purchaseCode,
            style: {
              color: "#0084FF",
              cursor: isHavePurchase.value ? "pointer" : "revert",
            },
            fn: isHavePurchase.value ? handlePushRouteOne : () => {},
            id: item.purchaseId,
            num: 1,
          },
          {
            label: "物品编码",
            value: item.productCode,
            id: item.productId,
            num: 1,
          },
          {
            label: "物品名称",
            value: item.productName,
            id: item.productId,
            num: 1,
          },
          {
            label: "到货数量",
            value: item.invoiceQuantity,
            id: item.productId,
            num: 1,
          },
          {
            label: "合格率",
            value: odds + "%",
            id: item.productId,
            num: 1,
          },
        ];
      });
    } else {
      auxiliaryData.value[1].data = [];
      auxiliaryData.value[2].data = [];
    }
    let list = proxy.deepClone(auxiliaryData.value);
    if (!(list[0].data && list[0].data.length > 0)) {
      list.splice(0, 1);
    }
    emit("auxiliaryChange", list);
  });
};
const handlePushRoute = (row) => {
  proxy.$router.push({
    name: "Contract",
    query: {
      code: row.value,
    },
  });
};
const handlePushRouteOne = (row) => {
  proxy.$router.push({
    name: "AlreadyPurchase",
    query: {
      code: row.value,
    },
  });
};
</script>

<style lang="scss" scoped>
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>
