<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="药品名称" prop="medicineName">
        <el-input v-model="queryParams.medicineName" placeholder="请输入药品名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="条码" prop="barcode">
        <el-input v-model="queryParams.barcode" placeholder="请输入条码" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="是否拆分" prop="isSplit">
        <el-select v-model="queryParams.isSplit" placeholder="请选择" clearable style="width: 150px">
          <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="批次" prop="batch">
        <el-input v-model="queryParams.batch" placeholder="请输入批次" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="有效期" prop="expiryDateRange">
        <el-date-picker v-model="queryParams.expiryDateRange" type="daterange" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" style="width: 260px" clearable />
      </el-form-item>
      <el-form-item label="库房" prop="storeroomId">
        <el-select v-model="queryParams.storeroomId" placeholder="请选择库房" clearable style="width: 180px">
          <el-option v-for="item in storeroomList" :key="item.id" :label="item.storeroomName" :value="item.id" />
        </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="['healthcare:archive:add']">药品建档</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['healthcare:archive:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['healthcare:archive:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['healthcare:archive:export']"
          >导出</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Upload" @click="handleImport"
          v-hasPermi="['healthcare:archive:add']">批量建档</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Download" @click="handleExport"
          v-hasPermi="['healthcare:archive:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div>
      <el-table :data="archiveList" :border="parentBorder" style="width: 100%" :tree-props="treeProps" row-key="id"
        :expand-row-keys="expandedRows" @row-click="toggleExpand">
        <el-table-column label="序号" type="index" width="55" align="center" />
        <el-table-column type="expand" width="55" align="center" />
        <el-table-column label="商品名称" align="center" prop="medicineName" />
        <el-table-column label="生产厂家" align="center" prop="manufacturer" />
        <el-table-column label="商品条码" align="center" prop="barcode" />
        <el-table-column label="是否拆分" align="center" prop="isSplit">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.isSplit" />
          </template>
        </el-table-column>
        <el-table-column label="商品规格" align="center" prop="specification" />
        <el-table-column label="最小单位数量" align="center">
          <template #default="scope">
            <span v-if="scope.row.isSplit === 'Y'">
              {{ scope.row.minNumber }}
              <span>
                <dict-tag style="display: inline" :options="healthcare_packaging_unit" :value="scope.row.splitUnit"
                  v-if="scope.row.isSplit === 'Y'" />
              </span>
            </span>
          </template>
        </el-table-column>

        <el-table-column type="expand">
          <template #default="props">
            <div style="margin-left: 20px;">
              <el-table :data="props.row.drugFilings" :border="childBorder" style="width: 98%">
                <!-- 添加序号列 -->
                <el-table-column label="序号" type="index" width="80" align="center" />

                <el-table-column label="批次" prop="batch" align="center" width="180">
                  <template #default="scope">
                    <el-input v-if="scope.row.editing" v-model="scope.row.batch" placeholder="请输入批次号" size="small" />
                    <span v-else>{{ scope.row.batch }}</span>
                  </template>
                </el-table-column>

                <el-table-column label="有效期至" prop="expiryDate" align="center" width="180">
                  <template #default="scope">
                    <el-date-picker v-if="scope.row.editing" v-model="scope.row.expiryDate" type="date"
                      placeholder="选择日期" value-format="YYYY-MM-DD" size="small" />
                    <span v-else>{{ scope.row.expiryDate }}</span>
                  </template>
                </el-table-column>

                <el-table-column label="所在库房" prop="storeroomName" align="center" width="180">
                  <template #default="scope">
                    <span>{{ scope.row.storeroomName }}</span>
                  </template>
                </el-table-column>

                <el-table-column label="数量" align="center" width="220">
                  <template #default="scope">
                    <div v-if="scope.row.editing" style="display: flex; align-items: center; gap: 8px;">
                      <el-input-number v-model="scope.row.boxCount" :min="0" :precision="0" size="small"
                        style="width: 100px" />
                      <span>{{ scope.row.inventoryUnit }}</span>
                      <template v-if="props.row.isSplit === 'Y'">
                        <el-input-number v-model="scope.row.packCount" :min="0" :precision="0" size="small"
                          style="width: 100px" />
                        <dict-tag :options="healthcare_packaging_unit" :value="scope.row.splitUnit" />
                      </template>
                    </div>
                    <div v-else style="display: inline-flex; align-items: center; gap: 8px;">
                      {{ scope.row.boxCount }} {{ scope.row.inventoryUnit }}
                      <template v-if="props.row.isSplit === 'Y'">
                        {{ scope.row.packCount }} <dict-tag :options="healthcare_packaging_unit"
                          :value="scope.row.splitUnit" />
                      </template>
                    </div>
                  </template>
                </el-table-column>

                <el-table-column label="采购价" prop="retailPrice" align="center" width="180">
                  <template #default="scope">
                    <el-input v-if="scope.row.editing" v-model="scope.row.retailPrice" placeholder="采购价" size="small"
                      style="width: 120px">
                      <template #append>元</template>
                    </el-input>
                    <span v-else>{{ scope.row.retailPrice }} 元</span>
                  </template>
                </el-table-column>

                <el-table-column label="最小单位价格" prop="minPrice" align="center" width="180">
                  <template #default="scope">
                    <el-input v-if="scope.row.editing" v-model="scope.row.minPrice" placeholder="最小单位价格" size="small"
                      style="width: 120px">
                      <template #append>元</template>
                    </el-input>
                    <span v-else>{{ scope.row.minPrice }} 元</span>
                  </template>
                </el-table-column>

                <!-- 操作列 -->
                <el-table-column label="操作" align="center" width="220" fixed="right">
                  <template #default="scope">
                    <div style="display: flex; gap: 8px; justify-content: center;">
                      <el-button v-if="!scope.row.editing" link type="primary" icon="Edit" size="small"
                        @click.stop="handleBatchEdit(scope.row)"
                        v-hasPermi="['healthcare:archive:batch:edit']">修改</el-button>
                      <el-button v-if="scope.row.editing" link type="success" icon="Check" size="small"
                        @click.stop="handleBatchSave(scope.row, props.row)"
                        v-hasPermi="['healthcare:archive:batch:edit']">保存</el-button>
                      <el-button v-if="scope.row.editing" link type="info" icon="Close" size="small"
                        @click.stop="handleBatchCancel(scope.row)">取消</el-button>
                      <el-button link type="danger" icon="Delete" size="small"
                        @click.stop="handleBatchDelete(scope.row, props.row)"
                        v-hasPermi="['healthcare:archive:batch:remove']">删除</el-button>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click.stop="handleUpdate(scope.row)"
              v-hasPermi="['healthcare:archive:edit']">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
              v-hasPermi="['healthcare:archive:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <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="1200px" append-to-body>
      <el-form ref="archiveRef" :model="form" :rules="rules" :inline="true">
        <el-form-item label="药品名称" prop="medicineName">
          <el-input v-model="form.medicineName" placeholder="请输入药品名称" style="width: 250px" />
        </el-form-item>
        <el-form-item label="生产厂家" prop="manufacturer">
          <el-input v-model="form.manufacturer" placeholder="请输入生产厂家" style="width: 250px" />
        </el-form-item>
        <el-form-item label="药品条码" prop="barcode">
          <el-input v-model="form.barcode" placeholder="请输入条码" style="width: 250px" />
        </el-form-item>
        <el-form-item label="药品规格" prop="specification">
          <el-input v-model="form.specification" placeholder="请输入规格" style="width: 250px" />
        </el-form-item>

        <el-form-item label="是否拆分" prop="isSplit">
          <el-select v-model="form.isSplit" placeholder="请选择是否允许拆分" style="width: 250px">
            <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>

        <!-- 详细规格 -->
        <div v-if="form.isSplit === 'Y'">
          <div>
            <el-divider><i class="el-icon-mobile-phone">详细规格</i></el-divider>
          </div>

          <el-form-item prop="state">
            <el-radio-group v-model="form.state">
              <el-radio value="0">剂量（成分含量）</el-radio>
              <!-- <el-radio value="1">剂量（容量：成分含量）</el-radio> 弃用-->
            </el-radio-group>
          </el-form-item>

          <div v-if="form.state === '0'">
            <span>
              示例：
            </span>
            <!-- 固态详细规格 -->
            <el-form-item label="剂量（成分含量）" prop="dosageForm" class="spe-title">3g</el-form-item>
            <el-form-item label="最小包装数量" prop="unitQuantity" class="title-center">12袋</el-form-item>
            <el-form-item label="包装单位" prop="packageUnit" class="spe-title">盒</el-form-item>
            <el-form-item label="最小单位数量" prop="minNumber" class="spe-title" />
            <el-input v-model="form.dosageForm" placeholder="请输入剂量" style="width: 230px; margin-left: 100px">
              <template #append>
                <el-select v-model="form.dosageUnit" filterable placeholder="请选择" style="width: 80px">
                  <el-option v-for="dict in healthcare_dose_unit" :key="dict.value" :label="dict.label"
                    :value="dict.value"></el-option>
                </el-select>
              </template>
            </el-input>
            <h1 style="display: inline">*</h1>
            <el-input v-model="form.unitQuantity" placeholder="请输入最小包装数量" style="width: 230px">
              <template #append>
                <el-select v-model="form.splitUnit" placeholder="请选择最小包装单位" style="width: 80px" filterable>
                  <el-option v-for="dict in healthcare_packaging_unit" :key="dict.value" :label="dict.label"
                    :value="dict.value"></el-option>
                </el-select>
              </template>
            </el-input>
            <h1 style="display: inline">/</h1>
            <el-select v-model="form.packageUnit" placeholder="请选择包装单位" style="width: 80px" filterable>
              <el-option v-for="dict in healthcare_packaging_unit" :key="dict.value" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
            <el-input v-model="form.minNumber" placeholder="请输入最小单位数量" style="width: 150px; margin-left: 100px" />
          </div>
          <span
            style="color:red;font-size:14px">说明：该单位数量用于做拆分后的价格计算。拆分示例：一次性使用医用棉签，商品规格是40支×50小袋，那么拆分后的最小单位数量是50。在对药品进行拆分时，只需要输入该药品拆分后的最小包装数量的总数量即可</span>
          <!-- 液态详细规格 -->
          <div v-if="form.state === '1'">
            <span>示例：</span>
            <el-form-item label="剂量（容量：成分含量）" prop="volume" class="spe-title">8ml：20ml</el-form-item>
            <el-form-item label="最小包装数量" prop="unitQuantity" style="margin: -20px 140px 0 460px"
              class="title-center2">10瓶</el-form-item>
            <el-form-item label="包装单位" prop="packageUnit" class="spe-title" style="margin-left: 0px">条</el-form-item>

            <el-input v-model="form.volume" placeholder="请输入容量" style="width: 300px; margin-left: 100px"
              class="custom-form-item">
              <template #append>
                <el-select v-model="form.volumeUnit" placeholder="请选择" filterable style="width: 80px">
                  <el-option v-for="dict in healthcare_dose_unit" :key="dict.value" :label="dict.label"
                    :value="dict.value"></el-option>
                </el-select>
              </template>
            </el-input>
            <h1 style="display: inline">:</h1>
            <el-input v-model="form.dosageForm" placeholder="请输入成分含量" style="width: 300px">
              <template #append>
                <el-select v-model="form.dosageUnit" placeholder="请选择" filterable style="width: 80px">
                  <el-option v-for="dict in healthcare_dose_unit" :key="dict.value" :label="dict.label"
                    :value="dict.value"></el-option>
                </el-select>
              </template>
            </el-input>
            <h1 style="display: inline">*</h1>
            <el-input v-model="form.unitQuantity" placeholder="请输入最小包装数量" style="width: 230px">
              <template #append>
                <el-select v-model="form.splitUnit" placeholder="请选择" filterable style="width: 80px">
                  <el-option v-for="dict in healthcare_packaging_unit" :key="dict.value" :label="dict.label"
                    :value="dict.value"></el-option>
                </el-select>
              </template>
            </el-input>
            <h1 style="display: inline">/</h1>
            <el-select v-model="form.packageUnit" placeholder="请选择" filterable style="width: 80px">
              <el-option v-for="dict in healthcare_packaging_unit" :key="dict.value" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
          </div>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 数据导入对话框 -->
    <el-dialog title="数据导入" v-model="excelOpen" width="500px" append-to-body>
      <el-upload ref="uploadRef" class="upload-demo" :action="archiveExcel" :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="Archive">

// 价格向上取整到小数点后两位（进一法）
function ceilPrice(value) {
  const num = Number(value)
  if (isNaN(num)) return '0.00'
  const scaled = Math.round(num * 10000)
  const cents = Math.ceil(scaled / 100)
  return (cents / 100).toFixed(2)
}

import {
    addArchive,
    delArchive,
    deleteBatch,
    getArchive,
    listArchive,
    updateArchive,
    updateBatch,
} from "@/api/healthcare/inventory/DrugFiling/archive.js"
import { listStoreroom } from "@/api/healthcare/inventory/StoreRoom/storeroom.js"
import { getToken } from "@/utils/auth"
import { getCurrentInstance, reactive, ref, toRefs } from "vue"
import { useRoute } from 'vue-router'

// import { ElNotification } from 'element-plus'

const { proxy } = getCurrentInstance();
const { healthcare_dose_unit, sys_yes_no, healthcare_packaging_unit } =
  proxy.useDict(
    "healthcare_dose_unit",
    "sys_yes_no",
    "healthcare_packaging_unit"
  );
console.log("单位字典", healthcare_packaging_unit);

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

// 上传地址
const archiveExcel = ref(
  import.meta.env.VITE_APP_BASE_API + "/healthcare/archive/archiveExcel"
);
// 上传请求头
const headers = ref({
  Authorization: "Bearer " + getToken(),
});

// 打开数据导入对话框
const excelOpen = ref(false);

// 上传Excel文件
const uploadRef = ref({});

// 上传前的校验
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 editingBatches = ref([]);

// 开始编辑批次
const handleBatchEdit = (row) => {
  row.editing = true;
  row.originalData = { ...row };
  editingBatches.value.push(row.id);
}

// 保存批次修改
const handleBatchSave = (row, parentRow) => {
  // 添加数据验证
  if (!row.batch) {
    proxy.$modal.msgError("批次号不能为空");
    return;
  }
  // 如果是可拆分药品，计算最小单位价格
  if (parentRow.isSplit === 'Y' && parentRow.minNumber) {
    const retailPrice = parseFloat(row.retailPrice) || 0;
    const minNumber = parseFloat(parentRow.minNumber) || 1;
    row.minPrice = ceilPrice(retailPrice / minNumber);
  }

  // 不可拆分药品，最小单位价格等于零售价      暂时不使用
  // else {
  //   row.minPrice = row.retailPrice;
  // }


  updateBatch({
    ...row,
    archiveId: parentRow.id
  }).then(response => {
    proxy.$modal.msgSuccess("批次修改成功");
    const index = archiveList.value.findIndex(item => item.id === parentRow.id);
    if (index !== -1) {
      archiveList.value[index].drugFilings = [...archiveList.value[index].drugFilings];
    }
    row.editing = false;
    editingBatches.value = editingBatches.value.filter(id => id !== row.id);
  }).catch(error => {
    proxy.$modal.msgError("批次修改失败");
    console.error('保存失败:', error);
  });
}

// 取消批次编辑
const handleBatchCancel = (row) => {
  Object.assign(row, row.originalData);
  row.editing = false;
  editingBatches.value = editingBatches.value.filter(id => id !== row.id);
}

// 删除批次
const handleBatchDelete = (row, parentRow) => {
  proxy.$modal.confirm('确认删除该批次信息吗？').then(() => {
    deleteBatch(row.id).then(response => {
      proxy.$modal.msgSuccess("批次删除成功");
      const parentIndex = archiveList.value.findIndex(item => item.id === parentRow.id);
      if (parentIndex !== -1) {
        archiveList.value[parentIndex].drugFilings =
          archiveList.value[parentIndex].drugFilings.filter(item => item.id !== row.id);
      }
    }).catch(error => {
      proxy.$modal.msgError("批次删除失败");
      console.error('删除失败:', error);
    });
  }).catch(() => { });
}



const data = reactive({
  form: {
    isSplit: "N", // 默认值
    state: "0", // 默认值
    dosageForm: null,
    dosageUnit: null,
    volume: null,
    volumeUnit: null,
    unitQuantity: null,
    splitUnit: null,
    packageUnit: null,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    medicineName: null,
    barcode: null,
    isSplit: null,
    batch: null,
    expiryDateRange: null,
    storeroomId: null,
    type: null
  },
  rules: {
    medicineName: [
      { required: true, message: "药品名称不能为空", trigger: "blur" },
      {
        pattern: /^\S+.*$/,
        message: "药品名称不能只包含空格",
        trigger: "blur",
      },
    ],
    manufacturer: [
      { required: true, message: "生产厂家不能为空", trigger: "blur" },
      {
        pattern: /^\S+.*$/,
        message: "生产厂家不能只包含空格",
        trigger: "blur",
      },
    ],
    barcode: [
      { required: true, message: "条码不能为空", trigger: "blur" },
      { pattern: /^\S+.*$/, message: "条码不能只包含空格", trigger: "blur" },
    ],
    specification: [
      { required: true, message: "规格不能为空", trigger: "blur" },
      { pattern: /^\S+.*$/, message: "规格不能只包含空格", trigger: "blur" },
    ],
    unitQuantity: [
      { required: true, message: "最小包装数量不能为空", trigger: "blur" },
      {
        pattern: /^\S+.*$/,
        message: "最小包装数量不能只包含空格",
        trigger: "blur",
      },
      {
        pattern: /^\d{1,6}(\.\d{1,6})?$/,
        message: "最小包装数量只能输入最多6位数字",
        trigger: "blur",
      },
    ],
    packageUnit: [
      { required: true, message: "包装单位不能为空", trigger: "blur" },
      {
        pattern: /^\S+.*$/,
        message: "包装单位不能只包含空格",
        trigger: "blur",
      },
    ],
    // volume: [
    //   { required: true, message: "容量不能为空", trigger: "blur" },
    //   { pattern: /^\S+.*$/, message: "容量不能只包含空格", trigger: "blur" },
    //   {
    //     pattern: /^\d{1,6}(\.\d{1,6})?$/,
    //     message: "容量只能输入最多6位数字",
    //     trigger: "blur",
    //   },
    // ],
    state: [{ required: true, message: "状态不能为空", trigger: "blur" }],
    minNumber: [
      { required: true, message: "最小单位数量不能为空", trigger: "blur" },
      {
        pattern: /^\S+.*$/,
        message: "最小单位数量不能只包含空格",
        trigger: "blur",
      },
      {
        pattern: /^\d{1,6}(\.\d{1,6})?$/,
        message: "最小单位数量只能输入最多6位数字",
      },
      {
        pattern: /^\d{1,6}$/,
        message: "最小包装数量只能输入整数",
        trigger: "blur",
      },
      {
        pattern: /^[1-9]\d*\.?\d*$/,
        message: "最小单位数量不能以0开头或者仅含0",
        trigger: "blur",
      },
    ],
  },
});

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

// 树形结构配置
const treeProps = reactive({
  children: "drugFilings", // 使用 drugFilings 作为子节点属性
  hasChildren: "hasChildren",
});

// 边框开关
const parentBorder = ref(false);
const childBorder = ref(false);

// 默认收起的行
const expandedRows = ref([]);

const storeList = ref([]);
// 库房列表
const storeroomList = ref([]);

// 获取库房列表
function getStoreroomList() {
  listStoreroom().then((response) => {
    storeroomList.value = response.rows || [];
  });
}
const route = useRoute();
let drugType = ref(route.query.type);
console.log('Initial received route:', drugType.value); // 添加日志以调试
// 查询药品档案列表
function getList() {
  loading.value = true;
  queryParams.value.type = drugType.value;
  // 处理有效期日期范围参数
  const params = { ...queryParams.value };
  if (params.expiryDateRange && params.expiryDateRange.length === 2) {
    params.expiryDateStart = params.expiryDateRange[0];
    params.expiryDateEnd = params.expiryDateRange[1];
  }
  delete params.expiryDateRange;
  listArchive(params)
    .then((response) => {
      const rows = response.rows || [];
      archiveList.value = formatData(rows);
      total.value = response.total;
      loading.value = true;
    })
    .catch((error) => {
      console.error("Error fetching data:", error);
      loading.value = false;
    });
}


// 格式化数据的方法
const formatData = (data) => {
  return data.map((item) => {
    const children =
      item.drugFilings?.map((filing) => ({
        ...filing,
        medicineName: item.medicineName,
        manufacturer: item.manufacturer,
        barcode: item.barcode,
        specification: item.specification,
        minNumber: item.minNumber,
        retailPrice: filing.retailPrice ?? item.retailPrice,
        medicineCode: filing.medicineCode,
        batch: filing.batch,
        expiryDate: filing.expiryDate,
        boxCount: filing.boxCount,
        packCount: filing.packCount,
        inventoryUnit: filing.inventoryUnit,
      })) || [];

    return {
      ...item,
      drugFilings: children,
      hasChildren: children.length > 0,
    };
  });
};

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

// 表单重置
function reset() {
  form.value = {
    id: null,
    medicineCode: null,
    medicineName: null,
    manufacturer: null,
    barcode: null,
    specification: null,
    retailPrice: null,
    minNumber: null,
    isSplit: null,
    state: "0",
    dosageForm: null,
    dosageUnit: null,
    volume: null,
    volumeUnit: null,
    unitQuantity: null,
    splitUnit: null,
    packageUnit: null,
    createTime: null,
    createBy: null,
    updateBy: null,
    updateTime: null,
    remark: null,
  };
  proxy.resetForm("archiveRef");
}

// 搜索按钮操作
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;
}

// 修改按钮点击事件
function handleEdit(row) {
  open.value = true;
  title.value = "修改药品档案";
  form.value = { ...row }; // 将选中的行数据复制到 form 中
  if (form.value.isSplit === "Y") {
    form.value.state = row.state; // 确保 state 被正确赋值
  }

}

// 新增按钮点击事件
function handleAdd() {
  open.value = true;
  title.value = "新增药品档案";
  reset();
  form.value.splitUnit = '1';
  form.value.dosageUnit = '1';
  form.value.volumeUnit = '1';
  form.value.packageUnit = '1';
}
// 修改按钮操作
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getArchive(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改药品档案";
    if (form.value.isSplit === "Y") {
      form.value.state = row.state;
    }
    console.log(form.value);

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

// 提交文件
function submitUpload() {
  uploadRef.value.submit();
}

// 上传成功回调
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，请稍候...");
}
// 提交按钮
function submitForm() {
  proxy.$refs["archiveRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateArchive(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addArchive(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

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

// 导出按钮操作
function handleExport() {
  const { pageNum, pageSize, ...exportParams } = queryParams.value;
  proxy.download(
    "healthcare/archive/export",
    exportParams,
    `archive_${new Date().getTime()}.xlsx`
  );
}

// 切换展开状态
function toggleExpand(row, column, event) {
  // 防止点击按钮时触发行的展开或收起
  if (event.target.closest(".el-button")) {
    return;
  }
  const index = expandedRows.value.indexOf(row.id);
  if (index === -1) {
    // 清空所有已展开的行
    expandedRows.value = [row.id];
  } else {
    expandedRows.value.splice(index, 1);
  }
}

getList();
getStoreroomList();
</script>

<style scoped>
h1 {
  line-height: 1;
  margin: 0 10px 0 10px;
}

.title-center {
  margin: 0 20px 0 125px;
  display: inline-block;
  /* 使提示信息水平显示 */
  color: red;
  font-size: 12px;
}

.title-center2 {
  margin: 0 290px 0 150px;
  margin-bottom: 20px;
  /* 调整表单项之间的间距 */
  display: inline-block;
  /* 使提示信息水平显示 */
  color: red;
  font-size: 12px;
}

.spe-title {
  margin-bottom: 20px;
  /* 调整表单项之间的间距 */
  display: inline-block;
  /* 使提示信息水平显示 */
  color: red;
  font-size: 12px;
  margin-left: 100px;
  /* 调整提示信息与输入框的距离 */
}

.small-padding {
  padding: 5px;
  /* 设置操作列的内边距 */
}

.fixed-width {
  width: 100px;
  /* 设置操作列的固定宽度 */
}

.custom-form-item .el-form-item__error {
  display: inline-block;
  /* 使提示信息水平显示 */
  color: red;
  font-size: 12px;
  margin-left: 8px;
  /* 调整提示信息与输入框的距离 */
}

.title-center {
  margin-bottom: 20px;
  /* 调整表单项之间的间距 */
}



/* 知无涯 */
/* 批次表格样式调整 */
/* 编辑模式下的输入框样式 */
.el-table .el-input__inner {
  height: 28px;
  line-height: 28px;
}

/* 操作按钮间距 */
.el-table .el-button {
  margin-left: 5px;
  margin-right: 5px;
}

/* 添加批次按钮样式 */
.add-batch-btn {
  margin-top: 10px;
}

/* 知无涯 */
</style>