<template>
  <div class="form">
    <van-nav-bar :title="$t('invoice.' + route.query.type)" :left-text="$t('common.back')" left-arrow @click-left="onClickLeft"> </van-nav-bar>
    <testForm v-model="formData.data" :formOption="formOption" :formConfig="formConfig" :rules="rules" @onSubmit="onSubmit" ref="formDom"> </testForm>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance, onMounted, reactive } from "vue";
import { showSuccessToast, showFailToast } from "vant";
import { useRoute } from "vue-router";
import { getUserInfo } from "@/utils/auth";
import testForm from "@/components/testForm/index.vue";

const proxy = getCurrentInstance().proxy;
const onClickLeft = () => history.back();
const route = useRoute();
const getDict = () => {
  proxy.post("/supplierInfo/page", { pageNum: 1, pageSize: 999 }).then((res) => {
    if (res.data.rows && res.data.rows.length > 0) {
      formConfig[0].data = res.data.rows.map((item) => {
        return {
          label: item.name,
          value: item.id,
        };
      });
    }
  });
  let query = {
    pageNum: 1,
    pageSize: 999,
    tenantId: getUserInfo().tenantId,
  };
  proxy.post("/dictTenantData/page", { ...query, dictCode: "invoice_type" }).then((res) => {
    if (res.data.rows && res.data.rows.length > 0) {
      formConfig[1].data = res.data.rows.map((item) => {
        return {
          label: item.dictValue,
          value: item.dictKey,
        };
      });
    }
  });
  proxy.get("/tenantUser/list", { pageNum: 1, pageSize: 10000, tenantId: getUserInfo().tenantId }).then((res) => {
    if (res.rows && res.rows.length > 0) {
    }
  });
};
getDict();
const formData = reactive({
  data: {
    supplyId: null,
    money: null,
    type: null,
    remark: null,
    invoiceDetailsList: [],
  },
});
const formDom = ref(null);
const formOption = reactive({
  readonly: false, //用于控制整个表单是否只读
  disabled: false,
  labelAlign: "top",
  scroll: true,
  labelWidth: "62pk",
  hiddenSubmitBtn: false,
  btnConfig: {
    isNeed: false,
    prop: "invoiceDetailsList",
    plain: true,
    listTitle: proxy.t("invoice.purchaseContract"),
    listConfig: [
      {
        type: "input",
        label: proxy.t("invoice.contractCode"),
        prop: "code",
        readonly: true,
      },
      {
        type: "input",
        label: proxy.t("invoice.contractMoney"),
        prop: "amount",
        readonly: true,
      },
      {
        type: "input",
        label: proxy.t("invoice.receivedInvoice"),
        prop: "sumInvoiceMoney",
        readonly: true,
      },
      {
        type: "input",
        label: proxy.t("invoice.relatedAmount"),
        prop: "money",
        itemType: "number",
      },
    ],
  },
});
const formConfig = reactive([
  {
    type: "picker",
    label: proxy.t("invoice.supplyName"),
    prop: "supplyId",
    itemType: "onePicker",
    showPicker: false,
    fieldNames: {
      text: "label",
      value: "value",
    },
    data: [],
    readonly: route.query.id,
    changeFn: (val, data) => {
      proxy.formChange(val, data, formData);
      proxy.get("/purchase/getNoInvoiceListBySupplyId", { supplyId: val.selectedValues[0] }).then((res) => {
        if (res.data && res.data.length > 0) {
          formData.data.invoiceDetailsList = res.data.map((item) => {
            return {
              purchaseId: item.id,
              code: item.code,
              amount: item.amount,
              sumInvoiceMoney: item.sumInvoiceMoney,
              money: null,
              remark: "",
            };
          });
        } else {
          formData.data.invoiceDetailsList = [];
        }
      });
      data.showPicker = false;
    },
  },
  {
    type: "picker",
    label: proxy.t("invoice.type"),
    prop: "type",
    itemType: "onePicker",
    showPicker: false,
    fieldNames: {
      text: "label",
      value: "value",
    },
    data: [],
  },
  {
    type: "input",
    label: proxy.t("invoice.invoiceAmount"),
    prop: "money",
    itemType: "number",
  },
]);
const rules = {
  supplyId: [{ required: true, message: proxy.t("invoice.supplyNameMsg") }],
  type: [{ required: true, message: proxy.t("invoice.typeMsg") }],
  money: [{ required: true, message: proxy.t("invoice.invoiceAmountMsg") }],
  relatedAmount: [{ required: true, message: proxy.t("invoice.relatedAmountMsg") }],
};
const onSubmit = () => {
  if (!(formData.data.invoiceDetailsList && formData.data.invoiceDetailsList.length > 0)) {
    return showFailToast(proxy.t("invoice.supplierNoContract"));
  }
  let money = 0;
  for (let i = 0; i < formData.data.invoiceDetailsList.length; i++) {
    money = parseFloat(Number(money) + Number(formData.data.invoiceDetailsList[i].money)).toFixed(2);
  }
  if (Number(money) != Number(formData.data.money)) {
    return showFailToast(proxy.t("invoice.unequalAmounts"));
  }
  proxy.post("/invoice/" + route.query.type, formData.data).then(() => {
    showSuccessToast(route.query.type === "add" ? proxy.t("common.addSuccess") : proxy.t("common.modifySuccess"));
    setTimeout(() => {
      onClickLeft();
    }, 500);
  });
};
onMounted(() => {
  if (route.query.id) {
    proxy.post("/invoice/detail", { id: route.query.id }).then((res) => {
      res.data.type = res.data.type + "";
      res.data.invoiceDetailsList = res.data.invoiceDetailsVoList.map((item) => {
        return {
          code: item.purchaseCode,
          purchaseId: item.purchaseId,
          amount: item.purchaseAmount,
          sumInvoiceMoney: item.sumMoney,
          money: item.money,
        };
      });
      formData.data = res.data;
    });
  }
});
</script>
