<template>
  <div class="form">
    <van-nav-bar
      :title="$t('salesContract.name')"
      :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, 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 formData = reactive({
  data: {
    salesContractDetailsList: [],
  },
});
const rules = {
  customerId: [
    {
      required: true,
      message: proxy.t("salesContract.pleaseSelectTheCustomerName"),
    },
  ],
  // deliveryDate: [
  //   {
  //     required: true,
  //     message: proxy.t("salesContract.pleaseSelectTheDeliveryDeadline"),
  //   },
  // ],
  payMethod: [
    {
      required: true,
      message: proxy.t("salesContract.pleaseSelectThePaymentMethod"),
    },
  ],
  freightPayer: [
    {
      required: true,
      message: proxy.t("salesContract.PleaseSelectTheFreightPayer"),
    },
  ],
  productId: [
    {
      required: true,
      message: proxy.t("salesContract.pleaseSelectTheProductName"),
    },
  ],
  isCustomized: [
    {
      required: true,
      message: proxy.t("salesContract.pleaseSelectWhetherToCustomize"),
    },
  ],
  unitPrice: [
    {
      required: true,
      message: proxy.t("salesContract.pleaseEnterTheUnitPrice"),
    },
  ],
  quantity: [
    {
      required: true,
      message: proxy.t("salesContract.pleaseEnterTheQuantity"),
    },
  ],
};
const formOption = reactive({
  readonly: false, //用于控制整个表单是否只读
  disabled: false,
  labelAlign: "top",
  scroll: true,
  labelWidth: "62pk",
  hiddenSubmitBtn: false,
  btnConfig: {
    isNeed: true,
    prop: "salesContractDetailsList",
    plain: true,
    listTitle: proxy.t("salesContract.contractDetails"),
    listConfig: [
      {
        type: "picker",
        label: proxy.t("salesContract.productName"),
        prop: "productId",
        itemType: "onePicker",
        showPicker: false,
        readonly: false,
        fieldNames: {
          text: "label",
          value: "value",
        },
        data: [],
        isNeedSearch: true, //是否需要关键字过滤数据
        searchKeyword: "",
        onSearchData: (keyword) => {
          getProductData(keyword);
        },
      },
      {
        type: "picker",
        label: proxy.t("salesContract.whetherToCustomize"),
        prop: "isCustomized",
        itemType: "onePicker",
        showPicker: false,
        readonly: false,
        fieldNames: {
          text: "label",
          value: "value",
        },
        data: [
          {
            label: proxy.t("salesContract.yes"),
            value: "1",
          },
          {
            label: proxy.t("salesContract.no"),
            value: "0",
          },
        ],
      },
      {
        type: "input",
        itemType: "number",
        label: proxy.t("salesContract.unitPrice"),
        prop: "unitPrice",
        clearable: true,
        changeFn: (index, val) => {
          changeAmount(index);
        },
      },
      {
        type: "input",
        itemType: "digit",
        label: proxy.t("salesContract.quantity"),
        prop: "quantity",
        clearable: true,
        changeFn: (index, val) => {
          changeAmount(index);
        },
      },
      {
        type: "input",
        itemType: "number",
        label: proxy.t("salesContract.amountSubtotal"),
        prop: "total",
        placeholder: proxy.t(
          "salesContract.automaticallyCalculatedBasedOnUnitPriceAndQuantity"
        ),
        readonly: true,
      },
      {
        type: "input",
        itemType: "textarea",
        label: "备注",
        prop: "productRemark",
      },
    ],
    clickFn: () => {
      if (
        formData.data.salesContractDetailsList &&
        formData.data.salesContractDetailsList.length > 0
      ) {
        formData.data.salesContractDetailsList.push({
          productId: "",
          quantity: "",
        });
      } else {
        formData.data.salesContractDetailsList = [
          {
            productId: "",
            quantity: "",
          },
        ];
      }
    },
  },
});
const formConfig = reactive([
  {
    type: "picker",
    label: "卖方公司",
    prop: "sellCorporationId",
    itemType: "onePicker",
    showPicker: false,
    fieldNames: {
      text: "label",
      value: "value",
    },
    data: [],
    changeFn: (val, data) => {
      proxy.formChange(val, data, formData);
      changeSellId(val.selectedValues[0]);
      data.showPicker = false;
    },
  },
  {
    type: "input",
    itemType: "text",
    label: "国家",
    prop: "sellCountryName",
  },
  {
    type: "input",
    itemType: "text",
    label: "省",
    prop: "sellProvinceName",
  },
  {
    type: "input",
    itemType: "text",
    label: "城市",
    prop: "sellCityName",
  },
  {
    type: "input",
    itemType: "textarea",
    label: "详细地址",
    prop: "sellAddress",
  },
  {
    type: "picker",
    label: "收款账号",
    prop: "shroffAccountId",
    itemType: "onePicker",
    showPicker: false,
    fieldNames: {
      text: "label",
      value: "value",
    },
    data: [],
    changeFn: (val, data) => {
      proxy.formChange(val, data, formData);
      changeShroffAccount(val.selectedValues[0]);
      data.showPicker = false;
    },
  },
  {
    type: "input",
    itemType: "text",
    label: "账户名",
    prop: "sellAccountName",
  },
  {
    type: "input",
    itemType: "text",
    label: "开户行",
    prop: "sellOpeningBank",
  },
  {
    type: "input",
    itemType: "text",
    label: "账号",
    prop: "sellAccountOpening",
  },
  {
    type: "input",
    itemType: "text",
    label: "银行号",
    prop: "sellInterbankNumber",
  },
  {
    type: "picker",
    label: proxy.t("salesContract.customerName"),
    prop: "customerId",
    itemType: "onePicker",
    showPicker: false,
    fieldNames: {
      text: "label",
      value: "value",
    },
    data: [],
    isNeedSearch: true, //是否需要关键字过滤数据
    searchKeyword: "",
    onSearchData: (keyword) => {
      getCustomerData(keyword);
    },
  },
  {
    type: "picker",
    label: proxy.t("salesContract.deliveryDeadline"),
    prop: "deliveryDate",
    itemType: "datePicker",
    showPicker: false,
    split: "-",
    columnsType: ["year", "month", "day"],
  },
  {
    type: "picker",
    label: proxy.t("salesContract.paymentMethod"),
    prop: "payMethod",
    itemType: "onePicker",
    showPicker: false,
    fieldNames: {
      text: "label",
      value: "value",
    },
    data: [],
  },
  {
    type: "picker",
    label: proxy.t("salesContract.freightPayer"),
    prop: "freightPayer",
    itemType: "onePicker",
    showPicker: false,
    fieldNames: {
      text: "label",
      value: "value",
    },
    data: [
      {
        label: proxy.t("salesContract.partyA"),
        value: "0",
      },
      {
        label: proxy.t("salesContract.partyB"),
        value: "1",
      },
    ],
  },
  {
    type: "input",
    itemType: "textarea",
    label: "交货期限备注",
    prop: "deliveryDateRemark",
  },
  {
    type: "input",
    itemType: "textarea",
    label: "付款方式备注",
    prop: "payMethodRemark",
  },
  {
    type: "input",
    itemType: "textarea",
    label: proxy.t("salesContract.remarks"),
    prop: "remark",
  },
  {
    type: "input",
    itemType: "number",
    label: proxy.t("salesContract.contractTotalAmount"),
    prop: "contractAmount",
    readonly: true,
  },
]);
const onClickLeft = () => history.back();
const fundsPaymentMethod = ref([]);
const customerData = ref([]);
const accountList = ref([]);
const corporationList = ref([]);
const productData = ref([]);
const getDict = () => {
  proxy.getDictOne(["funds_payment_method"]).then((res) => {
    fundsPaymentMethod.value = res["funds_payment_method"].data.map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
    formConfig[12].data = fundsPaymentMethod.value;
  });
  proxy.post("/customer/page", { pageNum: 1, pageSize: 9999 }).then((res) => {
    customerData.value = res.data.rows.map((x) => ({
      label: x.name,
      value: x.id,
    }));
    formConfig[10].data = customerData.value;
  });
  proxy
    .post("/productInfo/page", { pageNum: 1, pageSize: 9999, definition: "1" })
    .then((res) => {
      productData.value = res.data.rows.map((x) => ({
        label: x.name + ` (${x.spec})`,
        value: x.id,
      }));
      formOption.btnConfig.listConfig[0].data = productData.value;
    });

  proxy
    .post("/accountManagement/page", { pageNum: 1, pageSize: 999 })
    .then((res) => {
      accountList.value = res.data.rows.map((item) => {
        return {
          ...item,
          label: item.alias,
          value: item.id,
        };
      });
      formConfig[5].data = accountList.value;
    });

  proxy.post("/corporation/page", { pageNum: 1, pageSize: 999 }).then((res) => {
    corporationList.value = res.data.rows.map((item) => {
      return {
        ...item,
        label: item.name,
        value: item.id,
      };
    });
    formConfig[0].data = corporationList.value;
  });
};

const getProductData = (keyword) => {
  proxy.post("/productInfo/page", { keyword, definition: "1" }).then((res) => {
    productData.value = res.data.rows.map((x) => ({
      label: x.name + ` (${x.spec})`,
      value: x.id,
    }));
    formOption.btnConfig.listConfig[0].data = productData.value;
  });
};

const getCustomerData = (keyword) => {
  proxy.post("/customer/page", { keyword }).then((res) => {
    customerData.value = res.data.rows.map((x) => ({
      label: x.name,
      value: x.id,
    }));
    formConfig[10].data = customerData.value;
  });
};

const getDetails = (id) => {
  proxy.post("/salesContract/detail", { id }).then((res) => {
    if (res.data && res.data.contractDetailsList.length > 0) {
      res.data.salesContractDetailsList = res.data.contractDetailsList;
    } else {
      res.data.salesContractDetailsList = [];
    }
    res.data.deliveryDate = res.data.deliveryDate.slice(0, 10);
    formData.data = res.data;
    changeAmount();
  });
};

onMounted(() => {
  getDict();
  if (route.query.id) {
    getDetails(route.query.id);
    formOption.readonly = true; //全部只读
    formOption.hiddenSubmitBtn = true; //隐藏提交按钮
    formOption.btnConfig.isNeed = false;
  }
});

const onSubmit = () => {
  if (formData.data.salesContractDetailsList.length > 0) {
    proxy
      .post("/flowProcess/initiate", {
        flowKey: "jxst_sales_contract_flow",
        data: formData.data,
      })
      .then(
        () => {
          showSuccessToast(proxy.t("common.operationSuccessful"));
          setTimeout(() => {
            onClickLeft();
          }, 500);
        },
        (err) => {
          return showFailToast(err.message);
        }
      );
  } else {
    return showFailToast(proxy.t("salesContract.pleaseAddContractDetails"));
  }
};

const changeSellId = (val) => {
  if (val) {
    proxy.post("/corporation/detail", { id: val }).then((res) => {
      let detailCorporation = res.data;
      if (detailCorporation.countryName) {
        formData.data.sellCountryName = detailCorporation.countryName;
      }
      if (detailCorporation.provinceName) {
        formData.data.sellProvinceName = detailCorporation.provinceName;
      }
      if (detailCorporation.cityName) {
        formData.data.sellCityName = detailCorporation.cityName;
      }
      if (detailCorporation.address) {
        formData.data.sellAddress = detailCorporation.address;
      }
    });
  }
};
const changeShroffAccount = (val) => {
  if (val) {
    let data = accountList.value.filter((item) => item.value === val);
    if (data && data.length > 0) {
      formData.data.sellAccountName = data[0].name;
      formData.data.sellOpeningBank = data[0].openingBank;
      formData.data.sellInterbankNumber = data[0].interbankNumber;
      formData.data.sellAccountOpening = data[0].accountOpening;
    }
  }
};

const changeAmount = (index) => {
  let total = 0;
  for (let i = 0; i < formData.data.salesContractDetailsList.length; i++) {
    const element = formData.data.salesContractDetailsList[i];
    if (element.unitPrice && element.quantity) {
      element.total = parseFloat(element.unitPrice * element.quantity).toFixed(
        2
      );
      total += Number(element.total);
    }
  }
  if (total) {
    formData.data.contractAmount = total.toFixed(2);
  }
};
</script>
<style lang="scss" scoped>
.form {
  margin-bottom: 60px;
}
</style>
