<template>
  <div style="width: 100%; padding: 0px 15px">
    <el-form
      :model="formData.data"
      :rules="rules"
      ref="formDom"
      label-position="top"
    >
      <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="请选择"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="8">
          <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"
              >
              </el-option>
            </el-select>
          </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="单位" />
          <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
                  v-model="row.count"
                  :precision="4"
                  :controls="false"
                  :min="0"
                  @change="handleChangeAmount"
                />
              </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
                  v-model="row.price"
                  :precision="4"
                  :controls="false"
                  :min="0"
                  @change="handleChangeAmount"
                />
              </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)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <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-model="openProduct"
      title="选择货品"
      width="70%"
      append-to-body
    >
      <SelectGoods
        @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";

const { proxy } = getCurrentInstance();

let formData = reactive({
  data: {
    purchaseTime: "",
    purchaseDetailList: [],
  },
});
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" }],
});

let openProduct = ref(false);
// 物品相应逻辑
const handleRemove = (index) => {
  formData.data.purchaseDetailList.splice(index, 1);
  handleChangeAmount();
  return ElMessage({
    message: "删除成功！",
    type: "success",
  });
};

const pushGoods = (goods) => {
  const arr = goods.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;
  return ElMessage({
    message: "添加成功！",
    type: "success",
  });
};
// 提交方法
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 (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 userInfo = useUserStore().user;
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();
  }
});

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

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) => {
        delete x.id;
        return {
          ...x,
          subscribeCount: x.sumPackQuantity,
          purchaseCount: x.sumPurchaseCount,
          count: 0,
          price: null,
          amount: null,
        };
      });
    });
  } else {
    proxy.post("/subscribeDetail/detail", { ids: ids.value }).then((res) => {
      formData.data.purchaseDetailList = res.map((x) => ({
        ...x,
        subscribeCount: x.count,
        count: 0,
        price: null,
        amount: null,
      }));
    });
  }
};
// 获取供应商数据
const supplierData = ref([]);
const getSupplierList = async (req) => {
  proxy
    .post("/supplierInfo/page", { pageNum: 1, pageSize: 9999 })
    .then((res) => {
      supplierData.value = res.rows;
    });
};
// 供应商改变逻辑
const handleChangeSupplier = (val) => {
  console.log(val, "as");
};
// 计算采购总金额
const handleChangeAmount = () => {
  let sum = 0;
  for (let i = 0; i < formData.data.purchaseDetailList.length; i++) {
    const e = formData.data.purchaseDetailList[i];
    e.amount = e.count * e.price;
    sum += e.amount;
  }
  formData.data.amount = sum;
};
// 向父组件暴露
defineExpose({
  submitData: formData.data,
  handleSubmit,
});
</script>


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