<template>
  <el-dialog :model-value="visible" title="批量导入" @close="close" :width="width">
    <div class="flex items-center justify-between px-15px py-10px">
      <el-radio-group v-model="tab" @change="changeTab">
        <el-radio-button label="right" value="right">有效数据</el-radio-button>
        <el-radio-button label="error" value="error">错误数据</el-radio-button>
      </el-radio-group>
      <!-- <el-checkbox v-if="tab === 'right'" v-model="onSale" size="large" > {{ onSale ? "默认上架" : "默认下架"}}</el-checkbox> -->
      <el-switch v-if="rightList.length" v-model="onSale" active-text="上架" inactive-text="下架" size="large"
        inline-prompt />

    </div>
    <el-table height="50vh" :data="tableList">
      <el-table-column fixed="left" v-if="tab === 'error'" prop="err" label="错误信息" :width="240">
        <template #default="{ row }">
          <el-popover placement="right-start" title="" :width="240" trigger="hover">
            <template #reference>
              <div class="truncate text-red-500">{{ row.msgs.join(",") }}</div>
            </template>
            <el-scrollbar wrap-style="max-height:40vh">
              <div v-for="(item, index) in row.msgs" :key="index" class="text-red-500 text-14px mb-5px leading-24px">
                {{ item }}
              </div>
            </el-scrollbar>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="index" type="index" label="序号" :width="60" />
      <el-table-column prop="product_id" label="货品id" :width="160" />
      <el-table-column prop="name" label="药品" :width="160" />
      <el-table-column prop="specification" label="规格" :width="160" />
      <el-table-column prop="package_amount" label="包装量" :width="160" />
      <el-table-column prop="manufacturer" label="生产厂家" :width="160" />
      <el-table-column prop="barcode" label="条形码" :width="160" />
      <el-table-column prop="insurance_code" label="医保编码" :width="160" />
      <el-table-column prop="his_drug_code" label="ERP编码" :width="160" />
      <el-table-column prop="apply_people" label="适用人群" :width="120" />
      <el-table-column prop="dosage" label="单次剂量" :width="160" />
      <el-table-column prop="dosage_unit" label="剂量单位" :width="160" />
      <el-table-column prop="frequency" label="频次" :width="160" />
      <el-table-column prop="administration_method" label="给药方式" :width="160" />
      <el-table-column prop="days" label="用药天数" :width="160" />
      <el-table-column prop="recommended_quantity" label="推荐发药数量" :width="160" />
      <el-table-column label="" :min-width="0" />
    </el-table>
    <div class="flex justify-end">
      <pagination :totalRow="total" :pageSize="pageSize" :currentPage="page" @handle-size-change="changeSize"
        @handle-current-change="changePage" />
    </div>
    <template #footer>
      <div text-center>
        <el-button plain class="w-100px" type="primary" @click="close()">取消</el-button>
        <el-button v-if="errorList.length" class="w-100px" type="success" @click="reUpload()">重新导入</el-button>
        <el-button v-if="rightList.length" class="w-100px" type="primary" :loading="loading"
          @click="uploadDrugs()">上传药品</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { computed, ref, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { importHlwDrugInfo } from "@/api/hlw";
import { uploadDrugCsv, uploadOnlineDrugCsv } from '@/api/uploadFile'
import useElPagination from "@/hooks/useElPagination";
import pagination from "@/components/pagination/pagination.vue";
import { drugFieldDict } from './drug-dict.js';

const emits = defineEmits(["close", "change", "reUpload"]);
const props = defineProps({
  data: { type: Object, default: () => ({}) },
  visible: { type: Boolean, default: false },
  width: { type: Number, default: 300 },
  memberInfo: { type: Object, default: () => ({}) },
  // 库类型：hlw = 互联网医院药品库(drug-info)，online = 配送/线上药品库(online-drug-info)
  libType: { type: String, default: 'hlw' },
});

const { page, pageSize, changePage, changeSize } = useElPagination();
const tab = ref("right");
const loading = ref(false)
const onSale = ref(true)

const drugList = computed(() => props.data && Array.isArray(props.data.list) ? props.data.list : []);
const rightList = computed(() => drugList.value.filter((item) => item.msgs.length === 0));
const errorList = computed(() => drugList.value.filter((item) => item.msgs.length > 0));
const list = computed(() => tab.value === 'right' ? rightList.value : errorList.value)
const total = computed(() => list.value.length);
const tableList = computed(() => {
  return list.value.slice((page.value - 1) * pageSize.value, page.value * pageSize.value);
});


function close() {
  if (loading.value) return
  emits("close");
};

function reUpload() {
  if (loading.value) return
  emits("reUpload");
  close()
}
function changeTab(val) {
  changePage(1)
}

async function uploadDrugs() {
  if (loading.value) return;
  await ElMessageBox.confirm("确定上传药品吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  });
  loading.value = true;
  const csvFile = await getCsvFile()
  const payload = { onSale: onSale.value, operator: props.memberInfo.anotherName, operatorId: props.memberInfo._id };
  const isOnline = props.libType === 'online';
  const { success, message } = await (isOnline
    ? uploadOnlineDrugCsv(csvFile, payload)
    : uploadDrugCsv(csvFile, payload));
  loading.value = false
  if (success) {
    ElMessage.success(message)
    close()
    emits("change");
  } else {
    ElMessage.error(message)
  }

}
async function getCsvFile() {
  const csvList = rightList.value.map(i => {
    const { msgs, ...rest } = i;
    return rest;
  })
  const csvHeader = drugFieldDict.map(i => i.field);
  console.log(csvHeader)
  const csvRows = [
    csvHeader.join(","),
    ...csvList.map(row =>
      csvHeader.map(key => {
        let val = row[key] ? row[key] : '';
        // Escape double quotes and wrap in quotes if needed
        if (typeof val === "string" && (val.includes(",") || val.includes('"') || val.includes("\n"))) {
          val = `"${val.replace(/"/g, '""')}"`;
        }
        return val;
      }).join(",")
    )
  ];
  const csvContent = csvRows.join("\r\n");

  // 添加BOM头解决中文乱码问题
  const BOM = '\uFEFF';
  const csvWithBOM = BOM + csvContent;

  const csvFile = new File([csvWithBOM], "药品导入.csv", { type: "text/csv;charset=utf-8" });
  const link = document.createElement('a');
  link.href = URL.createObjectURL(csvFile);
  link.download = csvFile.name;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(link.href);
  return csvFile
}

watch(() => props.visible, (val) => {
  if (val) {
    tab.value = rightList.value.length ? 'right' : 'error';
    onSale.value = true
  }
})

</script>
