<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="请输入"
              disabled
            >
            </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="请输入"
              disabled
            >
            </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="请选择"
              disabled
            />
          </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"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="是否合同" prop="isAgreement">
            <el-select
              v-model="formData.data.isAgreement"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option label="是" value="1"> </el-option>
              <el-option label="否" value="0"> </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="付款方式" prop="paymentMethod">
            <el-select
              v-model="formData.data.paymentMethod"
              placeholder="请选择"
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="item in fundsPaymentMethod"
                :label="item.dictValue"
                :value="item.dictKey"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="采购单号" prop="contractCode">
            <el-input v-model="formData.data.contractCode" placeholder="请输入">
            </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"
          show-summary
          :summary-method="getSummaries"
        >
          <el-table-column
            prop="productDefinition"
            label="物品类型"
            :formatter="
              (row) =>
                row.productDefinition == 1
                  ? '产品'
                  : row.productDefinition == 2
                  ? '物料'
                  : ''
            "
          />
          <el-table-column prop="productCustomCode" 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="申购数量" />
          <el-table-column prop="purchaseCount" label="已采购数量" />
          <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
                  :model-value="formData.data.purchaseDetailList[$index].count"
                  :precision="4"
                  :controls="false"
                  :min="0"
                  onmousewheel="return false;"
                  @change="(val) => handleChangeMoney(val, $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
                  :model-value="formData.data.purchaseDetailList[$index].price"
                  :precision="4"
                  :controls="false"
                  :min="0"
                  onmousewheel="return false;"
                  @change="(val) => handleChangeMoney(val, $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)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <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"
          show-summary
          :summary-method="getSummariesOne"
        >
          <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-input v-model="row.name" placeholder="请输入" />
              </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
                  v-model="row.price"
                  :precision="4"
                  :controls="false"
                  onmousewheel="return false;"
                  @change="handleChangeAmount"
                />
              </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 :gutter="10">
        <el-col :span="4">
          <el-form-item label="运费" prop="freight">
            <el-input-number
              v-model="formData.data.freight"
              :precision="4"
              :min="0"
              :controls="false"
              onmousewheel="return false;"
              style="width: 100%"
              @change="handleChangeAmount"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="优惠" prop="preferential">
            <el-input-number
              v-model="formData.data.preferential"
              :precision="4"
              :controls="false"
              onmousewheel="return false;"
              style="width: 100%"
              @change="handleChangeAmount"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="_t" style="margin-bottom: 15px">采购总金额</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-item label="上传附件">
        <div style="width: 100%">
          <el-upload
            v-model:fileList="fileList"
            action="https://winfaster.obs.cn-south-1.myhuaweicloud.com"
            :data="uploadData"
            multiple
            :before-upload="handleBeforeUpload"
            :on-success="handleSuccess"
            :on-preview="onPreviewFile"
          >
            <el-button>选择</el-button>
          </el-upload>
        </div>
      </el-form-item>
    </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";
import { useRouter, useRoute } from "vue-router";
const { proxy } = getCurrentInstance();
const route = useRoute();
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" }],
  isAgreement: [
    { required: true, message: "请选择是否合同", trigger: "change" },
  ],
  paymentMethod: [
    { required: true, message: "请选择付款方式", trigger: "change" },
  ],
  contractCode: [
    { required: true, message: "请输入采购单号", trigger: "blur" },
  ],
  freight: [{ required: true, message: "请输入运费", trigger: "blur" }],
  preferential: [{ required: true, message: "请输入优惠", trigger: "blur" }],
});
let rulesOne = ref({
  name: [{ required: true, message: "请输入费用名称", trigger: "blur" }],
  price: [{ required: true, message: "请输入金额", trigger: "blur" }],
});
const openProduct = ref(false);
// 上传附件
const uploadData = ref({});
const fileList = ref([]);
const handleBeforeUpload = 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;
  file.uploadState = true;
  return true;
};
const handleSuccess = (any, UploadFile) => {
  UploadFile.raw.uploadState = false;
};
const onPreviewFile = (file) => {
  window.open(file.raw.fileUrl, "_blank");
};

const handleAdd = () => {
  formData.data.otherFeeList.push({
    name: "",
    price: 0,
    remark: "",
  });
};
// 物品相应逻辑
const handleRemove = (index, type) => {
  if (type == 10) {
    formData.data.otherFeeList.splice(index, 1);
  } else if (type == 20) {
    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;
          }
        }
      }
      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,
            uploadState: item.raw.uploadState,
          };
        });
      } else {
        formData.data.fileList = [];
      }
      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 (!route.query.processType) {
    formData.data.freight = 0;
    formData.data.preferential = 0;
    ids.value = props.queryData.ids.split(",") || [];
    getDetails();
  } else {
    let val = route.query.businessId;
    proxy
      .post("/purchase/detail", {
        id: val,
      })
      .then((res) => {
        let jsonData = {};
        if (res.victoriatouristJson) {
          jsonData = JSON.parse(res.victoriatouristJson);
        }
        formData.data = { ...res, ...jsonData };
        formData.data.purchaseDetailList = formData.data.purchaseDetailList.map(
          (x) => ({
            ...x,
            subscribeCount: x.subscribeQuantity,
            purchaseCount: x.purchaseQuantity,
          })
        );
      });

    proxy
      .post("/fileInfo/getList", { businessIdList: [val] })
      .then((fileObj) => {
        formData.data.fileList = fileObj[val] || [];
        if (formData.data.fileList && formData.data.fileList.length > 0) {
          fileList.value = formData.data.fileList.map((item) => {
            return {
              raw: item,
              name: item.fileName,
              url: item.fileUrl,
            };
          });
        }
      });
  }
});

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

const ids = ref([]);
const getDetails = () => {
  proxy.post("/subscribeDetail/detail", { ids: ids.value }).then((res) => {
    formData.data.purchaseDetailList = res.map((x) => ({
      ...x,
      subscribeDetailId: x.id,
      subscribeCount: x.count,
      count: Number(x.count) - Number(x.purchaseCount),
      price: null,
      amount: null,
    }));
  });
};
// 获取用户信息并赋默认值
const tenantId = userInfo.tenantId;
// 获取供应商数据
const supplierData = ref([]);
const fundsPaymentMethod = ref([]);
const getSupplierList = async (req) => {
  proxy
    .post("/supplierInfo/page", { pageNum: 1, pageSize: 9999 })
    .then((res) => {
      supplierData.value = res.rows;
    });

  proxy
    .post("/dictTenantData/page", {
      pageNum: 1,
      pageSize: 999,
      tenantId: tenantId,
      dictCode: "funds_payment_method",
    })
    .then((res) => {
      fundsPaymentMethod.value = res.rows;
    });
};
// 供应商改变逻辑
const handleChangeSupplier = (val) => {
  const ids = formData.data.purchaseDetailList.map((x) => x.bussinessId);
  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;
        }
      }
      handleChangeMoney();
    });
};
// 计算采购总金额
const handleChangeAmount = () => {
  let sum = 0;
  for (let i = 0; i < formData.data.purchaseDetailList.length; i++) {
    const e = formData.data.purchaseDetailList[i];
    // e.amount = parseFloat(e.count * e.price).toFixed(4);
    sum += Number(e.amount);
  }
  for (let i = 0; i < formData.data.otherFeeList.length; i++) {
    const e = formData.data.otherFeeList[i];
    sum += Number(e.price);
  }
  sum += formData.data.freight;
  sum += formData.data.preferential;
  formData.data.amount = parseFloat(sum).toFixed(4);
};

const handleChangeMoney = (val, index, key) => {
  if (key) {
    formData.data.purchaseDetailList[index][key] = val;
  }
  for (let i = 0; i < formData.data.purchaseDetailList.length; i++) {
    formData.data.purchaseDetailList[i].amount = parseFloat(
      formData.data.purchaseDetailList[i].count *
        formData.data.purchaseDetailList[i].price
    ).toFixed(4);
  }
  handleChangeAmount();
};

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

const judgeStatus = () => {
  if (route.query.processType == 20) {
    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 getFormData = () => {
  return formData.data;
};

// 向父组件暴露
defineExpose({
  // submitData: formData.data,
  getFormData,
  handleSubmit,
});

const getSummaries = (param) => {
  const { columns, data } = param; //columns是每列的信息，data是每行的信息
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计"; //此处是在index=0的这一列显示为“合计”
      return;
    }
    const values = data.map((item) => Number(item[column.property]));
    if (
      column.property === "subscribeCount" ||
      column.property === "purchaseCount" ||
      column.property === "count" ||
      column.property === "amount"
    ) {
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!isNaN(value)) {
          return Number(parseFloat(prev + curr).toFixed(4));
        } else {
          return prev;
        }
      }, 0);
      sums[index];
    }
  });
  return sums;
};

const getSummariesOne = (param) => {
  const { columns, data } = param; //columns是每列的信息，data是每行的信息
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计"; //此处是在index=0的这一列显示为“合计”
      return;
    }
    const values = data.map((item) => Number(item[column.property]));
    if (column.property === "price") {
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!isNaN(value)) {
          return Number(parseFloat(prev + curr).toFixed(4));
        } else {
          return prev;
        }
      }, 0);
      sums[index];
    }
  });
  return sums;
};
</script>


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