<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="处方类型" prop="prescribeType">
        <el-select v-model="queryParams.prescribeType" placeholder="请选择处方类型" clearable>
          <el-option label="西药" :value="1"></el-option>
          <el-option label="中药" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="处方单号" prop="prescribeCode">
        <el-input v-model="queryParams.prescribeCode" placeholder="请输入处方单号" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="订单编号" prop="orderCode">
        <el-input v-model="queryParams.orderCode" placeholder="请输入订单编号" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="患者姓名" prop="patientName">
        <el-input v-model="queryParams.patientName" placeholder="请输入患者姓名" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="医生姓名" prop="doctorName">
        <el-input v-model="queryParams.doctorName" placeholder="请输入医生姓名" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="创建时间" prop="dateRange">
        <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
                        end-placeholder="结束日期" value-format="yyyy-MM-dd"
                        @change="handleDateRangeChange"></el-date-picker>
      </el-form-item>
      <el-form-item label="审核时间" prop="auditRange">
        <el-date-picker v-model="auditRange" type="daterange" range-separator="至" start-placeholder="开始日期"
                        end-placeholder="结束日期" value-format="yyyy-MM-dd"
                        @change="handleAuditDateRangeChange"></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="['his:prescribe: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="['his:prescribe:edit']">修改
        </el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click=""-->
<!--                   v-hasPermi="['his:prescribe:remove']">删除-->
<!--        </el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   v-hasPermi="['his:prescribe:export']">导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-download" size="mini" @click="handleMessageFeedbackExport"
                   v-hasPermi="['his:prescribe:messageFeedbackExport']">导出医疗信息反馈单
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="prescribeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="处方ID" align="center" prop="prescribeId"/>
      <el-table-column label="处方单号" align="center" prop="prescribeCode"/>
      <el-table-column label="处方类型" align="center" prop="prescribeType">
        <template slot-scope="scope">
          <dict-tag :options="prescribeTypeOptions" :value="scope.row.prescribeType"/>
        </template>
      </el-table-column>
      <el-table-column label="订单编号" align="center" prop="orderCode" width="180"/>
      <el-table-column label="患者姓名" align="center" prop="patientName"/>
      <el-table-column label="医生姓名" align="center" prop="doctorName"/>
      <el-table-column label="是否确认" align="center" prop="doctorConfirm">
        <template slot-scope="scope">
          <dict-tag :options="doctorConfirmOptions" :value="scope.row.doctorConfirm"/>
        </template>
      </el-table-column>
      <el-table-column label="拒方次数" align="center" prop="refuseCount"/>
      <el-table-column label="操作时间" align="center" prop="operateTime"/>
      <el-table-column label="审核时间" align="center" prop="auditTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.auditTime, '{y}-{m}-{d}') }}</span>
        </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="prescribeSource" prop="createTime" width="180">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.prescribeSource === 1 ? 'success' : 'info'"
            size="small"
          >
            {{ scope.row.prescribeSource === 1 ? '信息采集表' : '其他' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.doctorConfirm == 0" size="mini" type="text" icon="el-icon-edit"
                     @click="handleUpdate(scope.row)">开方
          </el-button>
          <el-button v-if="scope.row.doctorConfirm == 0" size="mini" type="text" icon="el-icon-delete"
                     @click="handleReject(scope.row)">拒方
          </el-button>
          <el-button v-if="scope.row.doctorConfirm == 1" size="mini" type="text"
                     @click="handleUpdate(scope.row)">查看
          </el-button>
          <el-button v-if="scope.row.doctorConfirm == 1" size="mini" type="text"
                     @click="handleRecord(scope.row)">审核记录
          </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 @close="handleDialogClose">
      <el-tabs v-model="activeTab" type="border-card">
        <!-- Tab 1: 基本信息 -->
        <el-tab-pane label="基本信息" name="basic">
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="处方类型" prop="prescribeType">
              <el-radio-group v-model="form.prescribeType">
                <el-radio :label="1">西药</el-radio>
                <el-radio :label="2">中药</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="订单ID" prop="inquiryOrderId">
              <el-input v-model="form.inquiryOrderId" placeholder="请输入订单ID" disabled/>
            </el-form-item>
            <el-form-item label="店铺订单ID" prop="storeOrderId">
              <el-input v-model="form.storeOrderId" placeholder="请输入店铺订单ID" disabled/>
            </el-form-item>
            <el-form-item label="患者姓名" prop="patientName">
              <el-input v-model="form.patientName" placeholder="请输入患者姓名"/>
            </el-form-item>
            <el-form-item label="患者年龄" prop="patientAge">
              <el-input v-model="form.patientAge" placeholder="请输入患者年龄"/>
            </el-form-item>
            <el-form-item label="患者性别" prop="patientGender">
              <el-select v-model="form.patientGender" placeholder="请选择患者性别">
                <el-option label="男" value="1"></el-option>
                <el-option label="女" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="体重" prop="weight">
              <el-input v-model="form.weight" placeholder="请输入体重"/>
            </el-form-item>
            <el-form-item label="是否有过敏史" prop="isHistoryAllergic">
              <el-radio-group v-model="form.isHistoryAllergic">
                <el-radio :label="'是'">是</el-radio>
                <el-radio :label="'否'">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label="过敏史"
              prop="historyAllergic"
              :required="form.isHistoryAllergic === '是'"
            >
              <el-input
                v-model="form.historyAllergic"
                placeholder="请输入过敏史"
                :disabled="form.isHistoryAllergic === '否'"
              />
            </el-form-item>
            <!-- 定位在右下角的按钮 -->
            <el-button
              type="success"
              size="mini"
              style="position: absolute; bottom: 5px; right: 180px;"
              @click="openDoctorAdviceDialog"
              :disabled="!form.prescribeId || !form.userId"
            >
              查看医生建议
            </el-button>
            <el-button type="primary" size="mini" style="position: absolute; bottom: 5px; right: 20px;"
                       @click="openCollectionInfo">
              查看采集信息
            </el-button>
          </el-form>
        </el-tab-pane>
        <!-- Tab 2: 处方药品信息 -->
        <el-tab-pane label="处方药品信息" name="drug">
          <div class="drug-container">
            <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="drug-container">
              <!-- 诊断 -->
              <el-form-item label="诊断" prop="diagnose">
                <el-input v-model="form.diagnose" placeholder="请输入诊断">
                  <i slot="suffix" class="el-icon-search el-input__icon" style="cursor: pointer;"
                     @click="handleCommonlyDiagnoseWorlds"></i>
                </el-input>
              </el-form-item>

              <!-- 医嘱 -->
              <el-form-item label="医嘱" prop="remark">
                <div style="display: flex; align-items: center;">
                  <el-input v-model="form.remark" type="textarea" placeholder="请输入医嘱" style="flex: 1;"></el-input>
                </div>
              </el-form-item>
            </el-form>
            <!-- 药品操作按钮 -->
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button v-if="currentConfirm === 0" type="primary" icon="el-icon-plus" size="mini"
                           @click="handleAddDrug" :disabled="!form.prescribeId">新增药品
                </el-button>
              </el-col>
              <el-col :span="2.5">
                <el-button v-if="currentConfirm === 0" type="success" icon="el-icon-search" size="mini"
                           @click="openCommonPrescribeDialog" :disabled="!form.prescribeId">常用药品
                </el-button>
              </el-col>

            </el-row>
            <!-- 药品列表表格 -->
            <el-table v-loading="drugLoading" :data="drugList" border max-height="400">
              <el-table-column label="药品名称" align="center" prop="drugName"/>
              <el-table-column label="规格" align="center" prop="drugSpec" width="100"/>
              <el-table-column label="使用方法" align="center" prop="usageMethod" width="100"/>
              <el-table-column label="频次" align="center" prop="usageFrequencyUnit" width="80"/>
              <el-table-column label="每次用药数量" align="center" width="120">
                <template slot-scope="scope">
                  {{ scope.row.usagePerUseCount }}{{ scope.row.usagePerUseUnit }}
                </template>
              </el-table-column>
              <el-table-column v-if="currentConfirm === 0" label="操作" align="center"
                               class-name="small-padding fixed-width" width="150">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-edit"
                             @click="handleUpdateDrug(scope.row)">编辑
                  </el-button>
                  <el-button size="mini" type="text" icon="el-icon-delete"
                             @click="handleDeleteDrug(scope.row)">删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 药品分页 -->
            <pagination v-show="drugTotal > 0" :total="drugTotal" :page.sync="drugQueryParams.pageNum"
                        :limit.sync="drugQueryParams.pageSize" @pagination="getDrugList"/>
          </div>
        </el-tab-pane>
        <!-- Tab 3: 用户信息采集 -->
        <el-tab-pane label="采集信息详情" name="userCollection">
          <el-row :gutter="20" style="margin-bottom: 20px;">
            <el-col :span="8">
              <div class="info-item">
                <span class="label">患者姓名：</span>
                <span class="value">{{ form.patientName || '—' }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">患者年龄：</span>
                <span class="value">{{ form.patientAge || '—' }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">患者性别：</span>
                <span class="value">{{
                    form.patientGender === '1' ? '男' : form.patientGender === '2' ? '女' : '—'
                  }}</span>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="info-item">
                <span class="label">体重：</span>
                <span class="value">{{ form.weight ? form.weight + ' kg' : '—' }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">是否有过敏史：</span>
                <span class="value">{{ form.isHistoryAllergic || '—' }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">过敏史：</span>
                <span class="value">{{ form.isHistoryAllergic === '是' ? (form.historyAllergic || '—') : '无' }}</span>
              </div>
            </el-col>
          </el-row>
          <collectionDetail :userId="form.userId" :prescribeId="form.prescribeId" v-if="form.userId"/>
        </el-tab-pane>
      </el-tabs>

      <!-- 医生建议 el-dialog-->
      <el-dialog
        title="医生建议"
        :visible.sync="doctorAdviceDialogVisible"
        width="600px"
        append-to-body
      >
        <div v-if="doctorAdviceContent" v-html="doctorAdviceContent"></div> <!-- 使用 v-html 渲染 HTML 内容 -->
        <div v-else>暂无医生建议信息。</div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="doctorAdviceDialogVisible = false">关 闭</el-button>
            </span>
      </el-dialog>
      <!-- 查看采集信息的弹窗 -->
      <el-dialog :visible.sync="collectionDialogVisible" title="用户信息采集详情" width="800px" append-to-body>

        <el-row :gutter="20" style="margin-bottom: 20px;">
          <el-col :span="8">
            <div class="info-item">
              <span class="label">患者姓名：</span>
              <span class="value">{{ form.patientName || '—' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">患者年龄：</span>
              <span class="value">{{ form.patientAge || '—' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">患者性别：</span>
              <span class="value">{{
                  form.patientGender === '1' ? '男' : form.patientGender === '2' ? '女' : '—'
                }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <span class="label">体重：</span>
              <span class="value">{{ form.weight ? form.weight + ' kg' : '—' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">是否有过敏史：</span>
              <span class="value">{{ form.isHistoryAllergic || '—' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">过敏史：</span>
              <span class="value">{{ form.isHistoryAllergic === '是' ? (form.historyAllergic || '—') : '无' }}</span>
            </div>
          </el-col>
        </el-row>

        <collectionDetail :userId="form.userId" :prescribeId="form.prescribeId" v-if="collectionDialogVisible"/>
        <span slot="footer" class="dialog-footer">
          <el-button @click="collectionDialogVisible = false">关 闭</el-button>
        </span>
      </el-dialog>

      <span slot="footer" class="dialog-footer">
        <el-button @click="open = false">关 闭</el-button>
        <el-button type="primary" @click="submitForm" v-if="currentConfirm === 0">保 存</el-button>
        <el-button type="primary" @click="confirmPrescribe" v-if="currentConfirm === 0">确认处方</el-button>
      </span>
    </el-dialog>
    <!-- 药品新增/编辑对话框 -->
    <el-dialog :title="drugTitle" :visible.sync="drugOpen" width="700px" append-to-body>
      <el-form ref="drugForm" :model="drugForm" :rules="drugRules" label-width="120px">
        <el-form-item label="药品名称" prop="drugName">
          <el-input v-model="drugForm.drugName" placeholder="请输入药品名称"/>
        </el-form-item>
        <el-form-item label="规格" prop="drugSpec">
          <el-input v-model="drugForm.drugSpec" placeholder="请输入规格"/>
        </el-form-item>
        <el-form-item label="使用方法" prop="usageMethod">
          <el-input v-model="drugForm.usageMethod" placeholder="请输入使用方法"/>
        </el-form-item>
        <el-form-item label="每次用药数量" prop="usagePerUseCount">
          <el-input v-model="drugForm.usagePerUseCount" placeholder="请输入每次用药数量"/>
        </el-form-item>
        <el-form-item label="药品频次" prop="usageFrequencyUnit">
          <el-input v-model="drugForm.usageFrequencyUnit" placeholder="请输入药品频次,如:每日3次"/>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="drugOpen = false">取 消</el-button>
        <el-button type="primary" @click="submitDrugForm">确 定</el-button>
      </span>
    </el-dialog>

    <!--常用语选择对话框 -->
    <el-dialog :title="suggestDialogTitle" :visible.sync="showSuggestDialog" width="600px" append-to-body
               @closed="clearSuggestList">
      <el-table :data="suggestList" height="300" border @row-click="handleSuggestRowClick">
        <el-table-column type="index" width="50"/>
        <el-table-column label="内容" prop="diagnose" show-overflow-tooltip/>
        <el-table-column label="操作" width="80" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click.stop="handleAddSuggest(scope.row)">
              添加
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="suggestTotal > 0" :total="suggestTotal" :page.sync="suggestQuery.pageNum"
                  :limit.sync="suggestQuery.pageSize" @pagination="getSuggestList"/>
    </el-dialog>

    <!-- 常用药品选择对话框 -->
    <el-dialog title="选择常用药品" :visible.sync="commonPrescribeDialogVisible" width="800px" append-to-body
               @open="handleOpenCommonPrescribeDialog">

      <!-- 搜索区域 -->
      <el-form :model="commonDrugQuery" :inline="true" size="small" label-width="80px">
        <el-form-item label="药品名称" prop="drugName">
          <el-input v-model="commonDrugQuery.drugName" placeholder="请输入药品名称" clearable
                    @keyup.enter.native="handleCommonPrescribeQuery"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleCommonPrescribeQuery">搜索
          </el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetCommonPrescribeQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table v-loading="commonPrescribeLoading" :data="commonDrugList" border style="width: 100%; margin-top: 10px;"
                max-height="400">
        <!-- 药品名称 -->
        <el-table-column label="药品名称" align="center" prop="drugName" show-overflow-tooltip/>

        <!-- 规格 -->
        <el-table-column label="规格" align="center" prop="drugSpec" width="100"/>

        <!-- 用法 -->
        <el-table-column label="用法" align="center" prop="usageMethod" width="100"/>

        <!-- 频次 -->
        <el-table-column label="频次" align="center" prop="usageFrequencyUnit" width="100"/>

        <!-- 每次用药数量 -->
        <el-table-column label="每次用量" align="center" prop="usagePerUseCount" width="100"/>

        <!-- 操作 -->
        <el-table-column label="操作" align="center" width="100">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-check"
                       @click="applyCommonPrescribe(scope.row)">应用
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination v-show="commonPrescribeTotal > 0" :total="commonPrescribeTotal" :page.sync="commonDrugQuery.pageNum"
                  :limit.sync="commonDrugQuery.pageSize" @pagination="getCommonPrescribeList"
                  style="margin-top: 10px;"/>

    </el-dialog>


    <el-dialog title="审核记录" :visible.sync="recordDialogVisible" width="1000px" append-to-body>
      <el-table v-loading="recordLoading" :data="recordList" border style="width: 100%; margin-top: 10px;"
                max-height="400">
        <el-table-column label="审核药师" align="center" prop="drugDoctorName"/>
        <el-table-column label="拒方原因" align="center" prop="auditReason" show-overflow-tooltip/>
        <el-table-column label="处方图片" align="center" width="140">
          <template slot-scope="scope">
            <el-image v-if="scope.row.prescribeImgUrl" :src="scope.row.prescribeImgUrl"
                      :preview-src-list="[scope.row.prescribeImgUrl]" style="width: 120px; height: 120px" fit="cover"/>
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column label="审核时间" align="center" prop="createTime"/>
        <el-table-column label="审核状态" align="center" width="120">
          <template slot-scope="scope">
            {{ statusFormat(scope.row.auditStatus != null ? scope.row.auditStatus : scope.row.status) }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>
<script>
import {getCommonDrugList} from '@/api/commonlyDrug';
import {getCommonDiagnoseList} from '@/api/commonlyDiagnose';
import collectionDetail from '@/views/components/collection/collectionDetail.vue';
import {
  listPrescribe,
  getPrescribe,
  addPrescribe,
  updatePrescribe,
  exportPrescribe,
  exportMessageFeedback,
  confirmPrescribe,
  recordList
} from '@/api/his/prescribe'
import {listPrescribeDrug, addPrescribeDrug, updatePrescribeDrug, deletePrescribeDrug} from "@/api/his/prescribeDrug";
import {getCollectionByUserId} from "@/api/collection";
import {handleReject} from '@/api/his/prescribe'

export default {
  components: {
    collectionDetail // 注册引入的组件
  },
  name: "Prescribe",
  data() {
    // 自定义验证规则 - 过敏史条件验证
    const validateAllergyHistory = (rule, value, callback) => {
      if (this.form.isHistoryAllergic === '是' && !value) {
        callback(new Error('请填写过敏史'));
      } else {
        callback();
      }
    };
    return {
      //审核记录数据
      recordLoading: false,
      recordList: [],
      recordDialogVisible: false,//审核记录弹窗控制
      // 新增：用于存储医生建议内容
      doctorAdviceContent: '',
      // 新增：控制医生建议弹窗显示
      doctorAdviceDialogVisible: false,
      collectionDialogVisible: false, // 控制采集信息弹窗显示
      suggestList: [],   // 常用语建议列表
      suggestTotal: 0,   // 分页总数
      showSuggestDialog: false, // 是否显示建议对话框
      suggestQuery: {    // 建议查询参数
        pageNum: 1,
        pageSize: 10,
        diagnose: null
      },
      suggestSource: '', // 记录来源字段 'diagnose' 或 'remark'
      suggestRow: null,  // 如果是备注，记录具体行
      // 原有数据保持不变
      loading: false,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      prescribeList: [],
      title: "",
      open: false,
      dateRange: [],
      auditRange: [],
      doctorConfirmOptions: [
        {dictValue: '0', dictLabel: "未确认"},
        {dictValue: '1', dictLabel: "已确认"}
      ],
      prescribeTypeOptions: [
        {dictValue: '1', dictLabel: "西药"},
        {dictValue: '2', dictLabel: "中药"},
        {dictValue: '3', dictLabel: "OTC"}
      ],
      statusOptions: [
        {dictValue: '0', dictLabel: "未开"},
        {dictValue: '1', dictLabel: "已开"}
      ],
      // 常用药品弹窗相关
      commonPrescribeDialogVisible: false,
      commonPrescribeLoading: false,
      commonDrugList: [],
      commonPrescribeTotal: 0,
      commonDrugQuery: {
        pageNum: 1,
        pageSize: 10,
        drugName: undefined
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        prescribeType: undefined,
        prescribeCode: undefined,
        orderCode: undefined,
        patientName: undefined,
        patientTel: undefined,
        status: undefined,
        doctorName: undefined,
        beginCreateTime: undefined,
        endCreateTime: undefined,
        beginAuditTime: undefined,
        endAuditTime: undefined
      },
      currentConfirm: null,
      form: {},
      rules: {
        prescribeType: [
          { required: true, message: "处方类型不能为空", trigger: "change" }
        ],
        patientName: [
          { required: true, message: "患者姓名不能为空", trigger: "blur" }
        ],
        patientAge: [
          { required: true, message: "患者年龄不能为空", trigger: "blur" }
        ],
        patientGender: [
          { required: true, message: "患者性别不能为空", trigger: "change" }
        ],
        // weight: [
        //   { required: true, message: "患者体重不能为空", trigger: ["blur", "change"] }
        // ],
        isHistoryAllergic: [
          { required: true, message: "患者是否有过敏史不能为空", trigger: ["blur", "change"] }
        ],
        historyAllergic: [
          { validator: validateAllergyHistory, trigger: ["blur", "change"] }
        ],
        diagnose: [
          { required: true, message: "诊断不能为空", trigger: ["blur", "change"] }
        ],
        remark: [
          { required: true, message: "医嘱不能为空", trigger: ["blur", "change"] }
        ]
      },
      // 新增:Tab相关
      activeTab: 'basic',
      // 新增:药品相关数据
      drugLoading: false,
      drugList: [],
      drugTotal: 0,
      drugOpen: false,
      drugTitle: "",
      drugForm: {},
      drugQueryParams: {
        pageNum: 1,
        pageSize: 10,
        prescribeId: undefined
      },
      drugRules: {
        drugName: [{required: true, message: "药品名称不能为空", trigger: "blur"}],
        drugSpec: [{required: true, message: "规格不能为空", trigger: "blur"}],
        usageMethod: [{required: true, message: "使用方法不能为空", trigger: "blur"}],
        usageFrequencyUnit: [{required: true, message: "药品频次不能为空", trigger: "blur"}],
        usagePerUseCount: [{required: true, message: "每次用药数量不能为空", trigger: "blur"}],
        usagePerUseUnit: [{required: true, message: "每次用药单位不能为空", trigger: "blur"}],
        usageDays: [{required: true, message: "天数不能为空", trigger: "blur"}],
        drugPrice: [{required: true, message: "药品单价不能为空", trigger: "blur"}],
        drugNum: [{required: true, message: "药品数量不能为空", trigger: "blur"}],
        drugUnit: [{required: true, message: "药品数量单位不能为空", trigger: "blur"}],
        instructions: [{required: true, message: "药品说明书不能为空", trigger: "blur"}]
      }
    };
  },
  computed: {
    // 动态标题
    suggestDialogTitle() {
      if (this.suggestSource === 'diagnose') return '选择常用诊断内容';
      if (this.suggestSource === 'remark') return '选择常用备注内容';
      return '选择常用内容';
    }
  },
  created() {
    this.getList();
  },
  watch: {
    // 监听Tab切换,当切换到药品Tab时加载药品列表
    activeTab(newVal) {
      if (newVal === 'drug' && this.form.prescribeId) {
        this.getDrugList();
      }
    },

    // 监听是否有过敏史字段变化，动态调整过敏史字段的必填校验
    'form.isHistoryAllergic': function(newVal) {
      if (newVal === '否') {
        // 如果选择"否"，清空过敏史字段
        this.form.historyAllergic = '';
      }
      // 触发过敏史字段的重新验证
      this.$nextTick(() => {
        if (this.$refs["form"]) {
          this.$refs["form"].validateField('historyAllergic');
        }
      });
    }
  },
  methods: {
    statusFormat(val) {
      if (val === 0 || val === '0') return '待审核'
      if (val === 1 || val === '1') return '审核通过'
      if (val === 2 || val === '2') return '审核不通过'
      return '-'
    },
    //审核记录
    handleRecord(row) {
      this.recordDialogVisible = true;
      this.recordLoading = true;
      recordList(row.prescribeId).then(res => {
        this.recordLoading = false;
        this.recordList = res.data;
      })
    },
    /**
     * 打开常用药品对话框，并打印当前医生ID
     */
    openCommonPrescribeDialog() {
      // 打开对话框
      this.commonPrescribeDialogVisible = true;
    },

    /** 打开常用药品对话框时加载数据 */
    handleOpenCommonPrescribeDialog() {
      this.commonDrugQuery.pageNum = 1;
      this.getCommonPrescribeList();
    },

    /** 搜索常用药品 */
    handleCommonPrescribeQuery() {
      this.commonDrugQuery.pageNum = 1;
      this.getCommonPrescribeList();
    },

    /** 重置常用药品搜索 */
    resetCommonPrescribeQuery() {
      this.commonDrugQuery.drugName = undefined;
      this.handleCommonPrescribeQuery();
    },

    /** 获取常用药品列表 */
    getCommonPrescribeList() {
      this.commonPrescribeLoading = true;
      // 获取当前医生ID
      const doctorId = this.form.doctorId || this.$store.state.user.userId?.replace('D-', '');
      const params = {
        ...this.commonDrugQuery,
        doctorId: doctorId
      };
      getCommonDrugList(params).then(response => {
        this.commonDrugList = response.data.list || [];
        this.commonPrescribeTotal = response.data.total || 0;
        this.commonPrescribeLoading = false;
      }).catch(() => {
        this.commonPrescribeLoading = false;
      });
    },

    /** 应用选中的常用药品到当前表单 */
    async applyCommonPrescribe(row) {
      if (!this.form.prescribeId) {
        this.$message.warning('请先保存处方基本信息，再应用常用药品');
        this.commonPrescribeDialogVisible = false;
        return;
      }

      // 显示 loading
      this.drugLoading = true;
      this.$message.info(`正在添加药品: ${row.drugName}...`);

      try {
        // 构造药品数据（注意字段名要和 addPrescribeDrug 接口一致）
        const drugData = {
          prescribeId: this.form.prescribeId,
          drugName: row.drugName,
          drugSpec: row.drugSpec,
          usageMethod: row.usageMethod,
          usageFrequencyUnit: row.usageFrequencyUnit,
          usagePerUseCount: row.usagePerUseCount,
          usagePerUseUnit: '', // 或根据业务补充
          usageDays: '',
          drugPrice: '',
          drugNum: '',
          drugUnit: '',
          instructions: ''
        };

        await addPrescribeDrug(drugData);
        await this.getDrugList(); // 刷新药品列表
        this.$message.success(`成功添加药品: ${row.drugName}`);
      } catch (error) {
        console.error('应用常用药品失败:', error);
        this.$message.error('药品添加失败，请检查后重试');
      } finally {
        this.drugLoading = false;
        this.commonPrescribeDialogVisible = false;
      }
    },


    /**
     * 诊断常用语列表方法
     */
    handleCommonlyDiagnoseWorlds() {
      // 设置来源，用于后续填充
      this.suggestSource = 'diagnose';
      // 设置查询参数
      this.suggestQuery.pageNum = 1;
      // 获取建议列表
      this.getSuggestList().then(() => {
        if (this.suggestList.length > 0) {
          this.showSuggestDialog = true;
        } else {
          this.$message.info('未找到相关常用诊断');
        }
      });
    },

    /**
     * 获取常用语列表（支持分页）
     */
    async getSuggestList() {
      try {
        const response = await getCommonDiagnoseList(this.suggestQuery);
        if (response && response.data && Array.isArray(response.data.list)) {
          this.suggestList = response.data.list;
          this.suggestTotal = response.data.total;
        } else {
          this.suggestList = [];
          this.suggestTotal = 0;
        }
      } catch (error) {
        this.$message.warning("获取常用语失败");
        this.suggestList = [];
        this.suggestTotal = 0;
      }
    },

    /**
     * 点击建议行（双击或点击添加）
     */
    handleSuggestRowClick(row) {
      this.handleAddSuggest(row);
    },

    /**
     * 添加建议内容到对应字段（拼接而非覆盖）
     */
    handleAddSuggest(row) {
      const text = row.diagnose;
      if (!text) return;

      // 获取当前已输入的内容，去除首尾空格
      let current = (this.form.diagnose || '').trim();

      // 如果已有内容，且不以逗号结尾，则添加英文逗号 + 空格
      if (current) {
        // 避免重复逗号：如果结尾已经是逗号（或逗号+空格），就不再加
        if (!current.endsWith(',')) {
          current += ', ';
        }
        this.form.diagnose = current + text;
      } else {
        // 如果为空，直接赋值
        this.form.diagnose = text;
      }

      // 关闭对话框
      this.showSuggestDialog = false;
      this.clearSuggestList();
    },

    /**
     * 清空建议数据
     */
    clearSuggestList() {
      this.suggestList = [];
      this.suggestTotal = 0;
      this.suggestQuery.pageNum = 1;
      this.suggestQuery.textContent = '';
    },
    /** 查询处方列表 */
    getList() {
      this.loading = true;
      let userId = this.$store.state.user.userId;
      let query = this.addDateRange(this.queryParams, this.dateRange, 'Create');
      query.doctorId = userId.toString().replaceAll("D-", "").toString();
      listPrescribe(query).then(response => {
        this.prescribeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询药品列表 */
    getDrugList() {
      if (!this.form.prescribeId) {
        this.$message.warning("请先保存处方基本信息");
        return;
      }
      this.drugLoading = true;
      this.drugQueryParams.prescribeId = this.form.prescribeId;
      listPrescribeDrug(this.drugQueryParams).then(response => {
        this.drugList = response.rows;
        this.drugTotal = response.total;
        this.drugLoading = false;
      });
    },
    // 日期范围处理
    addDateRange(params, dateRange, type) {
      let obj = {...params};
      if (dateRange != null && dateRange.length > 0) {
        if (type === 'Create') {
          obj.beginCreateTime = dateRange[0];
          obj.endCreateTime = dateRange[1];
        } else if (type === 'Audit') {
          obj.beginAuditTime = dateRange[0];
          obj.endAuditTime = dateRange[1];
        }
      }
      return obj;
    },
    handleDateRangeChange(val) {
      this.queryParams.beginCreateTime = val ? val[0] : undefined;
      this.queryParams.endCreateTime = val ? val[1] : undefined;
    },
    handleAuditDateRangeChange(val) {
      this.queryParams.beginAuditTime = val ? val[0] : undefined;
      this.queryParams.endAuditTime = val ? val[1] : undefined;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.auditRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 选择条目触发事件 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.prescribeId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增处方";
      this.activeTab = 'basic';
    },
    /** 拒方弹窗 */
    handleReject(row) {
      this.$prompt('请输入拒方原因', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入备注（不可为空）',
        // 至少输入1个非空白字符
        inputPattern: /\S+/,
        inputErrorMessage: '拒方原因不能为空'
      }).then(({ value }) => {
        const remark = value.trim();
        handleReject({
          prescribeId: row.prescribeId,
          remark: remark
        }).then(() => {
          this.$message.success('拒方成功');
        }).catch(() => {
          this.$message.error('拒方失败');
        });
      }).catch(() => {
        this.$message.info('已取消拒方');
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const prescribeId = row.prescribeId || this.ids[0];
      this.currentConfirm = row.doctorConfirm;

      getPrescribe(prescribeId).then(response => {
        this.form = response.data;
        if(row.doctorConfirm === 0) {
        this.form.startOperateTime = new Date().getTime();
        }
        this.open = true;
        if (this.currentConfirm == 0) {
          this.title = "修改处方";
        } else {
          this.title = "查看处方";
        }

        this.activeTab = 'basic';
        // 如果有prescribeId,则可以查询药品列表
        if (this.form.prescribeId) {
          this.drugQueryParams.prescribeId = this.form.prescribeId;
        }
      })
    },
    confirmPrescribe() {
      // 检查必填字段
      const missingField = this.getFirstMissingField();
      if (missingField) {
        this.$message.error(`请填写${missingField}`);
        return;
      }
      //确认处方的同时保存处方
      this.savePrescribe();
      confirmPrescribe(this.form).then(response => {
        if (response.code === 200) {
          this.$message.success("确认成功！");
          this.open = false;
        } else {
          this.$message.error(response.message);
        }
      }).finally(() => {
        this.getList();
      })

    },
    /** 提交按钮操作 */
    submitForm() {
      // 检查必填字段
      const missingField = this.getFirstMissingField();
      if (missingField) {
        this.$message.error(`请填写${missingField}`);
        return;
      }

      this.savePrescribe();
    },

    /** 获取第一个未填写的必填字段 */
    getFirstMissingField() {
      const fieldConfig = {
        'prescribeType': '处方类型',
        'patientName': '患者姓名',
        'patientAge': '患者年龄',
        'patientGender': '患者性别',
        // 'weight': '患者体重',
        'isHistoryAllergic': '是否有过敏史',
        'diagnose': '诊断',
        'remark': '医嘱'
      };

      for (let [key, name] of Object.entries(fieldConfig)) {
        const value = this.form[key];

        // 检查字段是否为空
        if (value === undefined || value === null || value === '') {
          return name;
        }

        // 特殊处理过敏史
        if (key === 'isHistoryAllergic' && value === '是' && !this.form.historyAllergic) {
          return '过敏史';
        }
      }

      return null;
    },

    /** 保存处方数据 */
    savePrescribe() {
      const request = this.form.prescribeId != undefined
        ? updatePrescribe(this.form)
        : addPrescribe(this.form);

      request.then(response => {
        this.$message.success(this.form.prescribeId != undefined ? "修改成功" : "新增成功");
        this.open = false;
        this.getList();
      }).catch(error => {
        console.error('保存失败:', error);
        this.$message.error("保存失败");
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.$modal.confirm('是否确认导出所有处方数据项?').then(() => {
        this.exportLoading = true;
        return exportPrescribe(this.queryParams);
      }).then(response => {
        this.$download.excel(response, '处方数据');
        this.exportLoading = false;
      }).catch(() => {
      });
    },
    /** 导出医疗信息反馈单 */
    handleMessageFeedbackExport() {
      if (this.ids.length === 0) {
        this.$modal.msgError("请至少选择一条记录");
        return;
      }
      this.$modal.confirm('是否确认导出所选处方的医疗信息反馈单?').then(() => {
        this.exportLoading = true;
        return exportMessageFeedback(this.ids);
      }).then(response => {
        this.$download.excel(response, '医疗信息反馈单');
        this.exportLoading = false;
      }).catch(() => {
      });
    },
    /** 对话框关闭事件 */
    handleDialogClose() {
      // 重置药品相关数据
      this.drugList = [];
      this.currentConfirm = null;
      this.drugTotal = 0;
      this.drugQueryParams.pageNum = 1;
      this.activeTab = 'basic';
    },
    // ==================== 药品相关方法 ====================
    /** 新增药品按钮操作 */
    handleAddDrug() {
      if (!this.form.prescribeId) {
        this.$modal.msgWarning("请先保存处方基本信息后再添加药品");
        return;
      }
      this.resetDrugForm();
      this.drugOpen = true;
      this.drugTitle = "新增药品";
    },
    /** 修改药品按钮操作 */
    handleUpdateDrug(row) {
      this.resetDrugForm();
      this.drugForm = {...row};
      this.drugOpen = true;
      this.drugTitle = "修改药品";
    },
    /** 提交药品表单 */
    submitDrugForm() {
      this.$refs["drugForm"].validate(valid => {
        if (valid) {
          this.drugForm.prescribeId = this.form.prescribeId;
          if (this.drugForm.drugId != undefined) {
            // 修改
            updatePrescribeDrug(this.drugForm).then(response => {
              this.$message.success("修改成功");
              this.drugOpen = false;
              // 确保刷新完成
              this.getDrugList();
            }).catch(error => {
              // 发生错误时也要确保能正常操作
              console.error('修改药品失败:', error);
            });
          } else {
            // 新增
            addPrescribeDrug(this.drugForm).then(response => {
              this.$message.success("新增成功");
              this.drugOpen = false;
              // 新增成功后回到第一页并刷新
              this.drugQueryParams.pageNum = 1;
              this.getDrugList();
            }).catch(error => {
              console.error('新增药品失败:', error);
            });
          }
        }
      });
    },
    /** 删除药品按钮操作 */
    handleDeleteDrug(row) {
      this.$confirm('是否确认删除药品"' + row.drugName + '"?').then(() => {
        return deletePrescribeDrug(row.drugId);
      }).then(() => {
        this.$message.success("删除成功");

        // 处理删除后的分页逻辑
        // 如果当前页只有一条数据,且不是第一页,则页码减1
        if (this.drugList.length === 1 && this.drugQueryParams.pageNum > 1) {
          this.drugQueryParams.pageNum--;
        }

        // 刷新药品列表
        this.getDrugList();
      }).catch(error => {
        if (error !== 'cancel') {
          console.error('删除药品失败:', error);
        }
      });
    },
    /**
     * 获取医生建议信息 (修改版)
     * @param {string|number} userId - 用户ID
     * @returns {Promise<void>}
     */
    fetchDoctorAdviceInfo(userId) {
      return getCollectionByUserId(userId)
        .then(res => {
          const data = res.data;
          // 提取 doctorAdvice 字段
          if (data && typeof data.doctorAdvice === 'string') {
            this.doctorAdviceContent = data.doctorAdvice;
          } else {
            this.doctorAdviceContent = ''; // 如果没有或不是字符串，则清空
            this.$message.info("暂无医生建议内容。");
          }

        })
        .catch(err => {
          console.error("获取医生建议信息失败:", err);
          this.$message.error("获取医生建议信息失败");
          this.doctorAdviceContent = ''; // 出错时也清空内容
        });
    },

    /**
     * 打开医生建议弹窗的方法
     */
    openDoctorAdviceDialog() {
      // 确保有 userId 和 prescribeId
      const userId = this.form.userId;
      const prescribeId = this.form.prescribeId;

      if (!prescribeId) {
        this.$message.warning("请先保存或加载处方信息。");
        return;
      }

      if (!userId) {
        this.$message.warning("缺少患者用户ID。");
        return;
      }
      // 先清空之前的内容，避免显示旧数据
      this.doctorAdviceContent = '';
      this.fetchDoctorAdviceInfo(userId)
        .then(() => {
          // API 调用成功后，打开弹窗
          this.doctorAdviceDialogVisible = true;
        })
        .catch((error) => {
          console.error("打开医生建议弹窗过程中发生错误:", error);
        });
    },
    /** 患者信息采集详情页面 */
    openCollectionInfo() {
      if (!this.form.userId) {
        this.$message.warning("患者ID未填写！");
        return;
      }
      this.collectionDialogVisible = true;
    },
    // 表单重置
    // 表单重置
    reset() {
      this.form = {
        prescribeId: undefined,
        prescribeCode: undefined,
        prescribeType: 1,
        inquiryOrderId: undefined,
        storeOrderId: undefined,
        orderCode: undefined,
        patientId: undefined,
        userId: undefined,
        patientName: undefined,
        patientAge: undefined,
        patientGender: "1",
        patientTel: undefined,
        weight: undefined,
        isHistoryAllergic: undefined,
        historyAllergic: undefined,
        diagnose: undefined,
        doctorId: undefined,
        doctorName: undefined,
        status: 0,
        remark: undefined
      };
      this.resetForm("form");

      // 重置后清除验证状态
      this.$nextTick(() => {
        if (this.$refs["form"]) {
          this.$refs["form"].clearValidate();
        }
      });
    },
    // 药品表单重置
    resetDrugForm() {
      this.drugForm = {
        drugId: undefined,
        prescribeId: undefined,
        drugName: undefined,
        drugSpec: undefined,
        usageMethod: undefined,
        usageFrequencyUnit: undefined,
        usagePerUseCount: undefined,
        usagePerUseUnit: undefined,
        usageDays: undefined,
        drugPrice: undefined,
        drugNum: undefined,
        drugUnit: undefined,
        instructions: undefined
      };
      this.resetForm("drugForm");
    }
  }
};
</script>

<style scoped>
.drug-container {
  padding: 10px;
}

.detail-container {
  padding: 20px;
}

.detail-item {
  margin-bottom: 10px;
  display: flex;
}

.detail-item .label {
  min-width: 100px;
  font-weight: bold;
}

.id-card-info {
  display: flex;
  flex-direction: column;
}

.id-card-image {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.id-card-detail {
  margin-top: 20px;
}

/*------------这里开始是Tab3字体样式------------------*/
.info-item {
  display: flex;
  align-items: center;
  min-height: 32px;
}

.info-item .label {
  font-family: SimHei, "Microsoft YaHei", sans-serif;
  /* 黑体优先 */
  font-weight: bold;
  color: #333;
}

.info-item .value {
  color: #666;
  margin-left: 6px;
}

/* -----------这里是Tab3字体样式结束-----------------*/
</style>
