<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="治疗日期" style="width: 308px">
        <el-date-picker v-model="daterangeDatetime" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item label="羊只耳号" prop="sheepNo">
        <el-input v-model="queryParams.sheepNo" placeholder="请输入羊只耳号" clearable />
      </el-form-item>
      <el-form-item label="治疗状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择治疗状态" style="width: 120px;">
          <el-option v-for="u in treat_status" :key="u.value" :label="u.label" :value="u.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="兽医" prop="veterinary">
        <el-input v-model="queryParams.veterinary" placeholder="请输入兽医" clearable />
      </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">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改</el-button>
      </el-col>
      <!-- 按钮区域新增“诊疗” -->
      <el-col :span="1.5">
        <el-button type="info" plain icon="DocumentAdd" @click="handleAddDiagnosis" :disabled="multiple">诊疗</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="treatmentList" @selection-change="handleSelectionChange"
      @sort-change="handleSortChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="羊只耳号" align="center" prop="sheepNo" />
      <el-table-column label="品种" align="center" prop="variety" />
      <el-table-column label="羊只类别" align="center" prop="sheepType" />
      <el-table-column label="月龄" align="center" prop="monthAge" sortable="custom" />
      <el-table-column label="羊只性别" align="center" prop="gender">
        <template #default="scope"><dict-tag :options="sheep_gender" :value="scope.row.gender" /></template>
      </el-table-column>
      <el-table-column label="胎次" align="center" prop="parity" sortable="custom" />
      <el-table-column label="繁殖状态" align="center" prop="breed" />
      <el-table-column label="泌乳天数" align="center" prop="lactDay" sortable="custom" width="120px" />
      <el-table-column label="怀孕天数" align="center" prop="gestDay" sortable="custom" width="120px" />
      <el-table-column label="疾病类型" align="center" prop="diseaseName" />
      <el-table-column label="治疗状态" align="center" prop="treatmentPlan">
        <template #default="scope"><dict-tag :options="treat_status" :value="scope.row.status" /></template>
      </el-table-column>
      <el-table-column label="兽医" align="center" prop="veterinary" />
      <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="comment" />
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" @click="gotDiag(scope.row)"
            v-if="scope.row.status == 0 || scope.row.status == 1">诊断</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(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" :page-sizes="[20, 50, 100, 200, 500, 1000, 2000]" @pagination="getList" />

    <!-- 新增弹窗 -->
    <el-dialog title="添加治疗记录" v-model="addDialog" width="70%" top="5vh" append-to-body destroy-on-close>
      <el-form ref="addFormRef" :model="addForm" :rules="rules" label-width="80px" size="large">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="羊只耳号" required>
              <el-input v-model="sheepInput" placeholder="输入耳号后按回车验证" style="width: 300px"
                @keyup.enter="validateSheep" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <div style="margin-bottom: 10px;margin-left: 60px;">
              <el-tag v-for="(item, index) in selectedSheepList" :key="item.sheepNo" closable
                @close="removeSheep(index)" style="margin-right: 10px">
                {{ item.sheepNo }}（{{ item.barnName }}）
              </el-tag>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="事件日期" prop="datetime">
              <el-date-picker v-model="addForm.datetime" type="date" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处方">
              <el-select v-model="selectedPresId" filterable clearable placeholder="请选择处方" style="width: 100%"
                @change="handleSelectPrescription">
                <el-option v-for="item in presOptions" :key="item.id" :label="item.label" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="疾病大类" prop="diseasePid">
              <el-select v-model="addForm.diseasePid" placeholder="请选择" style="width: 100%"
                @change="handleDiseaseTypeChange">
                <el-option v-for="item in parentDiseaseOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="疾病子类型" prop="diseaseId">
              <el-select v-model="addForm.diseaseId" :disabled="!addForm.diseasePid" placeholder="请选择"
                style="width: 100%">
                <el-option v-for="item in childDiseaseOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">治疗记录</el-divider>
        <div class="mb20">
          <el-button type="primary" icon="Plus" @click="handleAddSwPresDetail">添加药品</el-button>
        </div>

        <el-table :data="swPresDetailList" border stripe>
          <el-table-column label="序号" width="60">
            <template #default="scope">{{ scope.$index + 1 }}</template>
          </el-table-column>
          <el-table-column label="药品" width="160px">
            <template #default="scope">
              <el-select v-model="scope.row.mediId" filterable placeholder="请选择药品">
                <el-option v-for="m in medicines" :key="m.value" :label="m.label" :value="m.value" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="用量" width="160px">
            <template #default="scope">
              <el-input-number v-model="scope.row.dosage" :min="0" :precision="1" style="width: 120px;" />
            </template>
          </el-table-column>
          <el-table-column label="单位">
            <template #default="scope">
              <el-select v-model="scope.row.unit" placeholder="单位">
                <el-option v-for="u in units" :key="u.value" :label="u.label" :value="u.value" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="使用方法">
            <template #default="scope">
              <el-select v-model="scope.row.usageId" placeholder="用法">
                <el-option v-for="u in usages" :key="u.value" :label="u.label" :value="u.value" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="使用时间" width="160px">
            <template #default="scope">
              <el-date-picker v-model="scope.row.usetime" type="date" placeholder="选择日期" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" style="width:100%;" />
            </template>
          </el-table-column>
          <el-table-column label="生产厂家" width="160px">
            <template #default="scope">
              <el-input v-model="scope.row.manufacturer" placeholder="生产厂家" />
            </template>
          </el-table-column>
          <el-table-column label="生产批号" width="160px">
            <template #default="scope">
              <el-input v-model="scope.row.batchNumber" placeholder="批号" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="60">
            <template #default="scope">
              <el-button link type="danger" icon="Delete" @click="deletePresDetail(scope.row)" />
            </template>
          </el-table-column>
        </el-table>

        <el-row :gutter="20" style="margin-top:20px;">
          <el-col :span="12">
            <el-form-item label="兽医">
              <el-input v-model="addForm.veterinarian" placeholder="请输入兽医姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="治疗状态">
              <el-select v-model="addForm.status" placeholder="请选择治疗状态">
                <el-option v-for="u in treat_status" :key="u.value" :label="u.label" :value="u.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注">
          <el-input type="textarea" :rows="3" v-model="addForm.comment" placeholder="请输入备注" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialog = false">取 消</el-button>
          <el-button type="primary" @click="submitAddForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改弹窗 -->
    <el-dialog title="修改治疗记录" v-model="editDialog" width="70%" top="5vh" append-to-body destroy-on-close>
      <el-form ref="editFormRef" :model="editForm" :rules="rules" label-width="80px" size="large">
        <!-- 羊只基本信息展示（只读） -->
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="羊只耳号:">
              <el-text>{{ editForm.sheepNo }}</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="羊只性别:">
              <el-text>{{ editForm.gender }}</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="品种:">
              <el-text>{{ editForm.variety }}</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="羊只类别:">
              <el-text>{{ editForm.sheepType }}</el-text>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="月龄">
              <el-text>{{ editForm.monthAge }}</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="胎次">
              <el-text>{{ editForm.parity }}</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="繁殖状态">
              <el-text>{{ editForm.breed }}</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="泌乳天数">
              <el-text>{{ editForm.lactDay }}天</el-text>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="怀孕天数">
              <el-text>{{ editForm.gestDay }}天</el-text>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 可编辑内容 -->
        <el-divider content-position="left">治疗记录</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="治疗日期" prop="datetime">
              <el-date-picker v-model="editForm.datetime" type="date" style="width: 100%" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="处方">
              <el-select v-model="selectedPresId" filterable clearable placeholder="请选择处方" style="width: 100%"
                @change="handleSelectPrescription">
                <el-option v-for="item in presOptions" :key="item.id" :label="item.label" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col> -->
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="疾病大类" prop="diseasePid">
              <el-select v-model="editForm.diseasePid" placeholder="请选择" style="width: 100%"
                @change="handleDiseaseTypeChange">
                <el-option v-for="item in parentDiseaseOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="疾病子类型" prop="diseaseId">
              <el-select v-model="editForm.diseaseId" :disabled="!editForm.diseasePid" placeholder="请选择"
                style="width: 100%">
                <el-option v-for="item in childDiseaseOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="mb20">
          <el-button type="primary" icon="Plus" @click="handleAddSwPresDetail">添加药品</el-button>
        </div>

        <el-table :data="swPresDetailList" border stripe>
          <el-table-column label="序号" width="60">
            <template #default="scope">{{ scope.$index + 1 }}</template>
          </el-table-column>
          <el-table-column label="药品">
            <template #default="scope">
              <el-select v-model="scope.row.mediId" filterable placeholder="请选择药品">
                <el-option v-for="m in medicines" :key="m.value" :label="m.label" :value="m.value" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="用量" width="160">
            <template #default="scope">
              <el-input-number v-model="scope.row.dosage" :min="0" :precision="1" style="width: 120px;" />
            </template>
          </el-table-column>
          <el-table-column label="单位">
            <template #default="scope">
              <el-select v-model="scope.row.unit" placeholder="单位">
                <el-option v-for="u in units" :key="u.value" :label="u.label" :value="u.value + ''" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="使用方法">
            <template #default="scope">
              <el-select v-model="scope.row.usageId" placeholder="用法">
                <el-option v-for="u in usages" :key="u.value" :label="u.label" :value="u.value + ''" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="使用时间" width="160px">
            <template #default="scope">
              <el-date-picker v-model="scope.row.usetime" type="date" placeholder="选择日期" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" style="width: 100%;" />
            </template>
          </el-table-column>
          <el-table-column label="生产厂家" width="160px">
            <template #default="scope">
              <el-input v-model="scope.row.manufacturer" placeholder="生产厂家" />
            </template>
          </el-table-column>
          <el-table-column label="生产批号" width="160px">
            <template #default="scope">
              <el-input v-model="scope.row.batchNumber" placeholder="批号" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="60">
            <template #default="scope">
              <el-button link type="danger" icon="Delete" @click="deletePresDetail(scope.row)" />
            </template>
          </el-table-column>
        </el-table>

        <el-row :gutter="20" style="margin-top:20px;">
          <el-col :span="12">
            <el-form-item label="兽医">
              <el-input v-model="editForm.veterinarian" placeholder="请输入兽医姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="治疗状态">
              <el-select v-model="editForm.status" placeholder="请选择治疗状态">
                <el-option v-for="u in treat_status" :key="u.value" :label="u.label" :value="u.value + ''" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注">
          <el-input type="textarea" :rows="3" v-model="editForm.comment" placeholder="请输入备注" />
        </el-form-item>
      </el-form>


      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialog = false">取 消</el-button>
          <el-button type="primary" @click="submitEditForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 新增诊疗弹窗 -->
    <el-dialog title="新增诊疗记录" v-model="diagnosisDialog" width="50%" append-to-body destroy-on-close>
      <el-form label-width="120px">
        <el-form-item label="选中羊只">
          <el-tag v-for="no in selectedSheepNos" :key="no" style="margin-right: 5px">{{ no }}</el-tag>
        </el-form-item>
        <el-form-item label="治疗日期" prop="datetime">
          <el-date-picker v-model="addDia.datetime" type="date" style="width: 100%" />
        </el-form-item>
        <el-form-item label="诊疗结果" prop="result">
          <el-select v-model="addDia.result" placeholder="请选择治疗结果" style="width: 100%;">
            <el-option v-for="item in diag_result" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="转入羊舍" prop="sheepfoldId">
          <el-select v-model="addDia.sheepfoldId" filterable placeholder="请选择转入羊舍" style="width: 100%;">
            <el-option v-for="item in sheepfolds" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="diagnosisDialog = false">取消</el-button>
        <el-button type="primary" @click="submitDiagnosis">确认</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { listTreatment, getTreatment, delTreatment, addTreatment, updateTreatment } from '@/api/biosafety/treatment'
import { listDisease } from '@/api/biosafety/disease'
import { listSheepfold_management } from "@/api/fileManagement/sheepfold_management"
import { listPrescription, getPrescription } from '@/api/biosafety/prescription'
import { listUnit } from '@/api/biosafety/unit'
import { listUsage } from '@/api/biosafety/usage'
import { listMedicine } from '@/api/biosafety/medicine'
import request from '@/utils/request'
import { useRouter } from 'vue-router'

const router = useRouter()

const { proxy } = getCurrentInstance()
const { sheep_gender, diag_result, treat_status } = proxy.useDict("sheep_gender", "diag_result", "treat_status")


/* ---------- 列表区域 ---------- */
const treatmentList = ref([])
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const daterangeDatetime = ref([])
const sheepfolds = ref([])

const queryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  sheepNo: null,
  veterinary: null,
  orderByColumn: null,   // 新增
  isAsc: null
})

/* ---------- 弹窗控制 ---------- */
const addDialog = ref(false)
const editDialog = ref(false)

/* ---------- 表单与数据 ---------- */
const sheepInput = ref('')
const selectedSheepList = ref([])

const selectedPresId = ref()
const presOptions = ref([])
const parentDiseaseOptions = ref([])
const childDiseaseOptions = ref([])
const units = ref([])
const usages = ref([])
const medicines = ref([])

const addForm = reactive({
  id: null,
  eventType: '诊疗',
  datetime: new Date(),
  diseasePid: null,
  diseaseId: null,
  veterinarian: '',
  stats: '',
  comment: ''
})

const editForm = reactive({
  id: null,
  eventType: '诊疗',
  datetime: new Date(),
  diseasePid: null,
  diseaseId: null,
  veterinarian: '',
  comment: '',
  sheepNo: '',
  barnName: '',
  variety: '',
  sheepType: '',
  monthAge: '',
  gender: '',
  status: '',
  parity: '',
  breed: '',
  lactDay: '',
  gestDay: ''
})

const rules = {
  datetime: [{ required: true, message: '请选择日期', trigger: 'change' }],
  diseasePid: [{ required: true, message: '请选择疾病大类', trigger: 'change' }],
  diseaseId: [{ required: true, message: '请选择疾病子类型', trigger: 'change' }]
}

const swPresDetailList = ref([
  { mediId: null, dosage: 0, unit: null, usageId: null, usetime: new Date().toISOString().slice(0, 10), manufacturer: '', batchNumber: '' }
])

/* ---------- 新增诊疗 ---------- */
const diagnosisDialog = ref(false)
const selectedSheepNos = ref([])
const addDia = reactive({
  sheepfoldId: null,
  result: null,
  datetime: new Date().toISOString().slice(0, 10)
})


function handleAddDiagnosis() {
  if (!ids.value.length) {
    proxy.$modal.msgWarning('请至少选择一条治疗记录')
    return
  }
  selectedSheepNos.value = treatmentList.value
    .filter(item => ids.value.includes(item.id))
    .map(item => item.sheepNo)
  diagnosisDialog.value = true
}

function submitDiagnosis() {
  const data = {
    treatIds: ids.value,
    result: addDia.result,
    datetime: addDia.datetime,
    sheepfoldId: addDia.sheepfoldId
  }
  request.post('/diagnosis/diagnosis/adds', data).then(() => {
    proxy.$modal.msgSuccess('诊疗成功')
    diagnosisDialog.value = false
    getList()
  })
}

/* ---------- 列表查询 ---------- */
function getList() {
  loading.value = true
  const qp = { ...queryParams }
  qp.params = {}
  if (daterangeDatetime.value && daterangeDatetime.value.length) {
    qp.params.beginDatetime = daterangeDatetime.value[0]
    qp.params.endDatetime = daterangeDatetime.value[1]
  }
  listTreatment(qp).then(res => {
    treatmentList.value = res.rows
    total.value = res.total
    loading.value = false
  })
}

/* ---------- 疾病联动 ---------- */
function handleDiseaseTypeChange(pid) {
  if (!pid) {
    childDiseaseOptions.value = []
    addForm.diseaseId = null
    editForm.diseaseId = null
    return
  }
  listDisease({ pid }).then(res => (childDiseaseOptions.value = res.data))
}

/* ---------- 处方联动 ---------- */
function handleSelectPrescription(id) {
  if (!id) return
  getPrescription(id).then(res => {
    swPresDetailList.value = res.data.swPresDetailList?.map(i => ({
      mediId: i.mediId,
      dosage: i.dosage,
      unit: i.unitId,
      usageId: i.usageId,
      manufacturer: '',
      batchNumber: ''
    })) || []
  })
}

/* ---------- 药品明细 ---------- */
function handleAddSwPresDetail() {
  swPresDetailList.value.push({
    mediId: null,
    dosage: 0,
    unit: null,
    usageId: null,
    usetime: new Date().toISOString().slice(0, 10),
    manufacturer: '',
    batchNumber: ''
  })
}
function deletePresDetail(row) {
  swPresDetailList.value.splice(swPresDetailList.value.indexOf(row), 1)
}

/* ---------- 羊只验证 ---------- */
function validateSheep() {
  const no = sheepInput.value.trim()
  if (!no) return
  request.get(`/sheep_file/sheep_file/byNo/${no}`).then(res => {
    if (!res.data) {
      proxy.$modal.msgError('羊只耳号不存在'); return
    }
    if (selectedSheepList.value.some(s => s.sheepNo === no)) {
      proxy.$modal.msgWarning('该羊只已添加'); return
    }
    selectedSheepList.value.push({
      sheepNo: res.data.bsManageTags,
      sheepId: res.data.id,
      barnName: res.data.sheepfoldName
    })
    sheepInput.value = ''
  })
}
function removeSheep(index) {
  selectedSheepList.value.splice(index, 1)
}

/* ---------- 新增 ---------- */
function handleAdd() {
  resetForm(addForm)
  addDialog.value = true
}
function submitAddForm() {
  proxy.$refs.addFormRef.validate(valid => {
    if (!valid) return
    if (!selectedSheepList.value.length) {
      proxy.$modal.msgError('请至少添加一只羊'); return
    }
    const data = {
      ...addForm,
      datetime: addForm.datetime ? new Date(addForm.datetime).getTime() : null,
      usageDetails: swPresDetailList.value,
      sheepIds: selectedSheepList.value.map(s => s.sheepId)
    }
    addTreatment(data).then(() => {
      proxy.$modal.msgSuccess('新增成功')
      addDialog.value = false
      getList()
    })
  })
}

/* ---------- 修改 ---------- */
function handleUpdate(row) {
  resetForm(editForm)
  getTreatment(row.id).then(res => {
    Object.assign(editForm, {
      id: res.data.id,
      datetime: res.data.datetime ? new Date(res.data.datetime) : new Date(),
      diseasePid: res.data.diseasePid,
      diseaseId: res.data.diseaseId,
      usageId: res.data.usageId,
      veterinarian: res.data.veterinarian,
      comment: res.data.comment,
      sheepNo: res.data.sheepNo,
      barnName: res.data.sheepfoldName,
      variety: res.data.variety,
      sheepType: res.data.sheepType,
      monthAge: res.data.monthAge,
      gender: res.data.gender,
      parity: res.data.parity,
      breed: res.data.breed,
      status: res.data.status,
      lactDay: res.data.lactDay,
      gestDay: res.data.gestDay
    })
    swPresDetailList.value = res.data.usageDetails || []
    selectedPresId.value = res.data.prescriptionId || null
    if (editForm.diseasePid) handleDiseaseTypeChange(editForm.diseasePid)
    editDialog.value = true
  })
}
function submitEditForm() {
  proxy.$refs.editFormRef.validate(valid => {
    if (!valid) return
    const data = {
      ...editForm,
      datetime: editForm.datetime ? new Date(editForm.datetime).getTime() : null,
      usageDetails: swPresDetailList.value
    }
    updateTreatment(data).then(() => {
      proxy.$modal.msgSuccess('修改成功')
      editDialog.value = false
      getList()
    })
  })
}

/* ---------- 通用 ---------- */
function resetQuery() {
  daterangeDatetime.value = []
  proxy.resetForm('queryRef')
  handleQuery()
}
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}
function handleDelete(row) {
  const id = row.id || ids.value
  proxy.$modal.confirm('是否确认删除治疗记录编号为"' + id + '"的数据项？')
    .then(() => delTreatment(id))
    .then(() => { getList(); proxy.$modal.msgSuccess('删除成功') })
}
function handleExport() {
  proxy.download('treatment/treatment/export', { ...queryParams }, `治疗记录_${Date.now()}.xlsx`)
}
function resetForm(formObj) {
  Object.assign(formObj, {
    id: null,
    datetime: new Date(),
    diseasePid: null,
    diseaseId: null,
    veterinarian: '',
    comment: '',
    sheepNo: '',
    barnName: '',
    variety: '',
    sheepType: '',
    monthAge: '',
    gender: '',
    parity: '',
    breed: '',
    lactDay: '',
    gestDay: ''
  })
  selectedPresId.value = null
  swPresDetailList.value = [{ mediId: null, dosage: 0, unit: null, usageId: null, manufacturer: '', batchNumber: '' }]
}
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

function handleSortChange({ prop, order }) {
  if (!order) {   // 取消排序
    queryParams.orderByColumn = null
    queryParams.isAsc = null
  } else {
    queryParams.orderByColumn = prop  
    queryParams.isAsc = order === 'ascending' ? 'asc' : 'desc'
  }
  getList()
}

/* 跳转诊疗 */
function gotDiag(row) {
  router.push({ path: '/biosafety/diagnosis/add', query: { tId: row.id, sId: row.sheepId } })
}


/* ---------- 初始化 ---------- */
onMounted(() => {
  getList()
  listDisease().then(res => {
    parentDiseaseOptions.value = res.data.filter(item => item.pid === 0)
  })
  listPrescription({ status: 1, persType: 4 }).then(res => {
    presOptions.value = res.rows.map(item => ({ id: item.id, label: item.name }))
  })
  listUnit().then(res => {
    units.value = res.rows.map(item => ({ value: item.id, label: item.name }))
  })
  listUsage().then(res => {
    usages.value = res.rows.map(item => ({ value: item.id, label: item.name }))
  })
  listMedicine().then(res => {
    medicines.value = res.rows.map(item => ({ value: item.id, label: item.name }))
  })
  listSheepfold_management().then(res => {
    sheepfolds.value = res.rows.map(item => ({ id: item.id, name: item.sheepfoldName }))
  })
})
</script>
