<template>
  <div class="form">
    <testForm
      v-model="formData.data"
      :formOption="formOption"
      :formConfig="formConfig"
      :rules="rules"
      @onSubmit="onSubmit"
      ref="formDom"
    ></testForm>
    <testForm
      v-model="formData.data"
      :formOption="formOptionOne"
      :formConfig="formConfigOne"
      :rules="rules"
      @onSubmit="onSubmit"
      ref="formDomOne"
    ></testForm>
  </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, onMounted } from "vue";
import { showSuccessToast, showFailToast } from "vant";
import { useRoute } from "vue-router";
import testForm from "@/components/testForm/index.vue";
const proxy = getCurrentInstance().proxy;
const route = useRoute();
const formDom = ref(null);
const formDomOne = ref(null);

const formData = reactive({
  data: {},
});
const rules = {
  supplyId: [
    {
      required: true,
      message: proxy.t("purchasePayment.supplyNameCanNotBeEmpty"),
    },
  ],
  type: [
    {
      required: true,
      message: proxy.t("purchasePayment.paymentTypeCanNotBeEmpty"),
    },
  ],
  advanceCode: [
    {
      required: true,
      message: proxy.t("purchasePayment.prepaymentCodeCanNotBeEmpty"),
    },
  ],
  remark: [
    {
      required: true,
      message: proxy.t("purchasePayment.descriptionCanNotBeEmpty"),
    },
  ],
  invoiceType: [
    {
      required: true,
      message: proxy.t("purchasePayment.invoiceTypeCanNotBeEmpty"),
    },
  ],
  rate: [
    {
      required: true,
      message: proxy.t("purchasePayment.taxRateCanNotBeEmpty"),
    },
  ],
  purchaseId: [
    {
      required: true,
      message: proxy.t("purchasePayment.purchaseContractCanNotBeEmpty"),
    },
  ],
  money: [
    {
      required: true,
      message: proxy.t("purchasePayment.paymentAmountCanNotBeEmpty"),
    },
  ],
  payType: [
    {
      required: true,
      message: proxy.t("purchasePayment.paymentMethonCanNotBeEmpty"),
    },
  ],
  accountManagementId: [
    {
      required: true,
      message: proxy.t("purchasePayment.paymentAccountCanNotBeEmpty"),
    },
  ],
  name: [
    {
      required: true,
      message: proxy.t("purchasePayment.accountNameCanNotBeEmpty"),
    },
  ],
};
const formOption = reactive({
  readonly: false, //用于控制整个表单是否只读
  disabled: false,
  labelAlign: "top",
  scroll: true,
  labelWidth: "62pk",
  submitBtnText: proxy.t("common.submit"),
  hiddenSubmitBtn: true,
  btnConfig: {
    isNeed: true,
    label: proxy.t("purchasePayment.paymentDetails"),
    prop: "payDetailList",
    plain: true,
    listConfig: [
      {
        type: "picker",
        label: proxy.t("purchasePayment.purchaseContract"),
        prop: "purchaseId",
        itemType: "onePicker",
        showPicker: false,
        readonly: false,
        fieldNames: {
          text: "label",
          value: "value",
        },
        data: [],
        changeFn: function (option, item, index, currentSonIndex, prop) {
          proxy.formChangeTwo(
            option,
            item,
            index,
            currentSonIndex,
            prop,
            formData
          );
          formDom.value.btnConfigCopy.listConfig[
            currentSonIndex
          ].showPicker = false;
          changePurchaseId(option.selectedValues[0], index);
        },
      },
      {
        type: "input",
        itemType: "number",
        label: proxy.t("purchasePayment.contractAmount"),
        prop: "amount",
        readonly: true,
      },
      {
        type: "input",
        itemType: "number",
        label: proxy.t("purchasePayment.paidAmount"),
        prop: "sumPayMoney",
        readonly: true,
      },
      {
        type: "input",
        itemType: "textarea",
        label: proxy.t("purchasePayment.paymentDescription"),
        prop: "remark",
        readonly: false,
      },
      {
        type: "input",
        itemType: "number",
        label: proxy.t("purchasePayment.paymentAmount"),
        prop: "money",
        readonly: false,
        changeFn: (index, val) => {
          changeMoney();
        },
      },
    ],
    clickFn: () => {
      if (
        formData.data.payDetailList &&
        formData.data.payDetailList.length > 0
      ) {
        formData.data.payDetailList.push({
          purchaseId: "",
          money: "",
          remark: "",
        });
      } else {
        formData.data.payDetailList = [
          { purchaseId: "", money: "", remark: "" },
        ];
      }
    },
  },
});
const formConfig = reactive([
  {
    type: "picker",
    label: proxy.t("purchasePayment.supplyName"),
    prop: "supplyId",
    itemType: "onePicker",
    showPicker: false,
    readonly: false,
    fieldNames: {
      text: "label",
      value: "value",
    },
    data: [],
    changeFn: function (option, item, index) {
      formData.data[item.prop] = option.selectedOptions[0].value;
      formData.data[item.prop + "Name"] = option.selectedOptions[0].label;
      formConfig[index].showPicker = false;
      changeSupply(option.selectedOptions[0].value);
    },
  },
  {
    type: "picker",
    label: proxy.t("purchasePayment.paymentTerm"),
    prop: "deadline",
    itemType: "datePickerTime",
    showPicker: false,
    readonly: false,
    needDefault: false,
  },
  // 先去掉以下选择
  {
    type: "pickerOne",
    label: proxy.t("purchasePayment.paymentType"),
    prop: "type",
    itemType: "onePicker",
    showPicker: false,
    readonly: false,
    fieldNames: {
      text: "label",
      value: "value",
    },
    data: [
      { label: "未核销", value: "0" },
      { label: "发票核销", value: "1" },
    ],
    changeFn: function (option, item, index) {
      proxy.formChange(option, item, formData);
      formConfig[index].showPicker = false;
      changeType(formData.data[item.prop]);
    },
  },
  {
    type: "pickerOne",
    label: proxy.t("purchasePayment.prepaymentCode"),
    prop: "advanceCode",
    itemType: "onePicker",
    showPicker: false,
    readonly: false,
    fieldNames: {
      text: "label",
      value: "value",
    },
    data: [],
    changeFn: function (option, item, index) {
      formData.data[item.prop] = option.selectedOptions[0].value;
      formData.data[item.prop + "Name"] = option.selectedOptions[0].label;
      formConfig[index].showPicker = false;
      changeSupply(option.selectedOptions[0].value);
    },
  },
  {
    type: "input",
    label: proxy.t("purchasePayment.paymentDescription"),
    prop: "remark",
    itemType: "textarea",
    readonly: false,
  },
  {
    type: "input",
    label: proxy.t("purchasePayment.documentNumber"),
    prop: "receiptsNum",
    itemType: "number",
    readonly: false,
  },
  {
    type: "picker",
    label: proxy.t("purchasePayment.invoiceType"),
    prop: "invoiceType",
    itemType: "onePicker",
    showPicker: false,
    readonly: false,
    fieldNames: {
      text: "label",
      value: "value",
    },
    data: [],
    changeFn: function (option, item, index) {
      proxy.formChange(option, item, formData);
      formConfig[index].showPicker = false;
      changeInvoiceType(formData.data[item.prop]);
    },
  },
  {
    type: "input",
    label: proxy.t("purchasePayment.taxRate") + "（%）",
    prop: "rate",
    itemType: "number",
    readonly: false,
  },
]);
const formOptionOne = reactive({
  readonly: false, //用于控制整个表单是否只读
  disabled: false,
  labelAlign: "top",
  scroll: true,
  labelWidth: "62pk",
  submitBtnText: proxy.t("common.submit"),
  hiddenSubmitBtn: true,
});
const formConfigOne = reactive([
  {
    type: "input",
    label: proxy.t("purchasePayment.totalPaymentAmount"),
    prop: "amount",
    itemType: "number",
    readonly: true,
  },
  {
    type: "picker",
    label: proxy.t("purchasePayment.paymentMethon"),
    prop: "payType",
    itemType: "onePicker",
    showPicker: false,
    readonly: false,
    fieldNames: {
      text: "label",
      value: "value",
    },
    data: [],
    changeFn: function (option, item, index) {
      proxy.formChange(option, item, formData);
      formConfigOne[index].showPicker = false;
    },
  },
  {
    type: "picker",
    label: proxy.t("purchasePayment.paymentAccount"),
    prop: "accountManagementId",
    itemType: "onePicker",
    showPicker: false,
    readonly: false,
    fieldNames: {
      text: "label",
      value: "value",
    },
    data: [],
    changeFn: function (option, item, index) {
      proxy.formChange(option, item, formData);
      formConfigOne[index].showPicker = false;
      changeAccount(formData.data[item.prop]);
    },
  },
  {
    type: "input",
    label: proxy.t("purchasePayment.accountName"),
    prop: "name",
    itemType: "text",
    readonly: false,
  },
  {
    type: "input",
    label: proxy.t("purchasePayment.bankAccount"),
    prop: "accountOpening",
    itemType: "text",
    readonly: false,
  },
  {
    type: "input",
    label: proxy.t("purchasePayment.bankOfDeposit"),
    prop: "openingBank",
    itemType: "text",
    readonly: false,
  },
  {
    type: "input",
    label: proxy.t("purchasePayment.interbankNumber"),
    prop: "interbankNumber",
    itemType: "text",
    readonly: false,
  },
]);
const supplierList = ref([]);
const accountList = ref([]);
const invoiceType = ref([]);
const fundsPaymentMethod = ref([]);
const contractList = ref([]);
const changeSupply = (val) => {
  if (val) {
    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 = [];
      }
      formOption.btnConfig.listConfig[0].data = contractList.value;
    });
  } else {
    contractList.value = [];
  }
  formData.data.payDetailList = [];
};
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 changePurchaseId = (val, index) => {
  const current = contractList.value.find((x) => x.value === val);
  if (current) {
    formData.data.payDetailList[index].amount = current.amount;
    formData.data.payDetailList[index].sumPayMoney = current.sumPayMoney;
    formData.data.payDetailList[index].sumInvoiceMoney =
      current.sumInvoiceMoney;
  } else {
  }
};
const changeType = (val) => {
  if (val == "1") {
    formConfig[3].type = "picker";
    proxy.get(`purchase/getAdvanceCode?money=${1}`).then((res) => {
      console.log(res, "aaa");
    });
  } else {
    formConfig[3].type = "pickerOne";
  }
};
const changeInvoiceType = (val) => {
  if (val == "1") {
    formConfig[7].type = "input";
    formData.data.rate = "13";
  } else if (val == "2") {
    formConfig[7].type = "input";
    formData.data.rate = "6";
  } else {
    formConfig[7].type = "inputOne";
    formData.data.rate = "";
  }
};
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 getDict = () => {
  proxy
    .post("/supplierInfo/page", { pageNum: 1, pageSize: 999 })
    .then((res) => {
      if (res.data.rows && res.data.rows.length > 0) {
        supplierList.value = res.data.rows.map((item) => {
          return {
            label: item.name,
            value: item.id,
          };
        });
        formConfig[0].data = supplierList.value;
      }
    });
  proxy
    .post("/accountManagement/page", { pageNum: 1, pageSize: 999 })
    .then((res) => {
      accountList.value = res.data.rows.map((item) => {
        return {
          bankName: item.name,
          accountOpening: item.accountOpening,
          openingBank: item.openingBank,
          interbankNumber: item.interbankNumber,
          label: item.alias,
          value: item.id,
        };
      });
      formConfigOne[2].data = accountList.value;
    });
  proxy.getDictOne(["invoice_type", "funds_payment_method"]).then((res) => {
    invoiceType.value = res["invoice_type"].data.map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
    fundsPaymentMethod.value = res["funds_payment_method"].data.map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
    formConfig[6].data = invoiceType.value;
    formConfigOne[1].data = fundsPaymentMethod.value;
  });
};
getDict();

const handleSubmit = async () => {
  const data = await formDom.value.validateForm().then((status) => {
    if (status) {
      return false;
    } else {
      if (
        formData.data.payDetailList &&
        formData.data.payDetailList.length > 0
      ) {
        return formDomOne.value.validateForm().then((status1) => {
          if (status1) {
            return false;
          } else {
            return true;
          }
        });
      } else {
        showFailToast(proxy.t("purchasePayment.pleaseAddPaymentDetails"));
        return false;
      }
    }
  });
  if (data) {
    return { ...formData.data };
  }
};

defineExpose({
  handleSubmit,
});
</script>

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