<template>
  <div style="width: 100%; padding: 0px 15px">
    <el-form
      :model="formData.data"
      :rules="rules"
      ref="formDom"
      label-position="top"
      :disabled="judgeStatus()"
    >
      <div class="_t">基础信息</div>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="采购部门" prop="deptName">
            <el-input v-model="formData.data.deptName" placeholder="请输入">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="采购人" prop="purchaseName">
            <el-input v-model="formData.data.purchaseName" placeholder="请输入">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="采购时间" prop="purchaseTime">
            <el-date-picker
              v-model="formData.data.purchaseTime"
              type="datetime"
              placeholder="请选择"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="供应商" prop="supplyId">
            <el-select
              v-model="formData.data.supplyId"
              placeholder="请选择"
              @change="handleChangeSupplier"
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="item in supplierData"
                :label="item.name"
                :value="item.id"
                :key="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="发票类型" prop="invoiceType">
            <el-select
              v-model="formData.data.invoiceType"
              placeholder="请选择"
              @change="handleChangeInvoiceType"
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="item in invoiceTypeData"
                :label="item.label"
                :value="item.value"
                :key="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="formData.data.invoiceType !== '0'">
          <el-form-item label="税率" prop="rate">
            <el-input v-model="formData.data.rate">
              <template #suffix>
                <div>%</div>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="采购说明" prop="purchaseContent">
        <el-input
          v-model="formData.data.purchaseContent"
          placeholder="请输入"
          type="textarea"
        >
        </el-input>
      </el-form-item>
      <div class="_t">采购明细</div>
      <el-form-item>
        <el-button
          type="primary"
          @click="openProduct = true"
          style="margin: 10px 0"
          v-if="ids.length == 0"
        >
          添加货品
        </el-button>
        <el-table :data="formData.data.purchaseDetailList">
          <el-table-column
            prop="goodType"
            label="货品类型"
            :formatter="(row) => (row.goodType == 1 ? '产品' : '物料')"
          />
          <el-table-column prop="productCode" label="货品编码" />
          <el-table-column prop="productName" label="货品名称" />
          <el-table-column prop="productSpec" label="规格型号" />
          <el-table-column
            prop="productUnit"
            label="单位"
            :formatter="(row) => dictValueLabel(row.productUnit, productUnit)"
          />
          <el-table-column
            prop="subscribeCount"
            label="申购数量"
            v-if="ids.length > 0"
          />
          <el-table-column
            prop="purchaseCount"
            label="已采购数量"
            v-if="ids.length > 0"
          />
          <el-table-column prop="count" label="本次采购" min-width="150">
            <template #default="{ row, $index }">
              <el-form-item
                :prop="'purchaseDetailList.' + $index + '.count'"
                :rules="rules.count"
                :inline-message="true"
              >
                <el-input-number
                  onmousewheel="return false;"
                  v-model="formData.data.purchaseDetailList[$index].count"
                  :controls="false"
                  :min="0"
                  @change="(e) => handleChangeMoney(e, $index, 'count')"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="单价" min-width="150">
            <template #default="{ row, $index }">
              <el-form-item
                :prop="'purchaseDetailList.' + $index + '.price'"
                :rules="rules.price"
                :inline-message="true"
              >
                <el-input-number
                  onmousewheel="return false;"
                  v-model="formData.data.purchaseDetailList[$index].price"
                  :controls="false"
                  :min="0"
                  @change="(e) => handleChangeMoney(e, $index, 'price')"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="金额" />
          <el-table-column prop="zip" label="操作" width="100">
            <template #default="{ $index }">
              <el-button
                type="primary"
                link
                @click="handleRemove($index, 20)"
                :disabled="formData.data.purchaseDetailList.length === 1"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-row>
        <el-col :span="4">
          <el-form-item label="商品金额小计" prop="productAmount">
            <el-input
              v-model="formData.data.productAmount"
              placeholder="请输入"
              disabled
            />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="_t">其他收费项目</div>
      <el-form-item>
        <el-button type="primary" style="margin: 10px 0" @click="handleAdd">
          添加
        </el-button>
        <el-table :data="formData.data.otherFeeList">
          <el-table-column prop="name" label="收费项目" min-width="150">
            <template #default="{ row, $index }">
              <el-form-item
                :prop="'otherFeeList.' + $index + '.name'"
                :rules="rulesOne.name"
                :inline-message="true"
              >
                <el-autocomplete
                  v-model="row.name"
                  :fetch-suggestions="querySearchPerson"
                  clearable
                  class="inline-input w-50"
                  placeholder="请输入"
                  @select="(val) => handlePerson(val, $index)"
                >
                </el-autocomplete>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="金额" min-width="150">
            <template #default="{ row, $index }">
              <el-form-item
                :prop="'otherFeeList.' + $index + '.price'"
                :rules="rulesOne.price"
                :inline-message="true"
              >
                <el-input-number
                  onmousewheel="return false;"
                  v-model="formData.data.otherFeeList[$index].price"
                  :controls="false"
                  @change="(e) => handleChangeOtherMoney(e, $index, 'price')"
                />
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column prop="remark" label="备注" min-width="150">
            <template #default="{ row, $index }">
              <el-form-item
                :prop="'otherFeeList.' + $index + '.remark'"
                :inline-message="true"
              >
                <el-input v-model="row.remark" placeholder="请输入" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="zip" label="操作" width="100">
            <template #default="{ $index }">
              <el-button type="primary" link @click="handleRemove($index, 10)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-row>
        <el-col :span="4">
          <el-form-item label="其他收费小计" prop="otherAmount">
            <el-input
              v-model="formData.data.otherAmount"
              placeholder="请输入"
              disabled
            />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <div class="_t">采购总金额</div> -->
      <el-row>
        <el-col :span="4">
          <el-form-item label="采购总金额" prop="amount">
            <el-input
              v-model="formData.data.amount"
              placeholder="请输入"
              disabled
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-dialog
      v-if="openProduct"
      v-model="openProduct"
      title="选择货品"
      width="70%"
      append-to-body
    >
      <SelectGoods
        :selectList="acquireSelectList()"
        @cancel="openProduct = false"
        @pushGoods="pushGoods"
      ></SelectGoods>
    </el-dialog>
  </div>
</template>

<script setup>
import SelectGoods from "@/components/product/SelectGoods";
import { ElMessage, ElMessageBox } from "element-plus";
import useUserStore from "@/store/modules/user";
import { onActivated } from "vue";

const route = useRoute();
const { proxy } = getCurrentInstance();
// 接收父组件的传值
const props = defineProps({
  queryData: String,
});

let formData = reactive({
  data: {
    purchaseTime: "",
    purchaseDetailList: [],
    otherFeeList: [],
  },
});
let rules = ref({
  deptName: [{ required: true, message: "请输入采购部门", trigger: "blur" }],
  purchaseName: [
    { required: true, message: "请输入采购人名称", trigger: "blur" },
  ],
  purchaseTime: [
    { required: true, message: "请选择采购时间", trigger: "change" },
  ],
  supplyId: [{ required: true, message: "请选择供应商", trigger: "change" }],
  count: [{ required: true, message: "请输入本次采购数量", trigger: "blur" }],
  price: [{ required: true, message: "请输入单价", trigger: "blur" }],
  remark: [{ required: true, message: "请输入备注", trigger: "blur" }],
  invoiceType: [
    { required: true, message: "请选择发票类型", trigger: "change" },
  ],
  rate: [{ required: true, message: "请输入税率", trigger: "blur" }],
});
let rulesOne = ref({
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  price: [{ required: true, message: "请输入金额", trigger: "blur" }],
});
const invoiceTypeData = ref([
  {
    label: "增值税专用发票",
    value: "1",
  },
  {
    label: "增值税普通发票",
    value: "2",
  },
  {
    label: "无发票",
    value: "0",
  },
]);
const handleChangeInvoiceType = (val) => {
  if (val === "1") {
    formData.data.rate = "13";
  } else if (val === "2") {
    formData.data.rate = "6";
  } else {
    formData.data.rate = "";
  }
};
let openProduct = ref(false);
// 物品相应逻辑
const handleRemove = (index, type) => {
  if (type === 20) {
    formData.data.purchaseDetailList.splice(index, 1);
    return ElMessage({
      message: "删除成功！",
      type: "success",
    });
  } else {
    formData.data.otherFeeList.splice(index, 1);
  }
  handleChangeAmount();
};

const handleAdd = () => {
  formData.data.otherFeeList.push({
    name: "",
    price: undefined,
    remark: "",
  });
};

const pushGoods = (goods) => {
  if (goods && goods.length > 0) {
    let afterFiltering = [];
    if (
      formData.data.purchaseDetailList &&
      formData.data.purchaseDetailList.length > 0
    ) {
      afterFiltering = goods.filter((item) => {
        let data = formData.data.purchaseDetailList.filter(
          (itemProduct) => itemProduct.bussinessId === item.id
        );
        if (data && data.length > 0) {
          return false;
        }
        return true;
      });
    } else {
      afterFiltering = goods;
    }
    const arr = afterFiltering.map((x) => ({
      goodType: x.goodType,
      productCode: x.code,
      productName: x.name,
      productSpec: x.spec,
      productUnit: x.unit,
      count: 0,
      price: 0,
      bussinessId: x.id,
      amount: 0,
    }));
    formData.data.purchaseDetailList =
      formData.data.purchaseDetailList.concat(arr);
    openProduct.value = false;
    const ids = formData.data.purchaseDetailList.map((x) => x.bussinessId);
    if (formData.data.supplyId && ids.length > 0) {
      handleChangeSupplier(formData.data.supplyId);
    }
    return ElMessage({
      message: "添加成功！",
      type: "success",
    });
  } else {
    ElMessage("请选择至少一件物品");
  }
};
// 提交方法
const formDom = ref(null);
const handleSubmit = async () => {
  const vaild = await formDom.value.validate();
  if (vaild) {
    if (formData.data.purchaseDetailList.length > 0) {
      const list = formData.data.purchaseDetailList;
      for (let i = 0; i < list.length; i++) {
        const e = list[i];
        if (ids.value.length > 0) {
          if (e.count == 0) {
            ElMessage({
              message: "本次采购数量不能为0！",
              type: "info",
            });
            return false;
          }
          // if (Number(e.subscribeCount) - Number(e.purchaseCount) > 0) {
          //   if (e.count == 0) {
          //     ElMessage({
          //       message: "本次采购数量不能为0！",
          //       type: "info",
          //     });
          //     return false;
          //   }
          // }
          // if (e.count + Number(e.purchaseCount) > Number(e.subscribeCount)) {
          //   ElMessage({
          //     message: "本次采购数量和已采购数量和不可大于申购数量！",
          //     type: "info",
          //   });
          //   return false;
          // }
        } else {
          if (e.count == 0) {
            ElMessage({
              message: "本次采购数量不能为0！",
              type: "info",
            });
            return false;
          }
        }
      }
      return true;
    }
    ElMessage({
      message: "请添加采购明细！",
      type: "info",
    });
    return false;
  }

  return false;
};
const ids = ref([]);
const getDetails = () => {
  if (props.queryData.type && props.queryData.type === "handoverSlip") {
    proxy.post("/contractProduct/getListDetail", ids.value).then((res) => {
      formData.data.purchaseDetailList = res.map((x) => {
        let obj = {
          ...x,
          dataResource: "1", //来源写死外销合同采购
          dataResourceId: x.id,
          bussinessId: x.productId,
          subscribeCount: x.quantity || x.sumPackQuantity || 0,
          purchaseCount: x.sumPurchaseCount || 0,
          count: x.expendQuantity || 0,
          price: null,
          amount: null,
        };
        delete obj.id;
        return obj;
      });
    });
  } else {
    proxy.post("/subscribeDetail/detail", { ids: ids.value }).then((res) => {
      formData.data.purchaseDetailList = res.map((x) => ({
        subscribeDetailId: x.id,
        bussinessId: x.bussinessId,
        goodType: x.productDefinition,
        productCode: x.productCode,
        productName: x.productName,
        productSpec: x.productSpec,
        productUnit: x.productUnit,
        purchaseCount: x.purchaseCount,
        subscribeCount: x.count,
        count: 0,
        price: null,
        amount: null,
      }));
    });
  }
};
// 获取供应商数据
const supplierData = ref([]);
const otherFeeListData = ref([]);
const getSupplierList = async (req) => {
  proxy
    .post("/supplierInfo/page", { pageNum: 1, pageSize: 9999 })
    .then((res) => {
      supplierData.value = res.rows;
    });
};
const emit = defineEmits(["auxiliaryChange"]);
let auxiliaryData = ref([
  {
    label: "供应商最近采购",
    data: [],
  },
  {
    label: "产品价格",
    data: [],
  },
]);
const auxiliaryChange = (data) => {
  emit("auxiliaryChange", data);
};

const getAuxiliaryData = (supplyId, productIdList) => {
  if (supplyId && productIdList.length > 0) {
    proxy
      .post("/subscribe/decisionAid", {
        supplyId: supplyId,
        productIdList: productIdList,
      })
      .then((res) => {
        // 获取数组长度
        let dataLength = auxiliaryData.value.length;
        // 供应商最近采购
        const recentlyArr = [
          {
            label: "合同编号",
            value: "",
            fn: () => {},
            num: 1,
          },
          {
            label: "下单日期",
            value: "",
            num: 1,
          },
          {
            label: "合同金额",
            value: "",
            num: 1,
          },
        ];
        auxiliaryData.value[dataLength - 2].data = res.purchaseList.map(
          (x, index) => {
            return recentlyArr.map((y, sonIndex) => {
              let obj = { ...y };
              let value = "";
              if (sonIndex === 0) {
                value = x.code;
              } else if (sonIndex === 1) {
                value = x.createTime;
              } else {
                value = x.currency + " " + proxy.moneyFormat(x.amount, 2);
              }
              obj.value = value;
              return obj;
            });
          }
        );
        // 产品价格
        const arrConfig = [
          {
            label: "产品名称",
            value: "",
            num: 1,
          },
          {
            label: "最近价格",
            value: "",
            num: 1,
          },
          {
            label: "历史最高",
            value: "",
            num: 1,
          },
          {
            label: "历史最低",
            value: "",
            num: 1,
          },
        ];
        auxiliaryData.value[dataLength - 1].data = res.productPriceList.map(
          (x, index) => {
            return arrConfig.map((y, sonIndex) => {
              let obj = { ...y };
              let value = "";
              if (sonIndex === 0) {
                value = x.name;
              } else if (sonIndex === 1) {
                value = x.lastPrice;
              } else if (sonIndex === 2) {
                value = x.maxPrice;
              } else {
                value = x.minPrice;
              }
              obj.value = value;
              return obj;
            });
          }
        );
        auxiliaryChange(auxiliaryData.value);
      });
  } else {
    if (props.queryData.type === "handoverSlip" && props.queryData.arr) {
      let arrConfig = [
        {
          label: "合同编号",
          value: "",
          fn: () => {},
          num: 1,
        },
        {
          label: "下单日期",
          value: "",
          num: 1,
        },
      ];
      auxiliaryData.value[0].data = contractData.value.map((x, index) => {
        return arrConfig.map((y, sonIndex) => {
          let obj = { ...y };
          let value = "";
          if (sonIndex === 0) {
            value = contractData.value[index].contractCode;
          } else if (sonIndex === 1) {
            value = contractData.value[index].claimTime;
          }
          obj.value = value;
          return obj;
        });
      });
      auxiliaryChange(auxiliaryData.value);
    }
  }
};
// 供应商改变逻辑
const handleChangeSupplier = (val) => {
  const ids = formData.data.purchaseDetailList.map((x) => x.bussinessId);
  if (val && ids.length > 0) {
    getAuxiliaryData(val, ids);
    proxy
      .post("/supplierPrice/getSupplierPriceByProductIds", {
        supplierInfoId: val,
        productIdList: ids,
      })
      .then((res) => {
        if (res && Object.keys(res).length > 0) {
          for (let i = 0; i < formData.data.purchaseDetailList.length; i++) {
            const e = formData.data.purchaseDetailList[i];
            for (const key in res) {
              if (e.bussinessId === key) {
                e.price = Number(res[key]);
              }
            }
          }
        } else {
          for (let i = 0; i < formData.data.purchaseDetailList.length; i++) {
            const e = formData.data.purchaseDetailList[i];
            e.price = 0;
          }
        }
        handleChangeAmount();
      });
  }
};

const formatNumber = (value, num = 10000) => {
  if (value === null || value === undefined || value === "") {
    return "";
  }
  // 将输入值保留四位小数
  const formattedValue = Math.round(Number(value) * num) / num;
  return formattedValue;
};

// 计算采购总金额
const handleChangeAmount = () => {
  let productAmount = 0;
  for (let i = 0; i < formData.data.purchaseDetailList.length; i++) {
    const e = formData.data.purchaseDetailList[i];
    e.amount = formatNumber(parseFloat(e.count * e.price), 100);
    productAmount += Number(e.amount);
  }
  formData.data.productAmount = formatNumber(productAmount, 100);
  // 其他收费
  let otherAmount = 0;
  for (let i = 0; i < formData.data.otherFeeList.length; i++) {
    const e = formData.data.otherFeeList[i];
    otherAmount += Number(e.price);
  }
  formData.data.otherAmount = formatNumber(otherAmount, 100);
  formData.data.amount = formatNumber(
    parseFloat(
      Number(formData.data.productAmount) + Number(formData.data.otherAmount)
    ),
    100
  );
};

const handleChangeMoney = (val, index, key) => {
  let num = 100;
  if (key === "count") {
    num = 10000;
  }
  formData.data.purchaseDetailList[index][key] = formatNumber(val, num);
  handleChangeAmount();
};

const handleChangeOtherMoney = (val, index, key) => {
  formData.data.otherFeeList[index][key] = formatNumber(val, 100);
  handleChangeAmount();
};

const productUnit = ref([]);
const getDict = () => {
  proxy.getDictOne(["unit"]).then((res) => {
    productUnit.value = res["unit"].map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
  });
  proxy.get("/purchaseOtherFee/listName").then((res) => {
    otherFeeListData.value = res.data.map((x) => ({ ...x, value: x.name }));
  });
};
getDict();

const createFilter = (queryString) => {
  return (restaurant) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    );
  };
};

const querySearchPerson = (queryString, callback) => {
  const results = queryString
    ? otherFeeListData.value.filter(createFilter(queryString))
    : otherFeeListData.value;
  callback(results);
};

const handlePerson = (item, index) => {
  formData.data.otherFeeList[index].name = item.name;
  formData.data.otherFeeList[index].price = item.price ? item.price : 0;
  formData.data.otherFeeList[index].remark = item.remark ? item.remark : "";
};

watch(
  props.queryData,
  () => {
    if (
      props.queryData &&
      (route.query.processType == 10 ||
        route.query.processType == 20 ||
        route.query.processType == 30)
    ) {
      formData.data = proxy.deepClone(props.queryData);
      const ids = formData.data.purchaseDetailList.map((x) => x.bussinessId);
      if (formData.data.supplyId && ids.length > 0) {
        getAuxiliaryData(formData.data.supplyId, ids);
      }
    }
  },
  {
    deep: true,
  }
);
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 userInfo = useUserStore().user;
const contractData = ref([]);
onMounted(() => {
  formData.data.purchaseTime = proxy.parseTime(new Date());
  formData.data.deptName = userInfo.dept.deptName;
  formData.data.purchaseName = userInfo.nickName;
  getSupplierList();
  if (props.queryData.ids) {
    ids.value = props.queryData.ids.split(",") || [];
    getDetails();
  }
  if (props.queryData.type === "handoverSlip" && props.queryData.arr) {
    formData.data.dataResourceId = JSON.parse(
      props.queryData.arr
    )[0].contractId;
    formData.data.dataResource = "1"; //外销合同采购
    contractData.value = JSON.parse(props.queryData.arr);
    auxiliaryData.value.unshift({
      label: "关联销售合同",
      data: [],
    });
    getAuxiliaryData();
  }
});

const getFormData = () => {
  return proxy.deepClone(formData.data);
};
// 向父组件暴露
defineExpose({
  getFormData,
  handleSubmit,
});
const acquireSelectList = () => {
  let data = [];
  if (
    formData.data.purchaseDetailList &&
    formData.data.purchaseDetailList.length > 0
  ) {
    data = formData.data.purchaseDetailList.map((item) => {
      return {
        id: item.bussinessId,
        name: item.productName,
      };
    });
  }
  return data;
};
</script>

<style lang="scss" scoped>
._t {
  margin-bottom: 5px;
  font-size: 14px;
}
</style>
