<template>
  <div class="add-treatment">
    <el-container style="height:100vh;display:flex;flex-direction:column;">
      <el-main style="padding:0;flex:1;display:flex;flex-direction:column;">
        <div class="content-wrapper">
          <h2 class="page-title">添加治疗记录</h2>

          <div class="treatment-container">
            <!-- 羊只信息只读展示 -->
            <div class="sheep-info-section">
              <el-row :gutter="20">
                <el-col :span="8">
                  <div class="info-item">
                    <strong>耳号：</strong>{{ sheepInfo.sheepNo || '–' }}
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="info-item">
                    <strong>性别：</strong>{{ sheepInfo.gender || '–' }}
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="info-item">
                    <strong>品种：</strong>{{ sheepInfo.variety || '–' }}
                  </div>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="8">
                  <div class="info-item">
                    <strong>羊只类别：</strong>{{ sheepInfo.name || '–' }}
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="info-item">
                    <strong>月龄：</strong>{{ sheepInfo.monthAge ?? '–' }} &nbsp;月
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="info-item">
                    <strong>胎次：</strong>{{ sheepInfo.parity ?? '–' }}
                  </div>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="8">
                  <div class="info-item">
                    <strong>繁殖状态：</strong>{{ sheepInfo.breed || '–' }}
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="info-item">
                    <strong>怀孕天数：</strong>{{ sheepInfo.gestationDay ?? '–' }} &nbsp;天
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="info-item">
                    <strong>泌乳天数：</strong>{{ sheepInfo.lactationDay ?? '–' }} &nbsp;天
                  </div>
                </el-col>
              </el-row>
            </div>

            <el-form ref="treatmentRef" :model="form" :rules="rules" label-width="140px" status-icon size="large"
              class="treatment-form">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="事件日期" prop="eventDate">
                    <el-date-picker v-model="form.eventDate" type="date" placeholder="选择日期" style="width:100%" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="处方" prop="prescription">
                    <el-select v-model="selectedPresId" placeholder="请选择处方" style="width:100%" filterable clearable
                      @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="form.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 :disabled="!form.diseasePid" v-model="form.diseaseId" 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="medication-actions mb20">
                <el-button type="primary" icon="Plus" @click="handleAddSwPresDetail">
                  添加药品
                </el-button>
              </div>

              <div style="margin-bottom:30px;">
                <el-table :data="swPresDetailList" border stripe style="width:100%;">
                  <el-table-column label="序号" align="center" width="80">
                    <template #default="scope">{{ scope.$index + 1 }}</template>
                  </el-table-column>

                  <el-table-column label="药品" prop="mediId">
                    <template #default="scope">
                      <el-select v-model="scope.row.mediId" filterable placeholder="请选择药品" style="width:100%">
                        <el-option v-for="item in medicines" :key="item.value" :label="item.label"
                          :value="item.value" />
                      </el-select>
                    </template>
                  </el-table-column>

                  <el-table-column label="用量" prop="dosage">
                    <template #default="scope">
                      <el-input-number v-model="scope.row.dosage" :min="0" :precision="1" placeholder="请输入用量"
                        controls-position="right" style="width:100%" />
                    </template>
                  </el-table-column>

                  <el-table-column label="单位" prop="unit">
                    <template #default="scope">
                      <el-select v-model="scope.row.unitId" placeholder="请选择单位">
                        <el-option v-for="item in units" :key="item.value" :label="item.label" :value="item.value" />
                      </el-select>
                    </template>
                  </el-table-column>

                  <el-table-column label="使用方法" prop="usageId">
                    <template #default="scope">
                      <el-select v-model="scope.row.usageId" placeholder="请选择使用方法" style="width:100%">
                        <el-option v-for="item in usages" :key="item.value" :label="item.label" :value="item.value" />
                      </el-select>
                    </template>
                  </el-table-column>

                  <el-table-column label="生产厂家" prop="manufacturer">
                    <template #default="scope">
                      <el-input v-model="scope.row.manufacturer" placeholder="请输入生产厂家" style="width:100%" />
                    </template>
                  </el-table-column>
                  <el-table-column label="生产批号" prop="batchNumber">
                    <template #default="scope">
                      <el-input v-model="scope.row.batchNumber" placeholder="生产批号" style="width:100%" />
                    </template>
                  </el-table-column>

                  <el-table-column label="操作" align="center" width="100">
                    <template #default="scope">
                      <el-button link type="danger" icon="Delete" @click="deletePresDetail(scope.row)">
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="兽医">
                    <el-input v-model="form.veterinarian" placeholder="请输入兽医姓名" />
                  </el-form-item>
                </el-col>
              </el-row>

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

              <div class="form-footer">
                <el-button @click="goBack">取消</el-button>
                <el-button type="primary" @click="submitForm">
                  确定
                </el-button>
              </div>
            </el-form>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import useTagsViewStore from "@/store/modules/tagsView.js"
import request from '@/utils/request';
import { listDisease } from "@/api/biosafety/disease"
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 { addTreatment } from '@/api/biosafety/treatment' // 新增治疗记录API
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'

const { proxy } = getCurrentInstance()

const route = useRoute()
const router = useRouter()
const { qId, sId } = route.query;

const sheepInfo = ref({
  sheepNo: null,
  gender: '',
  variety: '',
  name: '',
  monthAge: null,
  parity: null,
  breed: '',
  lactationDay: null,
  gestationDay: null
})

const units = ref([])   // 单位下拉选项
const usages = ref([]) // 使用方法下拉选项
const medicines = ref([]) // 药品下拉选项

function getMedicines() {
  listMedicine().then(response => {
    medicines.value = response.rows.map(item => ({
      value: item.id,
      label: item.name
    }))
  })
}

function getUnit() {
  listUnit().then(response => {
    units.value = response.rows.map(item => ({
      value: item.id,
      label: item.name
    }))
  })
}

function getUsageOptions() {
  listUsage().then(response => {
    usages.value = response.rows.map(item => ({
      value: item.id,
      label: item.name
    }))
  })
}

function getSheepInfo() {
  if (!sId) return
  request.get(`/sheep_file/sheep_file/${sId}`).then(response => {
    const data = response.data
    sheepInfo.value = {
      sheepNo: data.bsManageTags,
      gender: data.gender,
      variety: data.variety,
      name: data.name,
      monthAge: data.monthAge,
      parity: data.parity,
      breed: data.breed,
      lactationDay: data.lactationDay,
      gestationDay: data.gestationDay,
    }
  })
}

const selectedPresId = ref(null)
const presOptions = ref([])

function getPrescriptions() {
  const queryParams = {
    status: 1, // 只获取有效的处方
    persType: 4 // 只获取疾病治疗的处方
  }
  listPrescription(queryParams).then(response => {
    presOptions.value = response.rows.map(item => ({
      id: item.id,
      label: item.name
    }))
  })
}

function handleSelectPrescription(id) {
  if (!id) return
  getPrescription(id).then(response => {
    const data = response.data
    swPresDetailList.value = data.swPresDetailList.map(item => ({
      mediId: item.mediId,
      dosage: item.dosage,
      unitId: item.unitId,
      usageId: item.usageId,
    }))
  })
}

/* 疾病相关 */
const parentDiseaseOptions = ref([]) // 疾病父类选项
const childDiseaseOptions = ref([]) // 疾病子类选项

function getDiseases() {
  listDisease().then(response => {
    const diseases = proxy.handleTree(response.data, "id", "pid")
    // 提取父类疾病（pid为0）
    parentDiseaseOptions.value = diseases.filter(item => item.pid === 0)
  })
}

function handleDiseaseTypeChange(parentId) {
  if (!parentId) {
    childDiseaseOptions.value = []
    form.diseaseSubtype = null
    return
  }

  // 查找对应父类下的子类疾病
  listDisease({ pid: parentId }).then(response => {
    childDiseaseOptions.value = response.data
    form.diseaseSubtype = null
  })
}

const form = reactive({
  eventType: '诊疗',
  eventDate: new Date(), // 默认今天
  diseaseParentId: null, // 疾病大类
  diseaseSubtype: null,  // 疾病子类型
  veterinarian: '',
  comment: '',
  sheepId: sId // 羊只ID
})

const rules = {
  diseasePid: { required: true, message: '疾病大类不能为空', trigger: 'change' },
  diseaseId: { required: true, message: '疾病子类型不能为空', trigger: 'change' }
}

const swPresDetailList = ref([
  { mediId: null, dosage: 0, unitId: null, usageId: null, manufacturer: '', batchNumber: '' }
])

const handleAddSwPresDetail = () => {
  swPresDetailList.value.push({ mediId: null, dosage: 0, unitId: null, usageId: null, manufacturer: '', batchNumber: '' })
}

const deletePresDetail = (row) => {
  const index = swPresDetailList.value.indexOf(row)
  if (index !== -1) swPresDetailList.value.splice(index, 1)
}

function submitForm() {
  // 表单验证
  if (!form.diseasePid || !form.diseaseId) {
    ElMessage.error("请完整填写疾病信息！");
    return;
  }

  if (swPresDetailList.value.length === 0 || swPresDetailList.value.some(item => !item.mediId)) {
    ElMessage.error("请至少添加一个药品！");
    return;
  }

  // 整合提交数据
  const submitData = {
    ...sheepInfo.value,
    ...form,
    eventDate: form.eventDate ? new Date(form.eventDate).getTime() : null,
    usageDetails: swPresDetailList.value.map(item => ({
      mediId: item.mediId,
      dosage: item.dosage,
      unit: item.unitId,
      usageId: item.usageId,
      manufacturer: item.manufacturer,
      batchNumber: item.batchNumber
    }))
  };

  // 提交请求
  addTreatment(submitData).then(response => {
    if (response.code === 200) {
      ElMessage.success(response.message || "治疗记录添加成功！");
      goBack();
    } else {
      ElMessage.error(response.message || "添加治疗记录失败！");
    }
  }).catch(error => {
    ElMessage.error("请求失败：" + (error.message || "未知错误"));
    console.error("提交表单时出错:", error);
  });
}

// 关闭页面并跳转到对应的页面
const useTagsStore = useTagsViewStore()
const currentTag = router.currentRoute.value;
const goBack = () => {
  router.go(-1);
  useTagsStore.delVisitedView(currentTag);
};

// 初始化数据
getUnit()  // 获取单位下拉数据源
getUsageOptions() // 获取使用方法下拉数据源
getMedicines() // 获取药品下拉数据源
getSheepInfo() // 获取羊只信息
getPrescriptions() // 获取处方下拉数据源
getDiseases() // 获取疾病数据
</script>

<style scoped>
/* ===== 全屏极简样式 ===== */
html,
body,
#app {
  height: 100%;
  margin: 0;
  padding: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

.add-treatment {
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.el-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.content-wrapper {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.page-title {
  margin: 0 0 24px;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  text-align: center;
}

/* 羊只信息部分 */
.treatment-container {
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
}

.sheep-info-section {
  margin-bottom: 32px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.info-item strong {
  color: #606266;
  font-weight: 500;
  margin-right: 8px;
  width: 100px;
}

.info-item span {
  color: #303133;
  flex: 1;
}

/* 表单样式 */
.treatment-form {
  margin: 0 auto;
  padding: 0 20px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.el-form-item {
  margin-bottom: 24px;
}

.el-input,
.el-textarea,
.el-select {
  width: 100%;
}

/* 按钮样式 */
.form-footer {
  margin-top: 40px;
  text-align: center;
}

.form-footer .el-button {
  padding: 12px 40px;
  font-size: 16px;
  border-radius: 6px;
}

/* 表格样式 */
.el-table {
  border-radius: 8px;
  overflow: hidden;
  margin-top: 16px;
}

/* 分隔线样式 */
.el-divider {
  margin: 32px 0 24px;
}

.el-divider__text {
  background: transparent;
  color: #606266;
  font-size: 16px;
  font-weight: 500;
}

/* 药品添加按钮 */
.medication-actions {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .el-col {
    margin-bottom: 16px;
  }

  .el-row {
    margin-bottom: 16px;
  }

  .info-item {
    flex-direction: column;
    align-items: flex-start;
    margin-bottom: 12px;
  }

  .info-item strong {
    margin-bottom: 6px;
  }
}
</style>