<template>
  <div>
    <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="submit">
      <template #supplier>
        <div style="width: 100%">
          <el-form-item label="供应商" prop="supplierId" style="width: 100%; margin-bottom: 18px">
            <el-col :span="12">
              <el-select v-model="formData.data.supplierId" placeholder="请选择供应商" clearable style="width: 100%" @change="changeSupplier">
                <el-option v-for="item in supplierList" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey" />
              </el-select>
            </el-col>
          </el-form-item>
          <el-form-item label="地址" required style="width: 100%; margin-bottom: 18px">
            <el-col :span="6">
              <el-form-item prop="province" style="width: 100%">
                <el-input v-model="formData.data.province" placeholder="请输入省份" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="city" style="width: 100%">
                <el-input v-model="formData.data.city" placeholder="请输入城市" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="detailedAddress" style="width: 100%">
                <el-input v-model="formData.data.detailedAddress" placeholder="请输入地址" />
              </el-form-item>
            </el-col>
          </el-form-item>
          <el-form-item label="联系人" required style="width: 100%">
            <el-col :span="6">
              <el-form-item prop="contactPerson" style="width: 100%">
                <el-input v-model="formData.data.contactPerson" placeholder="请输入联系人" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="contactNumber" style="width: 100%">
                <el-input v-model="formData.data.contactNumber" placeholder="请输入联系人电话" />
              </el-form-item>
            </el-col>
          </el-form-item>
        </div>
      </template>
      <template #purchaseBomList>
        <div style="width: 100%">
          <el-table :data="formData.data.purchaseBomList" :row-style="{ height: '35px' }" header-row-class-name="tableHeader">
            <el-table-column label="品号" prop="bomSpecCode" width="120" />
            <el-table-column label="品名" prop="bomSpecName" min-width="240" />
            <el-table-column label="颜色" prop="bomSpecColour" width="140" />
            <el-table-column label="尺寸（长宽高，cm）" width="160">
              <template #default="{ row }">
                <div>{{ row.bomSpecLength }} * {{ row.bomSpecWidth }} * {{ row.bomSpecHeight }}</div>
              </template>
            </el-table-column>
            <el-table-column label="含税单价" width="140">
              <template #default="{ row, $index }">
                <el-form-item
                  :prop="'purchaseBomList.' + $index + '.unitPrice'"
                  :rules="rules.unitPrice"
                  :inline-message="true"
                  style="width: 100%"
                  @change="calculatedTotalAmount">
                  <el-input-number
                    onmousewheel="return false;"
                    v-model="row.unitPrice"
                    placeholder="含税单价"
                    style="width: 100%"
                    :controls="false"
                    :min="0"
                    :precision="2" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="税率" width="120">
              <template #default="{ row, $index }">
                <el-form-item
                  :prop="'purchaseBomList.' + $index + '.taxRate'"
                  :rules="rules.taxRate"
                  :inline-message="true"
                  style="width: 100%"
                  @change="calculatedTotalAmount">
                  <el-input-number
                    onmousewheel="return false;"
                    v-model="row.taxRate"
                    placeholder="税率"
                    style="width: 100%"
                    :controls="false"
                    :min="0"
                    :max="100"
                    :precision="2" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="不含税单价" width="100">
              <template #default="{ row }">
                <div>{{ moneyFormat(Number(Math.round(((row.unitPrice * 100) / (100 + row.taxRate)) * 100) / 100)) }}</div>
              </template>
            </el-table-column>
            <el-table-column label="可采购数量" width="100">
              <template #default="{ row }">
                <span v-if="route.query.processType && route.query.processType == 30">
                  {{ Number(Math.round(row.quantity - row.purchasedQuantity - row.frozenQuantity + row.thisTimeQuantity)) }}
                </span>
                <span v-else>
                  {{ Number(Math.round(row.quantity - row.purchasedQuantity - row.frozenQuantity)) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="采购数量" width="120">
              <template #default="{ row, $index }">
                <el-form-item
                  :prop="'purchaseBomList.' + $index + '.purchaseQuantity'"
                  :rules="rules.purchaseQuantity"
                  :inline-message="true"
                  style="width: 100%"
                  @change="calculatedTotalAmount">
                  <el-input-number
                    onmousewheel="return false;"
                    v-model="row.purchaseQuantity"
                    placeholder="采购数量"
                    style="width: 100%"
                    :controls="false"
                    :min="0"
                    :precision="0" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="含税小计" align="right" width="120">
              <template #default="{ row }">
                <div>{{ moneyFormat(Number(Math.round(row.unitPrice * row.purchaseQuantity * 100) / 100)) }}</div>
              </template>
            </el-table-column>
            <el-table-column label="不含税小计" align="right" width="120">
              <template #default="{ row }">
                <div>
                  {{
                    moneyFormat(Number(Math.round((Math.round(((row.unitPrice * 100) / (100 + row.taxRate)) * 100) / 100) * row.purchaseQuantity * 100) / 100))
                  }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" fixed="right" width="60">
              <template #default="{ $index }">
                <el-button type="danger" @click="clickDelete($index)" text>删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
      <template #deliveryAddress>
        <div style="width: 100%">
          <el-form-item label=" " prop="receiveGoodsType" style="width: 100%; margin-bottom: 18px">
            <el-radio-group v-model="formData.data.receiveGoodsType" @change="changeReceiveGoodsType">
              <el-radio :label="1">供应商运输</el-radio>
              <el-radio :label="2">自取</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="地址" required style="width: 100%; margin-bottom: 18px" v-if="formData.data.receiveGoodsType == 1">
            <el-col :span="6">
              <el-form-item prop="receiveProvince" style="width: 100%">
                <el-input v-model="formData.data.receiveProvince" placeholder="请输入省份" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="receiveCity" style="width: 100%">
                <el-input v-model="formData.data.receiveCity" placeholder="请输入城市" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="receiveDetailedAddress" style="width: 100%">
                <el-input v-model="formData.data.receiveDetailedAddress" placeholder="请输入地址" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item prop="receivePostcode" style="width: 100%">
                <el-input v-model="formData.data.receivePostcode" placeholder="请输入邮编" />
              </el-form-item>
            </el-col>
          </el-form-item>
          <el-form-item label="联系人" required style="width: 100%" v-if="formData.data.receiveGoodsType == 1">
            <el-col :span="6">
              <el-form-item prop="receiveContactPerson" style="width: 100%">
                <el-input v-model="formData.data.receiveContactPerson" placeholder="请输入联系人" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="receiveContactNumber" style="width: 100%">
                <el-input v-model="formData.data.receiveContactNumber" placeholder="请输入联系人电话" />
              </el-form-item>
            </el-col>
          </el-form-item>
        </div>
      </template>
      <template #money>
        <div style="width: 100%">
          <div style="padding: 8px; background-color: #e9f5fb; font-size: 12px; font-weight: 700">
            <span>含税总金额: {{ moneyFormat(formData.data.totalAmountIncludingTax) }} ({{ formData.data.totalAmountIncludingTaxCn }})</span>
            <span style="margin-left: 32px">
              不含税总金额: {{ moneyFormat(formData.data.totalAmountExcludingTax) }} ({{ formData.data.totalAmountExcludingTaxCn }})
            </span>
          </div>
        </div>
      </template>
      <template #attachments>
        <div style="width: 100%">
          <el-upload
            v-model:fileList="fileList"
            action="https://winfaster.obs.cn-south-1.myhuaweicloud.com"
            :data="uploadFileData"
            multiple
            :before-upload="beforeUpload"
            :on-success="onSuccessFile"
            :on-preview="onPreviewFile">
            <el-button style="background: #20b2aa; color: #fff; border: 1px solid #20b2aa">上传</el-button>
          </el-upload>
        </div>
      </template>
      <template #template>
        <div style="width: 100%">
          <el-form-item label="合同模板" prop="contractTemplateId" style="width: 100%; margin-bottom: 18px">
            <el-col :span="12">
              <el-select v-model="formData.data.contractTemplateId" placeholder="请选择合同模板" clearable style="width: 100%" @change="changeTemplate">
                <el-option v-for="item in templateList" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey" />
              </el-select>
            </el-col>
          </el-form-item>
          <div v-if="formOption.disabled">
            <div v-html="formData.data.contract"></div>
          </div>
          <Editor v-else :value="formData.data.contract" @updateValue="updateValue" ref="editor" />
        </div>
      </template>
    </byForm>
  </div>
</template>

<script setup>
import byForm from "/src/components/byForm/index";
import { useRoute } from "vue-router";
import Editor from "/src/components/Editor/index.vue";
import { ElMessage } from "element-plus";

const route = useRoute();
// 接收父组件的传值
const props = defineProps({
  queryData: Object,
});
const { proxy } = getCurrentInstance();
const supplierList = ref([]);
const templateList = ref([]);
const formData = reactive({
  data: {
    receiveGoodsType: 1,
    contract: "",
    purchaseBomList: [],
    fileList: [],
  },
});
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: "100px",
  itemWidth: 100,
  rules: [],
  labelPosition: "right",
  disabled: false,
});
const formConfig = computed(() => {
  return [
    {
      type: "title",
      title: "供应商",
      label: "",
    },
    {
      type: "slot",
      slotName: "supplier",
    },
    {
      type: "title",
      title: "采购清单",
      label: "",
    },
    {
      type: "slot",
      slotName: "purchaseBomList",
    },
    {
      type: "title",
      title: "收货地址",
      label: "",
    },

    {
      type: "slot",
      slotName: "deliveryAddress",
    },
    {
      type: "title",
      title: "付款信息",
      label: "",
    },
    {
      type: "select",
      label: "结算方式",
      prop: "settlementMethod",
      data: proxy.useUserStore().allDict["settlement_method"],
      itemWidth: 33,
    },
    {
      type: "select",
      label: "发票类型",
      prop: "invoiceType",
      data: proxy.useUserStore().allDict["invoice_type"],
      itemWidth: 33,
    },
    {
      type: "date",
      prop: "deliveryDate",
      label: "交付日期",
      format: "YYYY-MM-DD HH:mm:ss",
      itemType: "datetime",
      itemWidth: 34,
    },
    {
      type: "select",
      label: "币种",
      prop: "currency",
      data: proxy.useUserStore().allDict["currency"],
      itemWidth: 33,
    },
    {
      type: "number",
      prop: "advancePayment",
      label: "预付款 (%)",
      min: 0,
      max: 100,
      precision: 2,
      controls: false,
      itemWidth: 33,
    },
    {
      type: "title",
      title: "款项金额",
      label: "",
    },
    {
      type: "slot",
      slotName: "money",
    },
    {
      type: "title",
      title: "附件",
      label: "",
    },
    {
      type: "slot",
      slotName: "attachments",
      label: "附件",
    },
    {
      type: "title",
      title: "合同内容",
      label: "",
    },
    {
      type: "slot",
      slotName: "template",
    },
  ];
});
const rules = ref({
  supplierId: [{ required: true, message: "请选择供应商", trigger: "change" }],
  province: [{ required: true, message: "请输入省份", trigger: "blur" }],
  city: [{ required: true, message: "请输入城市", trigger: "blur" }],
  detailedAddress: [{ required: true, message: "请输入地址", trigger: "blur" }],
  contactPerson: [{ required: true, message: "请输入联系人", trigger: "blur" }],
  contactNumber: [{ required: true, message: "请输入联系人电话", trigger: "blur" }],
  unitPrice: [{ required: true, message: "请输入含税单价", trigger: "blur" }],
  taxRate: [{ required: true, message: "请输入税率", trigger: "blur" }],
  purchaseQuantity: [{ required: true, message: "请输入采购数量", trigger: "blur" }],
  receiveProvince: [{ required: true, message: "请输入省份", trigger: "blur" }],
  receiveCity: [{ required: true, message: "请输入城市", trigger: "blur" }],
  receiveDetailedAddress: [{ required: true, message: "请输入详细地址", trigger: "blur" }],
  receivePostcode: [{ required: true, message: "请输入邮编", trigger: "blur" }],
  receiveContactPerson: [{ required: true, message: "请输入联系人", trigger: "blur" }],
  receiveContactNumber: [{ required: true, message: "请输入联系人电话", trigger: "blur" }],
  settlementMethod: [{ required: true, message: "请选择结算方式", trigger: "change" }],
  invoiceType: [{ required: true, message: "请选择发票类型", trigger: "change" }],
  deliveryDate: [{ required: true, message: "请选择交付日期", trigger: "change" }],
  currency: [{ required: true, message: "请选择币种", trigger: "change" }],
  advancePayment: [{ required: true, message: "请输入预付款", trigger: "blur" }],
});
const getDemandData = () => {
  proxy.post("/supplier/page", { pageNum: 1, pageSize: 999 }).then((res) => {
    if (res.rows && res.rows.length > 0) {
      supplierList.value = res.rows.map((item) => {
        return {
          ...item,
          dictKey: item.id,
          dictValue: item.name,
        };
      });
    }
  });
  proxy.post("/contractTemplate/page", { pageNum: 1, pageSize: 999 }).then((res) => {
    if (res.rows && res.rows.length > 0) {
      templateList.value = res.rows.map((item) => {
        return {
          ...item,
          dictKey: item.id,
          dictValue: item.name,
        };
      });
    }
  });
};
getDemandData();
const changeSupplier = () => {
  if (formData.data.supplierId) {
    let list = supplierList.value.filter((item) => item.id === formData.data.supplierId);
    if (list && list.length > 0) {
      formData.data.province = list[0].province;
      formData.data.city = list[0].city;
      formData.data.detailedAddress = list[0].detailedAddress;
      formData.data.contactPerson = list[0].contactPerson1;
      formData.data.contactNumber = list[0].contactNumber1;
    }
  } else {
    formData.data.province = "";
    formData.data.city = "";
    formData.data.detailedAddress = "";
    formData.data.contactPerson = "";
    formData.data.contactNumber = "";
  }
};
const calculatedTotalAmount = () => {
  let money = 0;
  let notTaxMoney = 0;
  if (formData.data.purchaseBomList && formData.data.purchaseBomList.length > 0) {
    for (let i = 0; i < formData.data.purchaseBomList.length; i++) {
      if (formData.data.purchaseBomList[i].unitPrice && formData.data.purchaseBomList[i].purchaseQuantity) {
        money = Number(Math.round((money + formData.data.purchaseBomList[i].unitPrice * formData.data.purchaseBomList[i].purchaseQuantity) * 100) / 100);
        if (formData.data.purchaseBomList[i].taxRate) {
          notTaxMoney = Number(
            Math.round(
              (notTaxMoney +
                (Math.round(((formData.data.purchaseBomList[i].unitPrice * 100) / (100 + formData.data.purchaseBomList[i].taxRate)) * 100) / 100) *
                  formData.data.purchaseBomList[i].purchaseQuantity) *
                100
            ) / 100
          );
        }
      }
    }
  }
  formData.data.totalAmountIncludingTax = money;
  formData.data.totalAmountIncludingTaxCn = proxy.NumberToChinese(money);
  formData.data.totalAmountExcludingTax = notTaxMoney;
  formData.data.totalAmountExcludingTaxCn = proxy.NumberToChinese(notTaxMoney);
};
const clickDelete = (index) => {
  formData.data.purchaseBomList.splice(index, 1);
};
const changeReceiveGoodsType = () => {
  formData.data.receiveProvince = "";
  formData.data.receiveCity = "";
  formData.data.receiveDetailedAddress = "";
  formData.data.receivePostcode = "";
  formData.data.receiveContactPerson = "";
  formData.data.receiveContactNumber = "";
};
const changeTemplate = () => {
  if (formData.data.contractTemplateId) {
    proxy.post("/contractTemplate/detail", { id: formData.data.contractTemplateId }).then((res) => {
      proxy.$refs.editor.changeHtml(res.content);
    });
  }
};
const updateValue = (val) => {
  formData.data.contract = val;
};
const handleSubmit = async (flag) => {
  if (flag) {
    return true;
  } else {
    let status = await proxy.$refs.submit.handleSubmit(() => {});
    if (status) {
      if (!(formData.data.purchaseBomList && formData.data.purchaseBomList.length > 0)) {
        ElMessage("请添加采购清单");
        return false;
      } else {
        if (!route.query.processType) {
          for (let i = 0; i < formData.data.purchaseBomList.length; i++) {
            if (
              Number(
                Math.round(
                  formData.data.purchaseBomList[i].quantity -
                    formData.data.purchaseBomList[i].purchasedQuantity -
                    formData.data.purchaseBomList[i].frozenQuantity
                )
              ) < formData.data.purchaseBomList[i].purchaseQuantity
            ) {
              ElMessage("采购数量不能大于可采购数量");
              return false;
            }
          }
        } else if (route.query.processType == 30) {
          for (let i = 0; i < formData.data.purchaseBomList.length; i++) {
            if (
              Number(
                Math.round(
                  formData.data.purchaseBomList[i].quantity -
                    formData.data.purchaseBomList[i].purchasedQuantity -
                    formData.data.purchaseBomList[i].frozenQuantity +
                    formData.data.purchaseBomList[i].thisTimeQuantity
                )
              ) < formData.data.purchaseBomList[i].purchaseQuantity
            ) {
              ElMessage("采购数量不能大于可采购数量");
              return false;
            }
          }
        }
      }
      if (fileList.value && fileList.value.length > 0) {
        for (let i = 0; i < fileList.value.length; i++) {
          if (fileList.value[i].raw.uploadState) {
            ElMessage("文件上传中,请稍后提交");
            return false;
          }
        }
        formData.data.fileList = fileList.value.map((item) => {
          return {
            id: item.raw.id,
            fileName: item.raw.fileName,
            fileUrl: item.raw.fileUrl,
          };
        });
      } else {
        formData.data.fileList = [];
      }
      return true;
    } else {
      setTimeout(() => {
        const errorDiv = document.getElementsByClassName("is-error");
        errorDiv[0].scrollIntoView();
      }, 0);
    }
    return false;
  }
};
const getFormData = () => {
  return proxy.deepClone(formData.data);
};
const fileList = ref([]);
const uploadFileData = ref({});
const beforeUpload = async (file) => {
  const res = await proxy.post("/fileInfo/getSing", { fileName: file.name });
  uploadFileData.value = res.uploadBody;
  file.id = res.id;
  file.fileName = res.fileName;
  file.fileUrl = res.fileUrl;
  file.uploadState = true;
  return true;
};
const onSuccessFile = (any, UploadFile) => {
  UploadFile.raw.uploadState = false;
};
const onPreviewFile = (file) => {
  window.open(file.raw.fileUrl, "_blank");
};
watch(
  () => props.queryData,
  (newValue) => {
    formOption.disabled = judgeStatus();
    if (props.queryData && ["10", "20", "30", "40"].includes(route.query.processType)) {
      formData.data = proxy.deepClone(newValue);
      if (formData.data.contract) {
        proxy.$refs.editor.changeHtml(formData.data.contract);
      }
      formData.data.totalAmountIncludingTaxCn = proxy.NumberToChinese(formData.data.totalAmountIncludingTax);
      formData.data.totalAmountExcludingTaxCn = proxy.NumberToChinese(formData.data.totalAmountExcludingTax);
      if (formData.data.applyBuyId) {
        proxy.post("/applyBuy/detail", { id: formData.data.applyBuyId }).then((res) => {
          if (formData.data.purchaseBomList && formData.data.purchaseBomList.length > 0 && res.applyBuyBomList && res.applyBuyBomList.length > 0) {
            for (let i = 0; i < formData.data.purchaseBomList.length; i++) {
              formData.data.purchaseBomList[i].thisTimeQuantity = proxy.deepClone(formData.data.purchaseBomList[i].purchaseQuantity);
              for (let j = 0; j < res.applyBuyBomList.length; j++) {
                if (formData.data.purchaseBomList[i].applyBuyBomId === res.applyBuyBomList[j].id) {
                  formData.data.purchaseBomList[i].quantity = res.applyBuyBomList[j].quantity;
                  formData.data.purchaseBomList[i].purchasedQuantity = res.applyBuyBomList[j].purchaseQuantity;
                  formData.data.purchaseBomList[i].frozenQuantity = res.applyBuyBomList[j].frozenQuantity;
                }
              }
            }
          }
        });
      }
      if (formData.data.id) {
        proxy.post("/fileInfo/getList", { businessIdList: [formData.data.id] }).then((fileObj) => {
          if (fileObj[formData.data.id] && fileObj[formData.data.id].length > 0) {
            fileList.value = fileObj[formData.data.id].map((item) => {
              return {
                raw: item,
                name: item.fileName,
                url: item.fileUrl,
              };
            });
          } else {
            fileList.value = [];
          }
        });
      }
    }
  },
  {
    deep: true,
  }
);
onMounted(() => {
  if (route.query.subscribeId) {
    formData.data.applyBuyId = route.query.subscribeId;
    proxy.post("/applyBuy/detail", { id: route.query.subscribeId }).then((res) => {
      if (res.applyBuyBomList && res.applyBuyBomList.length > 0) {
        formData.data.purchaseBomList = res.applyBuyBomList.map((item) => {
          let frozenQuantity = 0;
          if (item.frozenQuantity) {
            frozenQuantity = item.frozenQuantity;
          }
          return {
            applyBuyBomId: item.id,
            bomSpecId: item.bomSpecId,
            unitPrice: undefined,
            taxRate: undefined,
            purchaseQuantity: undefined,
            bomSpecCode: item.bomSpecCode,
            bomSpecName: item.bomSpecName,
            bomSpecColour: item.bomSpecColour,
            bomSpecLength: item.bomSpecLength,
            bomSpecWidth: item.bomSpecWidth,
            bomSpecHeight: item.bomSpecHeight,
            quantity: item.quantity,
            purchasedQuantity: item.purchaseQuantity,
            frozenQuantity: frozenQuantity,
          };
        });
      }
    });
  }
});
// 向父组件暴露
defineExpose({ getFormData, handleSubmit });
</script>

<style lang="scss" scoped>
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}
:deep(.el-dialog) {
  margin-top: 10px !important;
  margin-bottom: 10px !important;
}
</style>
