<template>
  <div style="width: 100%; padding: 0px 15px">
    <byForm
      :formConfig="formConfig"
      :formOption="formOption"
      v-model="formData.data"
      :rules="rules"
      ref="formDom"
    >
      <template #details>
        <div style="width: 100%">
          <el-button
            type="primary"
            @click="openProduct = true"
            style="margin-bottom: 10px"
          >
            添加物品
          </el-button>
          <el-button
            type="primary"
            @click="openExcel = true"
            style="margin-bottom: 10px"
          >
            excel导入
          </el-button>
          <el-table
            :data="formData.data.subscribeDetailList"
            show-summary
            :summary-method="getSummaries"
          >
            <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="count" label="申购数量" min-width="150">
              <template #default="{ row, $index }">
                <el-form-item
                  :prop="'subscribeDetailList.' + $index + '.count'"
                  :rules="rules.count"
                  :inline-message="true"
                >
                  <el-input-number
                    v-model="row.count"
                    :precision="4"
                    :controls="false"
                    :min="0"
                    onmousewheel="return false;"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" min-width="150">
              <template #default="{ row, $index }">
                <el-form-item
                  :prop="'subscribeDetailList.' + $index + '.remark'"
                  :rules="rules.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)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
    </byForm>
    <el-dialog
      v-model="openProduct"
      title="选择物品"
      width="70%"
      append-to-body
    >
      <SelectGoods
        @cancel="openProduct = false"
        @pushGoods="pushGoods"
      ></SelectGoods>
    </el-dialog>

    <el-dialog v-model="openExcel" title="excel导入" width="30%" append-to-body>
      <div v-loading="excelLoading">
        <div style="margin: 15px 0">
          <!-- <a
            href="/static/申购明细导入模板.xlsx"
            download="申购明细导入模板.xlsx"
            class="download"
            >Excel模板下载</a
          > -->
          <!-- <el-button @click="aaa" type="primary">下载</el-button> -->
          <a
            href="https://winfaster.obs.cn-south-1.myhuaweicloud.com/byteSailing/templates/wdly/%E7%94%B3%E8%B4%AD%E6%98%8E%E7%BB%86%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx"
            download="申购明细导入模板.xlsx"
            class="download"
            >Excel模板下载</a
          >
        </div>
        <el-upload
          :action="actionUrl + '/subscribeDetail/excelImport'"
          :headers="headers"
          :before-upload="useImportExcelStore().updateRequestHeaders"
          :on-success="handleSuccess"
          :on-progress="handleProgress"
          :show-file-list="false"
          :on-error="handleError"
          accept=".xls, .xlsx"
        >
          <el-button type="primary">点击导入</el-button>
        </el-upload>
      </div>

      <template #footer>
        <el-button @click="openExcel = false" size="large">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import byForm from "@/components/byForm/index";
import { ElMessage, ElMessageBox } from "element-plus";
import SelectGoods from "@/components/WDLY/product/SelectGoods";
import useUserStore from "@/store/modules/user";
import { computed } from "vue";
import { getToken } from "@/utils/auth";
const { proxy } = getCurrentInstance();
import useImportExcelStore from "@/store/modules/importExcel";
const headers = computed(() => useImportExcelStore().requestHeaders);
const actionUrl = import.meta.env.VITE_APP_BASE_API;
const route = useRoute();
let formData = reactive({
  data: {
    subscribeDetailList: [],
  },
});
let rules = ref({
  receiptWarehouseId: [
    { required: true, message: "请选择收货仓库", trigger: "change" },
  ],
  planArrivalTime: [
    { required: true, message: "请选择要求到货时间", trigger: "change" },
  ],
  count: [{ required: true, message: "请输入申购数量", trigger: "blur" }],
  // remark: [{ required: true, message: "请输入申购备注", trigger: "blur" }],
});
const formOption = computed(() => ({
  disabled: false,
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
}));
const formConfig = computed(() => {
  return [
    {
      type: "input",
      prop: "deptName",
      label: "申购部门",
      itemWidth: 25,
      disabled: true,
      style: {
        "margin-right": "10px",
      },
    },
    {
      type: "input",
      prop: "subcribeName",
      label: "申购人",
      itemWidth: 25,
      disabled: true,
      style: {
        "margin-right": "10px",
      },
    },
    {
      type: "date",
      prop: "subcribeTime",
      label: "申购时间",
      itemWidth: 26,
      disabled: true,
      style: {
        "margin-right": "10px",
      },
    },
    {
      type: "select",
      prop: "receiptWarehouseId",
      label: "收货仓库",
      itemWidth: 25,
      isLoad: {
        url: "/warehouse/page",
        req: {
          pageNum: 1,
          pageSize: 9999,
        },
        labelKey: "name",
        labelVal: "id",
        method: "post",
        resUrl: "rows",
      },
    },
    {
      type: "date",
      prop: "planArrivalTime",
      label: "要求到货时间",
      itemWidth: 25,
      format: "YYYY-MM-DD",
      style: {
        "margin-left": "10px",
      },
    },
    {
      type: "input",
      itemType: "textarea",
      prop: "subcribeContent",
      label: "申购说明",
    },
    {
      type: "slot",
      slotName: "details",
      label: "申购明细",
    },
  ];
});
const formDom = ref(null);
const handleSubmit = async () => {
  const vaild = await formDom.value.handleSubmit(() => {}); //拿到内部表单是否验证通过
  if (vaild) {
    if (formData.data.subscribeDetailList.length > 0) {
      const list = formData.data.subscribeDetailList;
      for (let i = 0; i < list.length; i++) {
        const e = list[i];
        if (e.count == 0) {
          ElMessage({
            message: "申购数量不能为0！",
            type: "info",
          });
          return false;
        }
      }
      return true;
    }
    ElMessage({
      message: "请添加申购明细！",
      type: "info",
    });
    return false;
  }
};
const openProduct = ref(false);
const openExcel = ref(false);
const excelLoading = ref(false);

const handleRemove = (index) => {
  formData.data.subscribeDetailList.splice(index, 1);
  return ElMessage({
    message: "删除成功！",
    type: "success",
  });
};
const pushGoods = (goods) => {
  const arr = goods.map((x) => ({
    goodType: x.goodType,
    productCode: x.customCode,
    productName: x.name,
    productSpec: x.spec,
    productUnit: x.unit,
    count: 0,
    bussinessId: x.id,
    remark: "",
  }));
  formData.data.subscribeDetailList =
    formData.data.subscribeDetailList.concat(arr);
  openProduct.value = false;
  return ElMessage({
    message: "添加成功！",
    type: "success",
  });
};

// 接收父组件的传值
const props = defineProps({
  queryData: String,
});
const productUnit = ref([]);
const getDict = () => {
  proxy.getDictOne(["unit"]).then((res) => {
    productUnit.value = res["unit"].map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
  });
};
getDict();

// 获取用户信息并赋默认值
const userInfo = useUserStore().user;
onMounted(() => {
  if (
    route.query.id &&
    (route.query.processType == 20 || route.query.processType == 10)
  ) {
    formOption.value.disabled = true;
    setTimeout(() => {
      formData.data = {
        ...props.queryData,
      };
      if (formData.data && route.query.subscribeId) {
        // const ids = formData.data.subscribeDetailList.map((x) => x.bussinessId);
        proxy
          .post("/subscribe/detail", {
            id: route.query.subscribeId,
          })
          .then((res) => {
            formData.data.subscribeDetailList = res.subscribeDetailList.map(
              (x) => ({ ...x, goodType: x.productDefinition })
            );
          });
      }
    }, 2000);
  } else {
    formData.data.subcribeTime = proxy.parseTime(new Date());
    formData.data.deptName = userInfo.dept.deptName;
    formData.data.subcribeName = userInfo.nickName;
  }
});
const aaa = () => {
  fetch("/static/申购明细导入模板.xlsx")
    .then((res) => res.blob())
    .then((res) => {
      const url = window.URL.createObjectURL(res);
      let filename = "申购明细导入模板.xlsx";
      const link = document.createElement("a");
      link.style.display = "none";
      link.href = url;
      link.setAttribute("download", filename);
      document.body.appendChild(link);
      link.click();
    });
};
const handleProgress = () => {
  excelLoading.value = true;
};
const handleSuccess = (res) => {
  if (res.code != 200) {
    return ElMessage({
      message: `${res.msg}，请重试！`,
      type: "info",
    });
  } else {
    ElMessage({
      message: "导入成功！",
      type: "success",
    });
    if (res && res.data && res.data.length > 0) {
      formData.data.subscribeDetailList = res.data.map((x) => ({
        ...x,
        productCode: x.productCustomCode,
      }));
    }
    openExcel.value = false;
    excelLoading.value = false;
  }
};

const handleError = (err) => {
  ElMessage({
    message: `${err}，请重试！`,
    type: "info",
  });
  openExcel.value = false;
  excelLoading.value = false;
};

const getFormData = () => {
  return formData.data;
};

// 向父组件暴露
defineExpose({
  // submitData: formData.data,
  getFormData,
  handleSubmit,
});
parseFloat;
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 === "count") {
      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>
.download {
  background: #409eff;
  color: #fff;
  padding: 8px 12px;
  border-radius: 4px;
}
</style>