<template>
  <Mask :width="400" :height="240" :is-show="isShow" @close="close" :show-footer="true" title="选择模板范围">
    <template #default>
      <div class="select">
        <el-form style="height: 100%">
          <el-form-item label="药品物资选择范围">
            <el-cascader :collapse-tags="true" :props="props" :options="allCateList"
                         :show-all-levels="false"
                         v-model="cateIds" clearable @change="change"/>
          </el-form-item>
        </el-form>
      </div>
    </template>
    <template #footer>
      <div class="bottom">
        <input ref="fileInput" type="file" @change="handleFileChange" style="display: none"/>
        <div class="default-btn" @click="selectFile" style="margin-left: 24px">上传数据</div>
        <div class="default-btn" @click="toExcel" style="margin-left: 24px">下载模板</div>
        <div class="default-btn" @click="close" style="margin-left: 24px">取消</div>
      </div>
    </template>
  </Mask>

</template>

<script setup lang="ts">
import Mask from "@/components/common/Mask.vue";
import {defineModel, onMounted, ref} from "vue";
import {post} from "@/utils/request.ts";
import {loadConfig} from "@/utils/config.ts";
import {Plus} from "@element-plus/icons-vue";
import axios from "axios";

const isShow = defineModel()
const props = {multiple: true}
const baseUrl = ref("")
const file = ref([])

interface CateOption {
  value: string;
  label: string;
  children: { value: number; label: string }[];
}

const typeList = {
  "1301": "中西成药",
  "1302": "中药饮片",
  "1306": "医疗器材",
  "0": "其他商品",
}
const cateIds = ref<number[]>([]);
const allCateList = ref<CateOption[]>([]);
const toExcel = () => {
  let cateIdsVal = cateIds.value
  let cateIdList = []
  for (let i = 0; i < cateIdsVal.length; i++) {
    let item: any = cateIdsVal[i];
    if (item.length > 1) {
      cateIdList.push(item[1])
    }
  }
  post("inventory/order/toExcel", {cateIdList: cateIdList}).then((token: any) => {
    loadConfig().then((res: any) => {
      window.open(res.base_url + "file/download/" + token)
    })

  })
}

const getAllCate = () => {
  post("goods/cate/getAllList", null).then((res: any) => {
    const options = [];
    for (const key in res) {
      if (typeList.hasOwnProperty(key)) { // 检查键是否存在
        options.push({
          value: key,
          label: typeList[key as keyof typeof typeList], // 类型断言
          children: res[key].map((item: { id: number; name: string }) => ({
            value: item.id,
            label: item.name
          })),
        });
      }
    }
    allCateList.value = options;
  })
}
const ids = ref<any>([])
const change = (value: any) => {
  cateIds.value = value
  ids.value = []
}
const uploadCateIds = () => {
  cateIds.value.map((item: any) => {
    if (item[item.length - 1] === 0) return
    ids.value.push(item[item.length - 1])
  })
}
const fromExcel = () => {
}
onMounted(() => {
  getAllCate()
  loadConfig().then((res: any) => {
    baseUrl.value = res.base_url
  })
})
const selectedFile = ref(null);

const handleFileChange = (event: any) => {
  selectedFile.value = event.target.files[0];
  uploadFile();
};

const fileInput = ref<HTMLInputElement | null>(null); // 声明或已通过 ref 获取

const selectFile = () => {
  if (fileInput.value) {
    fileInput.value.click(); // 触发文件选择框弹出
  }
};
const emit = defineEmits(['initAddOrderData'])
const uploadFile = async () => {
  if (!selectedFile.value) {
    alert('请先选择一个文件');
    return;
  }

  const formData = new FormData();
  formData.append('file', selectedFile.value);

  try {
    const response = await axios.post(baseUrl.value + 'file/uploadToTemp', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    let excelData = await post("inventory/order/fromExcel", {token: response.data})
    close()
    emit('initAddOrderData',excelData)
  } catch (error) {
    console.error('上传失败:', error);
  }
};
const close = () => {
  isShow.value = false
}
</script>

<style scoped lang="scss">
.select {
  height: 100%;
  padding: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.bottom {
  height: 100%;
  display: flex;
  justify-content: flex-end;
  padding: 24px;
}
</style>