<template>
  <div style="width: 100%; padding: 0px 15px">
    <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="submit">
      <template #supplyId>
        <div style="width: 100%">
          <el-form-item prop="supplyId" label="供应商" class="margin-b-0">
            <el-select v-model="formData.data.supplyId" filterable remote reserve-keyword placeholder="请输入关键字" remote-show-suffix
                       :remote-method="remoteMethod" :loading="loadingSearch" @input="remoteMethod" style="width: 100%" @change="changeSupply" v-if="
                [30].includes(route.query.processType) ||
                !route.query.processType
              ">
              <el-option v-for="item in supplierList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            <el-select v-model="formData.data.supplyName" disabled v-else style="width: 100%">
            </el-select>
          </el-form-item>
        </div>
      </template>

      <template #payDetailList>
        <div style="width: 100%">
          <el-button type="primary" @click="clickAdd()" v-if="!judgeStatus()">添加行</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" class="margin-b-0">
                    <el-select v-model="row.purchaseId" placeholder="请选择采购订单" filterable 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="付款金额" width="180">
              <template #default="{ row, $index }">
                <div style="width: 100%">
                  <el-form-item :prop="'payDetailList.' + $index + '.money'" :rules="rules.money" :inline-message="true" class="margin-b-0">
                    <el-input-number onmousewheel="return false;" v-model="row.money" placeholder="请输入金额" style="width: 100%" :precision="2"
                                     :controls="false" :min="0" @change="changeMoney()" />
                  </el-form-item>
                </div>
              </template>
            </el-table-column>
            <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" class="margin-b-0">
                    <el-input v-model="row.remark" placeholder="请输入款项说明" style="width: 100%" />
                  </el-form-item>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80" v-if="!judgeStatus()">
              <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";
import { async } from "@antv/x6/lib/registry/marker/async";
const route = useRoute();
const { proxy } = getCurrentInstance();
const invoiceType = computed(
  () => proxy.useUserStore().allDict["invoice_type"]
);
const fundsPaymentMethod = computed(
  () => proxy.useUserStore().allDict["funds_payment_method"]
);
const payMethod = computed(() => proxy.useUserStore().allDict["pay_method"]);
const supplierList = ref([]);
const accountList = ref([]);
const contractList = ref([]);
let formData = reactive({
  data: {
    supplyId: "",
    amount: "",
    invoiceType: "",
    remark: "",
    deadline: "",
    receiptsNum: null,
    payType: "",
    currency: "",
    accountManagementId: "",
    userName: "",
    payDetailList: [],
    fileList: [],
    advanceCode: "",
    type: "",
    taxRate: null,
  },
});
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 formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  disabled: false,
});
const formConfig = computed(() => {
  return [
    {
      type: "title",
      title: "基础信息",
      label: "",
    },
    {
      type: "slot",
      slotName: "supplyId",
      label: "",
      itemWidth: 33.33,
    },
    {
      type: "date",
      prop: "deadline",
      itemType: "date",
      label: "付款期限",
      itemWidth: 33.33,
    },
    {
      type: "select",
      label: "付款类型",
      prop: "type",
      data: payMethod.value,
      itemWidth: 33.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: "treeSelect",
      prop: "companyId",
      label: "业务公司",
      data: proxy.useUserStore().allDict["tree_company_data"],
      propsTreeLabel: "deptName",
      propsTreeValue: "deptId",
      itemWidth: 33.33,
      disabled: true,
    },
    {
      type: "number",
      prop: "receiptsNum",
      label: "单据数量",
      precision: 0,
      min: 0,
      controls: false,
      itemWidth: 33.33,
    },
    {
      type: "select",
      label: "发票类型",
      prop: "invoiceType",
      data: invoiceType.value,
      itemWidth: 33,
      style: "width: 100%",
      fn: (val) => {
        if (val == "1") {
          formData.data.taxRate = 13;
        } else if (val == "2") {
          formData.data.taxRate = 6;
        } else {
          formData.data.taxRate = undefined;
        }
      },
    },
    {
      type: "number",
      prop: "taxRate",
      label: "税率 (%)",
      precision: 2,
      min: 0,
      controls: false,
      itemWidth: 33.33,
      isShow:
        formData.data.invoiceType == "1" || formData.data.invoiceType == "2",
    },
    {
      type: "upload",
      listType: "text",
      accept: "",
      prop: "fileList",
      label: "上传附件",
    },
    {
      type: "title",
      title: "付款明细",
      haveLine: true,
    },
    {
      type: "slot",
      prop: "payDetailList",
      slotName: "payDetailList",
      label: "",
    },
    {
      type: "input",
      prop: "amount",
      label: "付款总额",
      required: true,
      itemType: "text",
      disabled: true,
      itemWidth: 33.33,
    },
    {
      type: "title",
      title: "收款信息",
      haveLine: true,
    },
    {
      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" }],
  taxRate: [{ required: true, message: "请输入税率", trigger: "blur" }],
  companyId: [{ required: true, message: "请选择业务公司", trigger: "change" }],
});

const getDict = () => {
  proxy.post("/supplierInfo/page", { pageNum: 1, pageSize: 50 }).then((res) => {
    if (res.rows && res.rows.length > 0) {
      supplierList.value = res.rows.map((item) => {
        return {
          ...item,
          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 changeSupply = async (val) => {
  if (val) {
    await proxy
      .get("/ehsdPurchase/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,
              payableAmount: item.payableAmount,
              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();
  changeMoney();
};
const changeAccount = (val) => {
  if (val) {
    let data = accountList.value.filter((item) => item.value === val);
    if (data && data.length > 0) {
      formData.data.name = 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);
  console.log(data, "sss");
  if (data && data.length > 0) {
    row.amount = data[0].payableAmount;
    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) {
      return true;
    } else {
      ElMessage("请添加至少一条付款明细");
    }
    return false;
  }
  return status;
};
// 接收父组件的传值
const props = defineProps({
  queryData: Object,
});

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();
        }
      }
    }
  }
  formOption.disabled = judgeStatus();
  if (route.query && route.query.businessId) {
    proxy
      .post("/pay/detail", { id: route.query.businessId })
      .then(async (res) => {
        if (res.supplyId) {
          await changeSupply(res.supplyId);
        }
        res.payDetailList = res.payDetailVoList;
        for (const key in res) {
          formData.data[key] = res[key];
        }
        formData.data.fileList = [];
        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();
        }
        proxy
          .post("/fileInfo/getList", {
            businessIdList: [route.query.businessId],
          })
          .then((fileObj) => {
            if (
              fileObj[route.query.businessId] &&
              fileObj[route.query.businessId].length > 0
            ) {
              formData.data.fileList = fileObj[route.query.businessId].map(
                (x) => ({
                  ...x,
                  name: x.fileName,
                  url: x.fileUrl,
                })
              );
            }
          });
      });
  }
  formData.data.companyId = proxy.useUserStore().user.companyId;
});
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 = () => {
  return;
  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: isHaveOne.value ? "pointer" : "revert",
            },
            fn: isHaveOne.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: isHaveOne.value ? "pointer" : "revert",
            },
            fn: isHaveOne.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 loadingSearch = ref(false);
const remoteMethod = (keyword) => {
  if (keyword && typeof keyword === "string") {
    loadingSearch.value = true;
    proxy.post("/supplierInfo/page", { keyword }).then((res) => {
      supplierList.value = res.rows.map((x) => ({
        ...x,
        label: x.name,
        value: x.id,
      }));
      loadingSearch.value = false;
    });
  }
  return;
};
</script>

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