<template>
  <el-dialog
    :title="title"
    v-model="visible"
    width="1550px"
    append-to-body
  >
    <el-form
      @submit.prevent
      :inline="true"
      class="demo-form-inline"
    >
      <el-form-item label="查询条件">
        <el-input
          v-model="searchForm.query"
          placeholder="请输入药品名称或条码"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="searchArchives"
        >查询</el-button>
        <el-button
          icon="Refresh"
          @click="resetQuery"
        >重置</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="mergedData"
      :border="parentBorder"
      style="width: 100%"
      @row-click="selectRow"
      v-loading="loading"
    >
      <el-table-column
        label="序号"
        type="index"
        width="50"
      />
      <el-table-column
        label="药品名称"
        width="250px"
        align="center"
        prop="medicineName"
      />
      <el-table-column
        label="生产厂家"
        width="250px"
        align="center"
        prop="manufacturer"
      />
      <el-table-column
        label="条码"
        align="center"
        width="150px"
        prop="barcode"
      />
      <el-table-column
        label="规格"
        align="center"
        width="200px"
        prop="specification"
      />
      <el-table-column
        label="批号"
        align="center"
        prop="batch"
      />
      <el-table-column
        label="所在库房"
        align="center"
        prop="storeroomName"
      />
      <el-table-column
        label="生产日期"
        align="center"
        prop="expiryDate"
      />
      <el-table-column
        label="剩余盒数"
        align="center"
        prop="boxCount"
      />
      <el-table-column
        label="零售价"
        align="center"
        prop="retailPrice"
      />
      <el-table-column
        label="操作"
        align="center"
        fixed="right"
        width="100"
      >
        <template #default="scope">
          <el-button
            type="text"
            size="small"
            @click="confirmSelection(scope.row)"
          >选择</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="handlePagination"
    />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { listArchive } from '@/api/healthcare/inventory/DrugFiling/archive.js';

const props = defineProps({
  title: String,
});

const emit = defineEmits(['selectedArchive']);

const visible = ref(false);
const archiveList = ref([]);
const mergedData = ref([]);
const selectedArchive = ref(null);
const parentBorder = ref(false);
const searchForm = reactive({
  query: ''
});
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  medicineName: null,
  barcode: null,
});
const total = ref(0);
const loading = ref(false);

onMounted(() => {
  loadArchives();
});

// 加载药品档案列表
function loadArchives() {
  loading.value = true;
  listArchive(queryParams).then(response => {
    const rows = response.rows || [];
    const formattedRows = rows.map(row => ({
      ...row,
      drugFilings: row.drugFilings || [] // 确保每个 row 都有 drugFilings 集合，即使为空
    }));
    archiveList.value = formattedRows;
    total.value = response.total;
    console.log("获取药品档案archiveList：", archiveList.value);

    // 合并 archiveList 和 drugFilings
    mergedData.value = formattedRows.flatMap(row => [
      {
        ...row,
        filingId: null,
        packCount: row.packCount ?? 0,
        inventoryUnit: row.inventoryUnit,
        splitUnit: row.splitUnit,
        minNumber: row.minNumber,
        unitQuantity: row.minNumber ?? row.unitQuantity,
        isSplit: row.isSplit
      },
      ...row.drugFilings.map(filing => ({
        medicineName: row.medicineName,
        manufacturer: row.manufacturer,
        barcode: row.barcode,
        specification: row.specification,
        batch: filing.batch,
        expiryDate: filing.expiryDate,
        boxCount: filing.boxCount,
        packCount: filing.packCount,
        retailPrice: filing.retailPrice,
        minPrice: filing.minPrice,
        minNumber: filing.minNumber ?? row.minNumber,
        unitQuantity: filing.minNumber ?? row.minNumber,
        inventoryUnit: filing.inventoryUnit ?? row.inventoryUnit,
        splitUnit: filing.splitUnit ?? row.splitUnit,
        filingId: filing.id,
        archiveId: row.id,
        storeroomId: filing.storeroomId,
        storeroomName: filing.storeroomName,
        isSplit: row.isSplit
      }))
    ]);

    console.log("合并后的数据mergedData：", mergedData.value);
  }).catch(error => {
    ElMessage.error("加载药品档案失败：" + error.message);
  }).finally(() => {
    loading.value = false;
  });
}

// 查询按钮
function searchArchives() {
  queryParams.pageNum = 1; // 重置分页
  queryParams.medicineName = null;
  queryParams.barcode = null;

  const query = searchForm.query.trim();
  if (query) {
    if (/^\d+$/.test(query)) { // 判断是否为数字（条码）
      queryParams.barcode = query;
    } else {
      queryParams.medicineName = query;
    }
  }

  loadArchives();
}

// 重置按钮
function resetQuery() {
  searchForm.query = '';
  queryParams.medicineName = null;
  queryParams.barcode = null;
  queryParams.pageNum = 1; // 重置分页
  loadArchives();
}

// 选择行时触发
function selectRow(row) {
  selectedArchive.value = row;
}

// 确认选择并关闭弹窗
function confirmSelection(row) {
  if (row) {
    emit('selectedArchive', row);
    visible.value = false;
  }
}

// 显示弹窗
const showSelector = () => {
  visible.value = true;
};
defineExpose({ showSelector });

// 分页处理
function handlePagination(pagination) {
  queryParams.pageNum = pagination.page;
  queryParams.pageSize = pagination.limit;
  console.log("分页参数：", queryParams);
  loadArchives();
}
</script>

<style scoped>
.demo-form-inline {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
