<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="reportId">
        <el-input
          v-model="queryParams.reportId"
          placeholder="请输入报告ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="指标ID" prop="indicatorId">
        <el-input
          v-model="queryParams.indicatorId"
          placeholder="请输入指标ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </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:result:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleBatchAdd"
          v-hasPermi="['medical:result:add']"
        >批量新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="resultList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="结果ID" align="center" prop="resultId" />
      <el-table-column label="报告ID" align="center" prop="reportId" />
      <el-table-column label="指标ID" align="center" prop="indicatorId" />
      <el-table-column label="指标名称" align="center" prop="indicatorName" />
      <el-table-column label="检查结果" align="center" prop="resultValue" />
      <el-table-column label="参考范围" align="center" prop="referenceRange" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="异常标识" align="center" prop="abnormalFlag">
        <template slot-scope="scope">
          <dict-tag :options="abnormalFlagOptions" :value="scope.row.abnormalFlag"/>
        </template>
      </el-table-column>
      <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-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['medical:result:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['medical:result:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['medical:result: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="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="报告ID" prop="reportId">
          <el-input v-model="form.reportId" placeholder="请输入报告ID" />
        </el-form-item>
        <el-form-item label="指标ID" prop="indicatorId">
          <el-input v-model="form.indicatorId" placeholder="请输入指标ID" />
        </el-form-item>
        <el-form-item label="指标名称" prop="indicatorName">
          <el-input v-model="form.indicatorName" placeholder="请输入指标名称" />
        </el-form-item>
        <el-form-item label="检查结果" prop="resultValue">
          <el-input v-model="form.resultValue" placeholder="请输入检查结果" />
        </el-form-item>
        <el-form-item label="参考范围" prop="referenceRange">
          <el-input v-model="form.referenceRange" placeholder="请输入参考范围" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="异常标识" prop="abnormalFlag">
          <el-select v-model="form.abnormalFlag" placeholder="请选择异常标识">
            <el-option
              v-for="dict in abnormalFlagOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <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="batchOpen" width="800px" append-to-body>
      <el-form ref="batchForm" :model="batchForm" label-width="80px">
        <el-form-item label="报告ID" prop="reportId">
          <el-input v-model="batchForm.reportId" placeholder="请输入报告ID" />
        </el-form-item>
        <el-button type="primary" size="mini" @click="addBatchRow">添加行</el-button>
        <el-table :data="batchForm.results" style="margin-top: 10px;">
          <el-table-column label="指标ID" width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.indicatorId" size="mini" />
            </template>
          </el-table-column>
          <el-table-column label="指标名称" width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.indicatorName" size="mini" />
            </template>
          </el-table-column>
          <el-table-column label="检查结果" width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.resultValue" size="mini" />
            </template>
          </el-table-column>
          <el-table-column label="参考范围" width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.referenceRange" size="mini" />
            </template>
          </el-table-column>
          <el-table-column label="单位" width="80">
            <template slot-scope="scope">
              <el-input v-model="scope.row.unit" size="mini" />
            </template>
          </el-table-column>
          <el-table-column label="异常标识" width="100">
            <template slot-scope="scope">
              <el-select v-model="scope.row.abnormalFlag" size="mini">
                <el-option
                  v-for="dict in abnormalFlagOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="removeBatchRow(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBatchForm">确 定</el-button>
        <el-button @click="cancelBatch">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog title="检查结果详情" :visible.sync="detailOpen" width="500px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="结果ID">{{ detailData.resultId }}</el-descriptions-item>
        <el-descriptions-item label="报告ID">{{ detailData.reportId }}</el-descriptions-item>
        <el-descriptions-item label="指标ID">{{ detailData.indicatorId }}</el-descriptions-item>
        <el-descriptions-item label="指标名称">{{ detailData.indicatorName }}</el-descriptions-item>
        <el-descriptions-item label="检查结果">{{ detailData.resultValue }}</el-descriptions-item>
        <el-descriptions-item label="参考范围">{{ detailData.referenceRange }}</el-descriptions-item>
        <el-descriptions-item label="单位">{{ detailData.unit }}</el-descriptions-item>
        <el-descriptions-item label="异常标识">
          <dict-tag :options="abnormalFlagOptions" :value="detailData.abnormalFlag"/>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">
          {{ parseTime(detailData.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detailData.remark }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listResult, getResult, delResult, addResult, updateResult, batchAddResult, listByReportId, listByIndicatorId } from "@/api/medical/reportIndicator";

export default {
  name: "Result",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 报告指标检查结果表格数据
      resultList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示批量新增弹出层
      batchOpen: false,
      // 是否显示详情弹出层
      detailOpen: false,
      // 详情数据
      detailData: {},
      // 异常标识字典
      abnormalFlagOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        reportId: null,
        indicatorId: null,
      },
      // 表单参数
      form: {},
      // 批量表单参数
      batchForm: {
        reportId: null,
        results: []        },
      // 表单校验规则
      rules: {
        reportId: [{ required: true, message: '请输入报告ID', trigger: 'blur' }],
        indicatorId: [{ required: true, message: '请输入指标ID', trigger: 'blur' }],
        indicatorName: [{ required: true, message: '请输入指标名称', trigger: 'blur' }],
        resultValue: [{ required: true, message: '请输入检查结果', trigger: 'blur' }],
        referenceRange: [{ required: true, message: '请输入参考范围', trigger: 'blur' }],
        unit: [{ required: true, message: '请输入单位', trigger: 'blur' }],
        abnormalFlag: [{ required: true, message: '请选择异常标识', trigger: 'change' }],
      }
    };
  },
  created() {
    this.getList();
    this.loadDictData();
  },
  methods: {
    // 加载异常标识字典数据
    loadDictData() {
      // 这里模拟加载字典数据，实际可以根据项目字典接口替换
      this.abnormalFlagOptions = [
        { label: '正常', value: '0' },
        { label: '异常', value: '1' }
      ];
    },
    // 查询列表
    getList() {
      this.loading = true;
      listResult(this.queryParams).then((res) => {
        if (res && res.data) {
          this.resultList = res.data.list;
          this.total = res.data.total;
        }
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    // 重置搜索条件
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        reportId: null,
        indicatorId: null,
      };
      this.getList();
    },
    // 处理查询按钮点击
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 选择项变化
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.resultId);
      this.single = this.ids.length !== 1;
      this.multiple = this.ids.length === 0;
    },
    // 打开新增弹窗
    handleAdd() {
      this.title = "新增检查结果";
      this.form = {};
      this.open = true;
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.resetFields();
        }
      });
    },
    // 打开批量新增弹窗
    handleBatchAdd() {
      this.batchForm = {
        reportId: null,
        results: []
      };
      this.batchOpen = true;
    },
    // 添加批量新增表格行
    addBatchRow() {
      this.batchForm.results.push({
        indicatorId: '',
        indicatorName: '',
        resultValue: '',
        referenceRange: '',
        unit: '',
        abnormalFlag: '0'
      });
    },
    // 删除批量新增表格行
    removeBatchRow(index) {
      this.batchForm.results.splice(index, 1);
    },
    // 取消批量新增
    cancelBatch() {
      this.batchOpen = false;
    },
    // 提交批量新增表单
    submitBatchForm() {
      if (!this.batchForm.reportId) {
        this.$message.error('请输入报告ID');
        return;
      }
      if (this.batchForm.results.length === 0) {
        this.$message.error('请添加检查结果行');
        return;
      }
      // 给每个结果设置报告ID
      this.batchForm.results.forEach(item => {
        item.reportId = this.batchForm.reportId;
      });
      batchAddResult(this.batchForm.results).then(res => {
        if (res.code === 200) {
          this.$message.success(res.msg || '批量新增成功');
          this.batchOpen = false;
          this.getList();
        } else {
          this.$message.error(res.msg || '批量新增失败');
        }
      });
    },
    // 提交新增或修改表单
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.resultId) {
            updateResult(this.form).then(res => {
              if (res.code === 200) {
                this.$message.success(res.msg || '更新成功');
                this.open = false;
                this.getList();
              } else {
                this.$message.error(res.msg || '更新失败');
              }
            });
          } else {
            addResult(this.form).then(res => {
              if (res.code === 200) {
                this.$message.success(res.msg || '新增成功');
                this.open = false;
                this.getList();
              } else {
                this.$message.error(res.msg || '新增失败');
              }
            });
          }
        }
      });
    },
    // 取消新增或修改
    cancel() {
      this.open = false;
    },
    // 查看详情
    handleDetail(row) {
      getResult(row.resultId).then(res => {
        if (res.code === 200) {
          this.detailData = res.data;
          this.detailOpen = true;
        } else {
          this.$message.error(res.msg || '获取详情失败');
        }
      });
    },
    // 修改
    handleUpdate(row) {
      this.title = "修改检查结果";
      this.form = Object.assign({}, row);
      this.open = true;
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate();
        }
      });
    },
    // 删除
    handleDelete(row) {
      this.$confirm('确定删除该检查结果吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delResult(row.resultId).then(res => {
          if (res.code === 200) {
            this.$message.success(res.msg || '删除成功');
            this.getList();
          } else {
            this.$message.error(res.msg || '删除失败');
          }
        });
      }).catch(() => {});
    }
  }
};
</script>
