<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form ref="queryRef" :model="queryParams" :inline="true" v-show="showSearch" label-width="68px">
      <!-- 使用日期（新增） -->
      <el-form-item label="使用日期" style="width: 308px">
        <el-date-picker v-model="daterangeUseTime" type="daterange" range-separator="-" start-placeholder="开始日期"
          end-placeholder="结束日期" value-format="YYYY-MM-DD" />
      </el-form-item>

      <!-- 创建日期（原有） -->
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker v-model="daterangeCreateTime" type="daterange" range-separator="-" start-placeholder="开始日期"
          end-placeholder="结束日期" value-format="YYYY-MM-DD" />
      </el-form-item>

      <el-form-item label="羊只耳号" prop="sheepNo">
        <el-input v-model="queryParams.sheepNo" placeholder="羊只耳号" clearable @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item label="使用名称" prop="name">
        <el-select v-model="queryParams.name" placeholder="请选择使用药品名称" clearable filterable style="width: 100%"
          @keyup.enter="handleQuery">
          <el-option v-for="item in medicines" :key="item.value" :label="item.label" :value="item.label" />
        </el-select>
      </el-form-item>

      <el-form-item label="使用类型" prop="useType">
        <el-select v-model="queryParams.useType" placeholder="请选择使用类型" clearable style="width: 180px">
          <el-option v-for="dict in pres_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="warning" plain icon="Download" @click="handleExport" v-hasPermi="['biosafety:usage:export']">
          导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="usageList" @selection-change="handleSelectionChange">
      <el-table-column label="使用时间" align="center" prop="datetime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.datetime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="使用名称" align="center" prop="name" />
      <el-table-column label="羊只耳号" align="center" prop="sheepNo" />
      <el-table-column label="羊舍" align="center" prop="sheepfoldName" />
      <el-table-column label="使用类型" align="center" prop="useType">
        <template #default="scope">
          <dict-tag :options="pres_type" :value="scope.row.useType" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{m}') }}</span>
        </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="View" @click="handleDetail(scope.row)"
            v-hasPermi="['biosafety:usage:query']">
            详情
          </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" :page-sizes="[20, 50, 100, 200, 500, 1000, 2000]" @pagination="getList" />

    <!-- 详情弹窗（保持不变） -->
    <el-dialog :title="title" v-model="open" width="680px" top="8vh" append-to-body :close-on-click-modal="false"
      class="usage-detail-dialog">
      <!-- 基础信息 -->
      <el-card shadow="never" class="detail-card">
        <template #header>
          <div class="card-header">
            <el-icon>
              <Document />
            </el-icon> 基本信息
          </div>
        </template>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="使用名称">{{ form.name }}</el-descriptions-item>
          <el-descriptions-item label="使用类型">
            <el-tag size="small" :type="form.useType === 1 ? 'primary' : 'success'">
              {{ pres_type.find(it => it.value === form.useType)?.label || '' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="使用时间" :span="2">
            {{ parseTime(form.createTime, '{y}-{m}-{d} {h}:{i}') }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 药品明细 -->
      <el-card shadow="never" class="detail-card" style="margin-top: 16px">
        <template #header>
          <div class="card-header">
            <el-icon>
              <List />
            </el-icon> 药品使用明细
          </div>
        </template>
        <el-table :data="swMedicineUsageDetailsList" stripe size="small"
          :row-class-name="rowSwMedicineUsageDetailsIndex" style="width: 100%">
          <el-table-column label="药品" prop="mediName" show-overflow-tooltip />
          <el-table-column label="用量" prop="dosage" width="80" />
          <el-table-column label="单位" prop="unit" align="center" :formatter="formatUnit" />
          <el-table-column label="使用方法" align="center" prop="usageId" :formatter="formatUsage" />
          <el-table-column v-if="form.useType==4" label="使用时间" align="center" prop="useTime" width="120">
            <template #default="scope">
              <span>{{ parseTime(scope.row.usetime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="生产厂家" prop="manufacturer" show-overflow-tooltip />
          <el-table-column label="生产批号" prop="batchNumber" width="120" />
        </el-table>
      </el-card>

      <template #footer>
        <el-button @click="cancel">关 闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Usage">
import { listMedicine} from "@/api/biosafety/medicine"
import { listUsageInfo, getUsageInfo } from '@/api/biosafety/usageInfo'
import { listUnit } from '@/api/biosafety/unit'
import { listUsage } from '@/api/biosafety/usage'
import { getCurrentInstance, reactive, ref, toRefs } from 'vue'

const { proxy } = getCurrentInstance()
const { pres_type } = proxy.useDict('pres_type')

const usageList = ref([])
const swMedicineUsageDetailsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const total = ref(0)
const title = ref('')
const daterangeCreateTime = ref([])
const daterangeUseTime = ref([]) // 新增

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    name: null,
    useType: null,
    createTime: null
  },
  rules: {}
})
const { queryParams, form, rules } = toRefs(data)

const units = ref([])
const usages = ref([])
const medicines = ref([])

/* 获取单位 */
function getUnit() {
  listUnit().then(res => {
    units.value = res.rows.map(item => ({ value: item.id, label: item.name }))
  })
}
/* 获取药品信息 */
function getMedicineOptions() {
  listMedicine().then(res => {
    medicines.value = res.rows.map(item => ({ value: item.id, label: item.name }))
  })
}

/* 获取使用方法 */
function getUsageOptions() {
  listUsage().then(res => {
    usages.value = res.rows.map(item => ({ value: item.id, label: item.name }))
  })
}
/* 格式化单位 */
function formatUnit(row) {
  const unit = units.value.find(u => String(u.value) === String(row.unit))
  return unit?.label ?? ''
}
/* 格式化使用方法 */
function formatUsage(row) {
  const usage = usages.value.find(u => String(u.value) === String(row.usageId))
  return usage?.label ?? ''
}

/* 查询列表 */
function getList() {
  loading.value = true
  queryParams.value.params = {}

  if (daterangeCreateTime.value && daterangeCreateTime.value.length === 2) {
    queryParams.value.params.beginCreateTime = daterangeCreateTime.value[0]
    queryParams.value.params.endCreateTime = daterangeCreateTime.value[1]
  }
  if (daterangeUseTime.value && daterangeUseTime.value.length === 2) {
    queryParams.value.params.beginUseTime = daterangeUseTime.value[0]
    queryParams.value.params.endUseTime = daterangeUseTime.value[1]
  }

  listUsageInfo(queryParams.value).then(res => {
    usageList.value = res.rows
    total.value = res.total
    loading.value = false
  })
}

function reset() {
  form.value = {
    id: null,
    name: null,
    useType: null,
    createBy: null,
    createTime: null
  }
  swMedicineUsageDetailsList.value = []
}
function cancel() {
  open.value = false
  reset()
}
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}
function resetQuery() {
  daterangeCreateTime.value = []
  daterangeUseTime.value = [] // 新增
  proxy.resetForm('queryRef')
  handleQuery()
}

function handleDetail(row) {
  reset()
  getUsageInfo(row.id).then(res => {
    form.value = res.data
    swMedicineUsageDetailsList.value = res.data.swMedicineUsageDetailsList || []
    open.value = true
    title.value = '药品使用记录详情'
  })
}
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
}
function rowSwMedicineUsageDetailsIndex({ rowIndex }) {
  return `row-${rowIndex}`
}
function handleExport() {
  proxy.download(
    'biosafety/usageInfo/export',
    { ...queryParams.value },
    `药品使用记录_${new Date().getTime()}.xlsx`
  )
}

/* 初始化 */
getList()
getUnit()
getMedicineOptions()
getUsageOptions()
</script>

<style scoped>
.usage-detail-dialog .detail-card {
  border-radius: 6px;
  margin: 0;
}
.usage-detail-dialog .card-header {
  display: flex;
  align-items: center;
  font-weight: 600;
  color: #303133;
}
.usage-detail-dialog .card-header .el-icon {
  margin-right: 6px;
}
</style>