<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="体检日期" prop="examDate">
        <el-date-picker clearable
                        v-model="queryParams.examDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择体检日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @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="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['medical:report:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['medical:report:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['medical:report:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="reportList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="报告ID" align="center" prop="reportId" />
      <el-table-column label="用户" align="center" prop="userName" />
      <el-table-column label="销售" align="center" prop="companyUserName" />
      <el-table-column label="体检日期" align="center" prop="examDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.examDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="身高(cm)" align="center" prop="height" />
      <el-table-column label="体重(kg)" align="center" prop="weight" />
      <el-table-column label="BMI" align="center" prop="bmi" />
      <el-table-column label="血压" align="center" prop="bloodPressure" />
      <el-table-column label="心率" align="center" prop="heartRate" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['medical:report:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['medical:report:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改体检报告对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-tabs v-model="activeTab">
        <el-tab-pane label="身体信息" name="bodyInfo">
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="用户ID" prop="userId">
                  <el-input v-model="form.userId" placeholder="请输入用户ID" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="用户名" prop="userName">
                  <el-input v-model="form.userName" placeholder="请输入用户名" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="销售ID" prop="companyUserId">
                  <el-input v-model="form.companyUserId" placeholder="请输入销售ID" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="销售名称" prop="companyUserName">
                  <el-input v-model="form.companyUserName" placeholder="请输入销售名称" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="体检日期" prop="examDate">
                  <el-date-picker clearable
                                  v-model="form.examDate"
                                  type="date"
                                  value-format="yyyy-MM-dd"
                                  placeholder="请选择体检日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="身高(cm)" prop="height">
                  <el-input v-model="form.height" placeholder="请输入身高" @input="calculateBMI" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="体重(kg)" prop="weight">
                  <el-input v-model="form.weight" placeholder="请输入体重" @input="calculateBMI" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="BMI指数" prop="bmi">
                  <el-input v-model="form.bmi" placeholder="BMI自动计算" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="腰围(cm)" prop="waistCircumference">
                  <el-input v-model="form.waistCircumference" placeholder="请输入腰围" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="胸围(cm)" prop="chestCircumference">
                  <el-input v-model="form.chestCircumference" placeholder="请输入胸围" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="血压" prop="bloodPressure">
                  <el-input v-model="form.bloodPressure" placeholder="请输入血压" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="心率" prop="heartRate">
                  <el-input v-model="form.heartRate" placeholder="请输入心率" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="指标检查" name="indicators">
          <div class="indicator-toolbar" style="margin-bottom: 15px;">
            <el-input
              placeholder="搜索指标"
              v-model="indicatorSearch"
              style="width: 200px; margin-right: 10px;"
              class="filter-item"
              @keyup.enter.native="searchIndicators"
            >
              <el-button slot="append" icon="el-icon-search" @click="searchIndicators"></el-button>
            </el-input>
            <el-select
              v-model="indicatorCateId"
              placeholder="选择指标分类"
              clearable
              style="width: 180px; margin-right: 10px;"
              @change="handleIndicatorCateChange"
            >
              <el-option
                v-for="item in indicatorCateOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue">
              </el-option>
            </el-select>
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddIndicator">添加指标</el-button>
          </div>
          <el-table :data="indicatorList" style="width: 100%" v-loading="indicatorLoading">
            <el-table-column prop="indicatorName" label="指标名称" />
            <el-table-column prop="testValue" label="检测值" />
            <el-table-column prop="refRange" label="参考范围" />
            <el-table-column label="结果评价" align="center">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.isAbnormal === 0" type="success">正常</el-tag>
                <el-tag v-else-if="scope.row.abnormalType === '偏高'" type="danger">偏高</el-tag>
                <el-tag v-else-if="scope.row.abnormalType === '偏低'" type="warning">偏低</el-tag>
                <el-tag v-else-if="scope.row.isAbnormal === 1" type="danger">异常</el-tag>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="viewIndicatorDetail(scope.row)">查看详情</el-button>
                <el-button type="text" size="small" @click="editIndicator(scope.row)">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 指标检查分页 -->
          <pagination
            v-show="indicatorTotal > 0"
            :total="indicatorTotal"
            :page.sync="indicatorQueryParams.pageNum"
            :limit.sync="indicatorQueryParams.pageSize"
            @pagination="loadIndicators"
            style="margin-top: 15px;"
          />
        </el-tab-pane>
      </el-tabs>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 指标详情对话框 -->
    <el-dialog title="指标详情" :visible.sync="indicatorDetailVisible" width="600px" append-to-body>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="指标名称">{{ currentIndicator.indicatorName }}</el-descriptions-item>
        <el-descriptions-item label="检测值">{{ currentIndicator.testValue || '-' }}</el-descriptions-item>
        <el-descriptions-item label="参考范围">{{ currentIndicator.refRange }}</el-descriptions-item>
        <el-descriptions-item label="结果评价">
          <el-tag v-if="currentIndicator.isAbnormal === 0" type="success">正常</el-tag>
          <el-tag v-else-if="currentIndicator.abnormalType === '偏高'" type="danger">偏高</el-tag>
          <el-tag v-else-if="currentIndicator.abnormalType === '偏低'" type="warning">偏低</el-tag>
          <el-tag v-else-if="currentIndicator.isAbnormal === 1" type="danger">异常</el-tag>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="备注说明">{{ currentIndicator.remarks || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 添加指标对话框 -->
    <el-dialog title="添加指标" :visible.sync="indicatorSelectVisible" width="600px" append-to-body>
      <div class="search-container" style="margin-bottom: 15px;">
        <el-input
          placeholder="搜索指标库"
          v-model="indicatorLibrarySearch"
          style="width: 250px; margin-right: 10px;"
          @keyup.enter.native="searchIndicatorLibrary"
        >
          <el-button slot="append" icon="el-icon-search" @click="searchIndicatorLibrary"></el-button>
        </el-input>
        <el-select v-model="indicatorCategory" placeholder="选择分类" style="width: 150px;">
          <el-option
            v-for="item in indicatorCategoryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>

      <el-table
        :data="indicatorLibrary"
        style="width: 100%"
        height="350px"
        @selection-change="handleIndicatorSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="indicatorName" label="指标名称" />
        <el-table-column prop="indicatorCategory" label="分类" />
        <el-table-column label="参考范围" align="center">
          <template slot-scope="scope">
            {{ formatReferenceRange(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" />
      </el-table>

      <div style="margin-top: 15px;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalIndicators">
        </el-pagination>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addSelectedIndicators">添加所选指标</el-button>
        <el-button @click="indicatorSelectVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 编辑指标结果对话框 -->
    <el-dialog title="编辑指标结果" :visible.sync="indicatorResultDialogVisible" width="500px" append-to-body>
      <el-form ref="indicatorResultForm" :model="indicatorResultForm" :rules="indicatorResultRules" label-width="100px">
        <el-form-item label="指标名称">
          <span>{{ indicatorResultForm.indicatorName }}</span>
        </el-form-item>
        <el-form-item label="参考范围">
          <span>{{ indicatorResultForm.referenceRange }}</span>
        </el-form-item>
        <el-form-item label="检查数值" prop="testValue">
          <el-input v-model="indicatorResultForm.testValue" placeholder="请输入检查数值" />
        </el-form-item>
        <el-form-item label="检查结果" prop="testResult">
          <el-input v-model="indicatorResultForm.testResult" placeholder="请输入检查结果(文本)" />
        </el-form-item>
        <el-form-item label="是否异常">
          <el-radio-group v-model="indicatorResultForm.isAbnormal">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">异常</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="异常类型" v-if="indicatorResultForm.isAbnormal === 1" prop="abnormalType">
          <el-select v-model="indicatorResultForm.abnormalType" placeholder="请选择异常类型">
            <el-option label="偏高" value="偏高" />
            <el-option label="偏低" value="偏低" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注说明" prop="remarks">
          <el-input v-model="indicatorResultForm.remarks" type="textarea" rows="3" placeholder="请输入备注说明" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitIndicatorResult">确 定</el-button>
        <el-button @click="indicatorResultDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listReport, getReport, delReport, addReport, updateReport } from "@/api/medical/report";
import { parseTime } from "@/utils/common";
import { getDicts } from "@/api/system/dict/data";

export default {
  name: "Report",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 体检报告表格数据
      reportList: [],
      indicatorCateId: '', // 选中的指标分类ID
      indicatorCateOptions: [], // 指标分类选项列表
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 当前激活的tab页
      activeTab: 'bodyInfo',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        examDate: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
        examDate: [
          { required: true, message: "体检日期不能为空", trigger: "blur" }
        ]
      },
      // 指标搜索
      indicatorSearch: '',
      // 指标列表
      indicatorList: [],
      // 肝功能列表
      liverFunctionList: [],
      // 指标详情对话框可见性
      indicatorDetailVisible: false,
      // 当前查看的指标
      currentIndicator: {},
      // 指标选择对话框可见性
      indicatorSelectVisible: false,
      // 指标库搜索
      indicatorLibrarySearch: '',
      // 指标分类
      indicatorCategory: '',
      // 指标分类选项
      indicatorCategoryOptions: [
        { value: '', label: '全部' },
        { value: '肝脏', label: '肝脏' },
        { value: '血常规', label: '血常规' },
        { value: '尿常规', label: '尿常规' },
        { value: '心脏', label: '心脏' },
        { value: '肾功能', label: '肾功能' },
        { value: '血脂', label: '血脂' },
        { value: '其他', label: '其他' }
      ],
      // 指标库数据
      indicatorLibrary: [],
      // 选中的指标
      selectedIndicators: [],
      // 分页
      currentPage: 1,
      pageSize: 10,
      totalIndicators: 0,
      // 指标结果对话框可见性
      indicatorResultDialogVisible: false,
      // 指标结果表单
      indicatorResultForm: {
        resultId: null,
        indicatorName: '',
        referenceRange: '',
        testValue: '',
        testResult: '',
        isAbnormal: 0,
        abnormalType: '',
        remarks: ''
      },
      // 指标结果表单校验规则
      indicatorResultRules: {
        testValue: [
          { required: true, message: "检查数值不能为空", trigger: "blur" }
        ],
        testResult: [
          { required: true, message: "检查结果不能为空", trigger: "blur" }
        ],
        abnormalType: [
          { required: true, message: "异常类型不能为空", trigger: "blur" }
        ]
      },
             // 指标检查分页参数
       indicatorQueryParams: {
         pageNum: 1,
         pageSize: 10,
         reportId: null, // 报告ID
         indicatorName: '', // 指标名称
         indicatorCateId: '', // 指标分类ID
         isAbnormal: null // 是否异常
       },
      // 指标检查加载状态
      indicatorLoading: false,
      // 指标检查总条数
      indicatorTotal: 0
    };
  },
  created() {
    this.getList();
    this.loadIndicatorCateDict(); // 加载指标分类字典
  },
  methods: {
    /**
     * 加载指标分类字典数据
     */
    loadIndicatorCateDict() {
      getDicts('user_custom_type').then(response => {
        this.indicatorCateOptions = response.data || [];
        console.log('指标分类字典加载成功:', this.indicatorCateOptions);
      }).catch(error => {
        console.error("加载指标分类字典失败", error);
        this.$message.error("加载指标分类字典失败");
      });
    },
    parseTime,
    /** 查询体检报告列表 */
    getList() {
      this.loading = true;
      listReport(this.queryParams).then(response => {
        this.reportList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        reportId: null,
        userId: null,
        userName: null,
        companyUserId: null,
        companyUserName: null,
        examDate: null,
        height: null,
        weight: null,
        bmi: null,
        waistCircumference: null,
        chestCircumference: null,
        bloodPressure: null,
        heartRate: null,
        generalCondition: null,
        skinAndMucosa: null,
        lymphNodes: null,
        head: null,
        neck: null,
        chest: null,
        heart: null,
        lungs: null,
        abdomen: null,
        examResult: null,
        doctorAdvice: null
      };
      this.resetForm("form");
      // 重置指标列表
      this.indicatorList = [];
      this.liverFunctionList = [];
      // 重置当前tab
      this.activeTab = 'bodyInfo';
      // 重置指标查询参数
      this.indicatorQueryParams = {
        pageNum: 1,
        pageSize: 10,
        reportId: null,
        indicatorName: '',
        indicatorCateId: '',
        isAbnormal: null
      };
      this.indicatorSearch = '';
      this.indicatorCateId = '';
      this.indicatorTotal = 0;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 搜索指标
    searchIndicators() {
      if (!this.form.reportId) {
        return;
      }
      
      // 重置到第一页
      this.indicatorQueryParams.pageNum = 1;
      this.indicatorQueryParams.reportId = this.form.reportId;
      this.loadIndicators(this.form.reportId);
    },

    /**
     * 指标分类筛选变化处理
     */
    handleIndicatorCateChange(value) {
      this.indicatorCateId = value;
      this.searchIndicators();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.reportId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加体检报告";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const reportId = row.reportId || this.ids
      getReport(reportId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改体检报告";
        
        // 设置指标查询参数
        this.indicatorQueryParams.reportId = reportId;
        this.indicatorQueryParams.pageNum = 1;
        
        // 获取指标数据
        this.loadIndicators(reportId);
        // 获取肝功能数据
        this.loadLiverFunction(reportId);
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.reportId != null) {
            updateReport(this.form).then(response => {
              this.$message.success("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addReport(this.form).then(response => {
              this.$message.success("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const reportIds = row.reportId || this.ids;
      this.$confirm('是否确认删除体检报告编号为"' + reportIds + '"的数据项？').then(function() {
        return delReport(reportIds);
      }).then(() => {
        this.getList();
        this.$message.success("删除成功");
      }).catch(() => {});
    },

    // 自动计算BMI
    calculateBMI() {
      if (this.form.height && this.form.weight) {
        const height = parseFloat(this.form.height) / 100; // 转换为米
        const weight = parseFloat(this.form.weight);
        if (height > 0 && weight > 0) {
          this.form.bmi = (weight / (height * height)).toFixed(2);
        }
      }
    },

    // 加载指标数据
    loadIndicators(reportId) {
      this.indicatorLoading = true; // 开始加载
      
      // 如果有reportId参数，更新查询参数
      if (reportId) {
        this.indicatorQueryParams.reportId = reportId;
      }
      
      // 调用API从后端获取报告相关的指标检查结果
      return import('@/api/medical/reportIndicator').then(module => {
        const { listResult } = module;
        const query = {
          reportId: this.indicatorQueryParams.reportId,
          pageNum: this.indicatorQueryParams.pageNum,
          pageSize: this.indicatorQueryParams.pageSize,
          indicatorName: this.indicatorSearch || undefined,
          indicatorCateId: this.indicatorCateId || undefined,
          isAbnormal: this.indicatorQueryParams.isAbnormal || undefined
        };
        return listResult(query).then(response => {
          this.indicatorList = response.data.list;
          this.indicatorTotal = response.data.total;
          this.indicatorLoading = false; // 结束加载
          return this.indicatorList; // 返回过滤后的数据
        });
      }).catch(error => {
        console.error("加载指标数据失败", error);
        this.$message.error("加载指标数据失败");
        this.indicatorLoading = false; // 结束加载
        throw error; // 重新抛出错误
      });
    },

    // 加载肝功能数据
    loadLiverFunction(reportId) {
      // 调用API从后端获取报告相关的肝功能检查结果
      return import('@/api/medical/reportIndicator').then(module => {
        const { listResult } = module;
        const query = {
          reportId: reportId,
          pageNum: 1,
          pageSize: 1000 // 获取足够多的数据
        };
        return listResult(query).then(response => {
          // 过滤出肝功能相关的指标
          this.liverFunctionList = response.data.list.filter(item => item.category === '肝脏' || item.indicatorCategory === '肝脏');
          return this.liverFunctionList; // 返回过滤后的数据
        });
      }).catch(error => {
        console.error("加载肝功能数据失败", error);
        this.$message.error("加载肝功能数据失败");
        throw error; // 重新抛出错误
      });
    },

    // 搜索指标
    searchIndicators() {
      if (!this.form.reportId) {
        return;
      }
      
      // 重置到第一页
      this.indicatorQueryParams.pageNum = 1;
      this.indicatorQueryParams.reportId = this.form.reportId;
      this.loadIndicators(this.form.reportId);
    },

    /**
     * 重置指标筛选条件
     */
    resetIndicatorFilter() {
      this.indicatorSearch = '';
      this.indicatorCateId = '';
      this.searchIndicators();
    },
    // 查看指标详情
    viewIndicatorDetail(indicator) {
      this.currentIndicator = indicator;
      this.indicatorDetailVisible = true;
    },

    // 添加指标
    handleAddIndicator() {
      if (!this.form.reportId) {
        this.$message.warning("请先保存体检报告，再添加指标");
        return;
      }

      // 加载指标库数据
      this.searchIndicatorLibrary();
      this.indicatorSelectVisible = true;
    },

    // 搜索指标库
    searchIndicatorLibrary() {
      // 构建查询参数
      const query = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        indicatorName: this.indicatorLibrarySearch || undefined,
        indicatorCategory: this.indicatorCategory || undefined
      };

      // 调用API查询指标库
      import('@/api/medical/indicator').then(module => {
        const { listIndicator } = module;
        listIndicator(query).then(response => {
          this.indicatorLibrary = response.data.list;
          this.totalIndicators = response.data.total;
        });
      }).catch(error => {
        console.error("搜索指标库失败", error);
        this.$message.error("搜索指标库失败");
      });
    },

    // 分页大小变化
    handleSizeChange(val) {
      this.pageSize = val;
      this.searchIndicatorLibrary();
    },

    // 分页页码变化
    handleCurrentChange(val) {
      this.currentPage = val;
      this.searchIndicatorLibrary();
    },

    // 指标选择变化
    handleIndicatorSelectionChange(selection) {
      this.selectedIndicators = selection;
    },

    // 添加选中的指标
    addSelectedIndicators() {
      if (this.selectedIndicators.length === 0) {
        this.$message.warning("请至少选择一个指标");
        return;
      }

      // 准备批量添加的数据
      const batchData = this.selectedIndicators.map(item => ({
        reportId: this.form.reportId,
        indicatorId: item.indicatorId,
        testValue: null,
        testResult: null,
        isAbnormal: 0,
        abnormalType: null,
        remarks: null
      }));

      // 调用API批量添加指标结果
      import('@/api/medical/reportIndicator').then(module => {
        const { batchAddResult } = module;
        batchAddResult(batchData).then(() => {
          this.$message.success("添加指标成功");
          this.indicatorSelectVisible = false;
          // 重新加载指标数据
          this.loadIndicators();
          // 重新加载肝功能数据
          this.loadLiverFunction(this.form.reportId);
        });
      }).catch(error => {
        console.error("添加指标失败", error);
        this.$message.error("添加指标失败");
      });
    },

    // 格式化参考范围
    formatReferenceRange(indicator) {
      if (indicator.referenceText) {
        return indicator.referenceText;
      } else if (indicator.referenceMin !== null && indicator.referenceMax !== null) {
        return `${indicator.referenceMin}-${indicator.referenceMax}`;
      } else if (indicator.referenceMin !== null) {
        return `>${indicator.referenceMin}`;
      } else if (indicator.referenceMax !== null) {
        return `<${indicator.referenceMax}`;
      }
      return '无参考范围';
    },

    // 编辑指标结果
    editIndicator(indicator) {
      this.indicatorResultForm = {
        resultId: indicator.resultId,
        indicatorName: indicator.indicatorName || indicator.name,
        referenceRange: indicator.refRange || '',
        testValue: indicator.testValue || '',
        testResult: indicator.testResult || '',
        isAbnormal: indicator.isAbnormal || 0,
        abnormalType: indicator.abnormalType || '',
        remarks: indicator.remarks || ''
      };
      this.indicatorResultDialogVisible = true;
    },

    // 提交指标结果
    submitIndicatorResult() {
      this.$refs.indicatorResultForm.validate(valid => {
        if (valid) {
          // 调用API更新指标结果
          import('@/api/medical/reportIndicator').then(module => {
            const { updateResult } = module;
            const data = {
              resultId: this.indicatorResultForm.resultId,
              testValue: this.indicatorResultForm.testValue,
              testResult: this.indicatorResultForm.testResult,
              isAbnormal: this.indicatorResultForm.isAbnormal,
              abnormalType: this.indicatorResultForm.abnormalType,
              remarks: this.indicatorResultForm.remarks
            };

            updateResult(data).then(() => {
              this.$message.success("更新指标结果成功");
              this.indicatorResultDialogVisible = false;
              // 重新加载指标数据
              this.loadIndicators();
              // 重新加载肝功能数据
              this.loadLiverFunction(this.form.reportId);
            });
          }).catch(error => {
            console.error("更新指标结果失败", error);
            this.$message.error("更新指标结果失败");
          });
        }
      });
    }
  }
};
</script>
