<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="入库状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择入库状态" clearable style="width: 250px">
          <el-option v-for="dict in healthcare_entry_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="入库类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择入库类型" clearable style="width: 250px">
          <el-option v-for="dict in healthcare_entry_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['pasd-healthcare:drugentry:add']">药品入库</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['pasd-healthcare:drugentry:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['pasd-healthcare:drugentry:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['pasd-healthcare:drugentry:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Upload" @click="handleImport"
          v-hasPermi="['pasd-healthcare:drugentry:add']">批量导入</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="drugentryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="55" align="center" />
      <el-table-column label="药品入库单号" align="center" prop="orderNumber" width="200px" />
      <el-table-column label="入库状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="healthcare_entry_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="入库类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="healthcare_entry_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="药品品种数量" align="center" prop="variety" />
      <el-table-column label="药品入库数量" align="center" prop="tatolquantity" />
      <el-table-column label="药品入库金额" align="center" prop="amount" />

      <el-table-column label="入库操作员" align="center" prop="entryPerson" />
      <el-table-column label="入库时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180px">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row, queryParams2)"
            v-hasPermi="['pasd-healthcare:drugentry:edit']"><span v-if="scope.row.status === 1">修改</span>
            <span v-else>查看详情</span></el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['pasd-healthcare:drugentry:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改药品入库记录对话框 -->
    <el-dialog :title="title" v-model="open" width="1550px" append-to-body>
      <el-form ref="drugentryRef" :model="form" :rules="rules" label-width="150px" :inline="true">
        <el-form-item label="入库类型" prop="type" width="500px">
          <el-select v-model="form.type" placeholder="请选择入库类型" :disabled="isDisabled" style="width: 500px">
            <el-option v-for="dict in healthcare_entry_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="药品品种合计" prop="variety">
          <el-input v-model="form.variety" placeholder="请输入药品品种" style="width: 500px" :disabled="true" />
        </el-form-item>
        <el-form-item label="入库数量合计" prop="tatolquantity">
          <el-input v-model="form.tatolquantity" placeholder="请输入入库数量" style="width: 500px" :disabled="true" />
        </el-form-item>
        <el-form-item label="入库金额合计" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入入库金额" style="width: 500px" :disabled="true" />
        </el-form-item>
        <el-divider content-position="center">入库详情</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" :disabled="isDisabled"
              @click="handleAddHealthcareInventoryDrugentryDetails">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteHealthcareInventoryDrugentryDetails"
              :disabled="isDisabled">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="healthcareInventoryDrugentryDetailsList"
          :row-class-name="rowHealthcareInventoryDrugentryDetailsIndex" @selection-change="
            handleHealthcareInventoryDrugentryDetailsSelectionChange
          " ref="healthcareInventoryDrugentryDetails">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50" />

          <el-table-column label="药品档案" prop="medicineName" width="300px">
            <template #default="scope">
              <el-form-item :prop="`healthcareInventoryDrugentryDetailsList.${scope.$index}.medicineName`" :rules="[
                {
                  required: true,
                  message: '药品名称不能为空',
                  trigger: 'blur',
                },
              ]">
                <el-input v-model="healthcareInventoryDrugentryDetailsList[scope.$index]
                    .medicineName
                  " placeholder="请输入药品名称" :disabled="true" style="width: 250px" @blur="handleBlur(scope.$index)" />
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="条码" prop="barcode" width="150" />
          <el-table-column label="批次" prop="batch" width="110">
            <template #default="scope">
              <el-form-item :prop="`healthcareInventoryDrugentryDetailsList.${scope.$index}.batch`" :rules="[
                { required: true, message: '批次不能为空', trigger: 'blur' },
                {
                  pattern: /^[^\s]+$/,
                  message: '禁止包含空格',
                  trigger: 'blur',
                },
                {
                  max: 11,
                  message: '长度不能超过11位数',
                  trigger: 'blur',
                },
              ]">
                <el-input v-model="healthcareInventoryDrugentryDetailsList[scope.$index].batch
                  " placeholder="请输入批次" :disabled="healthcareInventoryDrugentryDetailsList[scope.$index]
                      .drugFilingId != null || isDisabled
                    " style="width: 90px" @blur="handleBlur(scope.$index)" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="入库数量" prop="quantity" width="140">
            <template #default="scope">
              <el-form-item :prop="`healthcareInventoryDrugentryDetailsList.${scope.$index}.quantity`" :rules="[
                { required: true, message: '数量不能为空', trigger: 'blur' },
                {
                  pattern: /^\d+$/,
                  message: '禁止包含小数负数',
                  trigger: 'blur',
                },
                {
                  pattern: /^[1-9]\d*$/,
                  message: '数量不能为0',
                  trigger: 'blur',
                },
                {
                  pattern: /^.{0,5}$/,
                  message: '禁止超5位数',
                  trigger: 'blur',
                  trigger: 'blur',
                },
              ]">
                <el-input v-model="healthcareInventoryDrugentryDetailsList[scope.$index]
                    .quantity
                  " placeholder="请输入入库数量" :disabled="isDisabled" style="width: 120px"
                  @blur="handleBlur(scope.$index)" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="单价" prop="price" width="110px">
            <template #default="scope">
              <el-form-item :prop="`healthcareInventoryDrugentryDetailsList.${scope.$index}.price`" :rules="[
                { required: true, message: '单价不能为空', trigger: 'blur' },
                {
                  pattern: /^\d*\.?\d+$/,
                  message: '单价禁止负数',
                  trigger: 'blur',
                },
                {
                  pattern: /^[^\s]+$/,
                  message: '禁止包含空格',
                  trigger: 'blur',
                },
                {
                  pattern: /^.{0,5}$/,
                  message: '禁止超5位数',
                  trigger: 'blur',
                  trigger: 'blur',
                },
              ]">
                <el-input v-model="healthcareInventoryDrugentryDetailsList[scope.$index].price
                  " placeholder="请输入单价" :disabled="healthcareInventoryDrugentryDetailsList[scope.$index]
                      .drugFilingId != null || isDisabled
                    " style="width: 90px" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="入库金额" prop="detailAmount" width="150px">
            <template #default="scope">
              <el-form-item prop="detailAmount">
                <el-input v-model="scope.row.detailAmount" placeholder="请输入入库金额" :disabled="true" style="width: 135px"
                  type="number" />
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="入库点" prop="storeroomId" width="170">
            <template #default="scope">
              <el-form-item :prop="`healthcareInventoryDrugentryDetailsList.${scope.$index}.storeroomId`" :rules="[
                {
                  required: true,
                  message: '入库点不能为空',
                  trigger: 'blur',
                },
              ]">
                <el-select v-model="healthcareInventoryDrugentryDetailsList[scope.$index]
                    .storeroomId
                  " placeholder="请选择入库点" style="width: 150px" @blur="handleBlur(scope.$index)" :disabled="healthcareInventoryDrugentryDetailsList[scope.$index]
                      .drugFilingId != null || isDisabled
                    ">
                  <el-option v-for="dict in storeroomList" :key="dict.id" :label="dict.storeroomName"
                    :value="dict.id" />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="有效日期" prop="expiryDate" width="200">
            <template #default="scope">
              <el-form-item :prop="`healthcareInventoryDrugentryDetailsList.${scope.$index}.expiryDate`" :rules="[
                {
                  required: true,
                  message: '有效日期不能为空',
                  trigger: 'blur',
                },
              ]">
                <el-date-picker clearable v-model="healthcareInventoryDrugentryDetailsList[scope.$index]
                    .expiryDate
                  " type="date" value-format="YYYY-MM-DD" placeholder="请选择有效日期" :disabled="healthcareInventoryDrugentryDetailsList[scope.$index]
                      .drugFilingId != null || isDisabled
                    " style="width: 150px" @blur="handleBlur(scope.$index)" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button type="text" icon="Edit" @click="openArchiveSelector(scope.row.index)"
                :disabled="isDisabled">选择</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-if="isPaginationVisible" v-show="detailsTotal > 0" :total="detailsTotal"
          v-model:page="queryParams2.pageNum" v-model:limit="queryParams2.pageSize" @pagination="handlePageChange" />
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" :disabled="isDisabled">入 库</el-button>
          <el-button type="primary" @click="handleSave" :disabled="isDisabled">
            {{ isSaving ? "保存中..." : "保存" }}</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
      <DrugArchive ref="archiveSelectorRef" title="药品库存选择" @selectedArchive="handleArchiveSelected" />
    </el-dialog>
    <!-- 数据导入对话框 -->
    <el-dialog title="数据导入" v-model="excelOpen" width="500px" append-to-body>
      <el-upload ref="uploadRef" class="upload-demo" :action="entryExcelUrl" :headers="headers"
        :before-upload="handleBeforeUpload" :on-success="handleUploadSuccess" :auto-upload="false" :limit="1">
        <template #trigger>
          <el-button type="primary" style="margin: 0 50px">选择上传文件</el-button>
        </template>

        <el-button class="ml-3" type="success" @click="submitUpload">
          确认上传
        </el-button>

        <template #tip>
          <div class="el-upload__tip">
            上传文件仅支持xls/xlsx格式,文件大小不得超过1M
          </div>
        </template>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script setup name="Drugentry">
import {
  listDrugentry,
  getDrugentry,
  delDrugentry,
  addDrugentry,
  updateDrugentry,
  saveDrugentry,
} from "@/api/healthcare/inventory/DrugEntry/drugentry.js";
import DrugArchive from "@/components/drugFiling/index.vue";
import { ref, computed, watchEffect } from "vue";
import { getToken } from "@/utils/auth";
import { listStoreroom } from "@/api/healthcare/inventory/StoreRoom/storeroom.js";

const archiveSelectorRef = ref(null);
const { proxy } = getCurrentInstance();
const {
  healthcare_entry_type,
  healthcare_entry_point,
  healthcare_entry_status,
} = proxy.useDict(
  "healthcare_entry_type",
  "healthcare_entry_point",
  "healthcare_entry_status"
);
const ListIndex = ref(0);

const drugentryList = ref([]);
const healthcareInventoryDrugentryDetailsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedHealthcareInventoryDrugentryDetails = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const isDisabled = ref(false);

const detailsTotal = ref(0);

const isPaginationVisible = ref(false);

const data = reactive({
  form: {
    variety: null,
    tatolquantity: null,
    amount: null,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    status: null,
    type: null,
  },

  rules: {
    type: [{ required: true, message: "入库类型不能为空", trigger: "change" }],
  },
});

// 上传前的校验
const props = defineProps({
  modelValue: [String, Object, Array],
  // 图片数量限制
  limit: {
    type: Number,
    default: 1,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 1,
  },
  // 文件类型, 例如['xls', 'xlsx']
  fileType: {
    type: Array,
    default: () => ["xls", "xlsx"],
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true,
  },
});

const { queryParams, form, rules } = toRefs(data);

// 打开对话框的方法
const openArchiveSelector = (index) => {
  archiveSelectorRef.value.showSelector();
  console.log("待入库查询", archiveSelectorRef.value);
  ListIndex.value = index - 1;
};

// 处理选中药品档案后的回调
const handleArchiveSelected = (archive) => {
  healthcareInventoryDrugentryDetailsList.value[ListIndex.value].drugArchiveId =
    archive.archiveId || archive.id;
  healthcareInventoryDrugentryDetailsList.value[ListIndex.value].medicineName =
    archive.medicineName;
  healthcareInventoryDrugentryDetailsList.value[ListIndex.value].barcode =
    archive.barcode;
  healthcareInventoryDrugentryDetailsList.value[ListIndex.value].drugFilingId =
    archive.filingId;
  healthcareInventoryDrugentryDetailsList.value[ListIndex.value].batch =
    archive.batch;
  healthcareInventoryDrugentryDetailsList.value[ListIndex.value].price =
    archive.retailPrice;
  healthcareInventoryDrugentryDetailsList.value[ListIndex.value].expiryDate =
    archive.expiryDate;
  healthcareInventoryDrugentryDetailsList.value[ListIndex.value].storeroomId =
    archive.storeroomId;

  console.log("选中的档案信息", archive);
};

// 计算药品品种合计
const calculateVarietyTotal = () => {
  const total = healthcareInventoryDrugentryDetailsList.value.length;
  form.value.variety = total;
  return total;
};

// 计算入库数量合计
const calculateQuantityTotal = () => {
  const total = healthcareInventoryDrugentryDetailsList.value.reduce(
    (acc, cur) => {
      return acc + (parseFloat(cur.quantity) || 0);
    },
    0
  );
  form.value.tatolquantity = total;
  return total;
};
// 计算入库金额合计
const calculateAmountTotal = () => {
  const total = healthcareInventoryDrugentryDetailsList.value.reduce(
    (acc, cur) => acc + (cur.detailAmount || 0),
    0
  );
  form.value.amount = total;
  return total;
};

// 计算入库金额
function calculateAmount(row) {
  if (row.quantity && row.price) {
    row.detailAmount = parseFloat(row.quantity) * parseFloat(row.price);
  } else {
    row.detailAmount = "";
  }
}

// 定义一个变量来存储停止监听器的函数
let stopWatchEffect;

// 监听入库数量和单价的变化

const createWatchEffect = () => {
  stopWatchEffect = watchEffect(() => {
    healthcareInventoryDrugentryDetailsList.value.forEach((item) => {
      calculateAmount(item); // 使用 calculateAmount 来计算每个条目的入库金额
    });

    // 其他计算总和的函数调用
    calculateVarietyTotal();
    calculateQuantityTotal();
    calculateAmountTotal();
  });
};

// 关闭监听器
const stopWatchEffectFunction = () => {
  if (stopWatchEffect) {
    stopWatchEffect();
    stopWatchEffect = null;
  }
};

const storeroomList = ref([]);
/** 查询药品入库记录列表 */
function getList() {
  loading.value = true;
  listDrugentry(queryParams.value).then((response) => {
    drugentryList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
  // 查询库房管理列表
  listStoreroom().then((response) => {
    storeroomList.value = response.rows;
    console.log(storeroomList.value);
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    orderNumber: null,
    status: null,
    type: null,
    variety: null,
    tatolquantity: null,
    quantity: null,
    amount: null,
    storeroomId: null,
    entryPerson: null,
    entryTime: null,
    createTime: null,
    createBy: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    medicineName: null,
    barcode: null,
    unit: null,
    expiryDate: null,
    healthcareInventoryDrugentryDetailsList: [],
  }; //

  proxy.resetForm("drugentryRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

const handleBlur = (index) => {
  form.value.healthcareInventoryDrugentryDetailsList =
    healthcareInventoryDrugentryDetailsList.value;
};

/** 新增按钮操作 */
function handleAdd() {
  reset();
  createWatchEffect();
  healthcareInventoryDrugentryDetailsList.value = [];
  isDisabled.value = false;
  open.value = true;
  isPaginationVisible.value = false;
  title.value = "添加药品入库记录";
}

const queryParams2 = ref({
  pageNum: 1,
  pageSize: 10,
  status: null,
  type: null,
});

const currentPage = ref(1); // 当前页码
const pageSize = ref(10); // 每页显示的记录数
const rowRon = ref({
  id: null,
});

/** 修改按钮操作 */
function handleUpdate(row, queryParams1) {
  rowRon.value.id = row.id;
  reset();
  isPaginationVisible.value = true;
  const _id = row.id || ids.value;
  const pageNum = queryParams1.pageNum;
  const pageSize = queryParams1.pageSize;
  getDrugentry(_id, pageNum, pageSize).then((response) => {
    form.value = response.data;
    detailsTotal.value = response.data.variety;
    healthcareInventoryDrugentryDetailsList.value =
      response.data.healthcareInventoryDrugentryDetailsList;
    total.value = response.data.total; // 更新总记录数
    if (form.value.status === 0) {
      isDisabled.value = true;
      // stopWatchEffectFunction()
    } else if (form.value.status === 1) {
      isDisabled.value = false;
    }
    open.value = true;
    title.value = "查看药品入库记录";
  });
}

function handlePageChange() {
  // currentPage.value = page;
  // 重新获取数据
  handleUpdate(rowRon.value, queryParams2.value);
}

/** 提交按钮 */
function submitForm() {
  if (form.value.healthcareInventoryDrugentryDetailsList.length == 0) {
    proxy.$modal.msgError("请添加入库明细");
    return;
  }
  proxy.$refs["drugentryRef"].validate((valid) => {
    if (valid) {
      form.value.healthcareInventoryDrugentryDetailsList =
        healthcareInventoryDrugentryDetailsList.value;
      if (form.value.id != null) {
        updateDrugentry(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDrugentry(form.value).then((response) => {
          console.log(form.value);
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

const isSaving = ref(false);
// 保存按钮操作
const handleSave = () => {
  proxy.$refs["drugentryRef"].validate((valid) => {
    form.value.healthcareInventoryDrugentryDetailsList =
      healthcareInventoryDrugentryDetailsList.value;
    console.log("待提交信息", form.value);
    if (valid) {
      saveDrugentry(form.value)
        .then((response) => {
          if (response.code === 200) {
            proxy.$modal.msgSuccess("保存成功");
            isSaving.value = true;
            open.value = false;
            getList();
          } else {
            proxy.$modal.msgError(response.msg);
          }
        })
        .finally(() => {
          isSaving.value = false;
        });
    }
  });
};

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除药品入库记录编号为"' + _ids + '"的数据项?')
    .then(function () {
      return delDrugentry(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

/** 入库详情,用于记录药品入库的详细信息序号 */
function rowHealthcareInventoryDrugentryDetailsIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 入库详情,用于记录药品入库的详细信息添加按钮操作 */
function handleAddHealthcareInventoryDrugentryDetails() {
  let obj = {};
  obj.drugArchiveId = "";
  obj.unit = "";
  obj.quantity = "";
  obj.detailAmount = "";
  obj.expiryDate = "";
  obj.medicineName = "";
  obj.barcode = "";
  obj.drugFilingId = "";
  obj.storeroomId = "";
  obj.price = "";
  healthcareInventoryDrugentryDetailsList.value.push(obj);
}

/** 入库详情,用于记录药品入库的详细信息删除按钮操作 */
function handleDeleteHealthcareInventoryDrugentryDetails() {
  if (checkedHealthcareInventoryDrugentryDetails.value.length == 0) {
    proxy.$modal.msgError(
      "请先选择要删除的入库详情,用于记录药品入库的详细信息数据"
    );
  } else {
    const healthcareInventoryDrugentryDetailss =
      healthcareInventoryDrugentryDetailsList.value;
    const checkedHealthcareInventoryDrugentryDetailss =
      checkedHealthcareInventoryDrugentryDetails.value;
    healthcareInventoryDrugentryDetailsList.value =
      healthcareInventoryDrugentryDetailss.filter(function (item) {
        return (
          checkedHealthcareInventoryDrugentryDetailss.indexOf(item.index) == -1
        );
      });
  }
}

/** 复选框选中数据 */
function handleHealthcareInventoryDrugentryDetailsSelectionChange(selection) {
  checkedHealthcareInventoryDrugentryDetails.value = selection.map(
    (item) => item.index
  );
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "pasd-healthcare/drugentry/export",
    {
      ...queryParams.value,
    },
    `drugentry_${new Date().getTime()}.xlsx`
  );
}

const excelOpen = ref(false);
// 导入弹窗打开
function handleImport() {
  excelOpen.value = true;
}

const uploadRef = ref(null);
// 确认上传
function submitUpload() {
  uploadRef.value.submit();
}
// 上传地址
const entryExcelUrl = ref(
  import.meta.env.VITE_APP_BASE_API + "/pasd-healthcare/drugentry/entryExcel"
);
// 上传请求头
const headers = ref({
  Authorization: "Bearer " + getToken(),
});

// 上传成功回调
function handleUploadSuccess(res, file) {
  if (res.code === 200) {
    proxy.$modal.msgSuccess("导入Excel成功");
    excelOpen.value = false;
    getList();
  } else {
    proxy.$modal.msgError(res.msg);
  }
  uploadRef.value.clearFiles();
  proxy.$modal.closeLoading();
}
// 上传失败
function handleUploadError() {
  proxy.$modal.msgError("上传图片失败");
  uploadRef.value.clearFiles();
  proxy.$modal.closeLoading();
}

// 上传前loading加载
function handleBeforeUpload(file) {
  let isExcel = false;
  if (props.fileType.length) {
    let fileExtension = "";
    if (file.name.lastIndexOf(".") > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
    }
    isExcel = props.fileType.some((type) => {
      if (file.type.indexOf(type) > -1) return true;
      if (fileExtension && fileExtension.indexOf(type) > -1) return true;
      return false;
    });
  }
  if (!isExcel) {
    proxy.$modal.msgError(
      `文件格式不正确, 请上传${props.fileType.join("/")}格式文件!`
    );
    return false;
  }
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      proxy.$modal.msgError(`上传头Excel大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  proxy.$modal.loading("正在上传Excel,请稍候...");
}

getList();
</script>
<style scoped>
.drug-count {
  float: right;
}
</style>