<template>
  <div style="width: 100%; padding: 0px 15px">
    <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="submit">
      <template #deadline>
        <div>
          <el-date-picker v-model="formData.data.deadline" type="date" placeholder="请选择付款期限" value-format="YYYY-MM-DD" />
        </div>
      </template>
      <template #receiptsNum>
        <div>
          <el-input-number
            onmousewheel="return false;"
            v-model="formData.data.receiptsNum"
            placeholder="请输入单据数量"
            :min="0"
            :precision="0"
            :controls="false" />
        </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)">
                      <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 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";

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: [],
  },
});
const submit = ref(null);
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const formConfig = computed(() => {
  return [
    {
      type: "title",
      title: "基础信息",
      label: "",
    },
    {
      type: "select",
      label: "供应商",
      prop: "supplyId",
      data: supplierList.value,
      fn: (val) => {
        changeSupply(val);
      },
    },
    {
      type: "slot",
      prop: "deadline",
      slotName: "deadline",
      label: "付款期限",
      itemWidth: 50,
    },
    {
      type: "select",
      label: "发票类型",
      prop: "invoiceType",
      data: invoiceType.value,
      itemWidth: 50,
    },
    {
      type: "input",
      prop: "remark",
      label: "付款说明",
      itemType: "textarea",
    },
    {
      type: "slot",
      prop: "receiptsNum",
      slotName: "receiptsNum",
      label: "单据数量",
    },
    {
      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,
    },
    {
      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: "bankName",
      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" }],
});
const fileList = ref([]);
const uploadData = ref({});
const getDict = () => {
  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,
          };
        });
        console.log(fundsPaymentMethod.value);
      }
    });
  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,
          };
        });
      } else {
        contractList.value = [];
      }
    });
  } else {
    contractList.value = [];
  }
};
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);
};
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) => {
  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;
  } else {
    row.amount = "";
    row.sumPayMoney = "";
  }
};
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,
          };
        });
      }
      return true;
    } else {
      ElMessage("请添加至少一条付款明细");
    }
    return false;
  }
  return status;
};
// 接收父组件的传值
const props = defineProps({
  queryData: Object,
});
onMounted(async () => {
  if (props.queryData.supplyId) {
    formData.data.supplyId = props.queryData.supplyId;
    await changeSupply(formData.data.supplyId);
    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]);
          }
        }
      }
    }
  }
});
// 向父组件暴露
defineExpose({
  submitData: formData.data,
  handleSubmit,
});
</script>

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