<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="75px">
      <el-form-item label="是否医保" prop="isInsured">
        <el-select style="width: 100px" v-model="queryParams.isInsured" placeholder="是否医保" clearable>
          <el-option v-for="dict in healthcare_os_insured" :key="dict.value" :label="dict.label"
                     :value="parseInt(dict.value)"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="false" label="数值""�? prop="value">
        <el-input v-model="queryParams.value" placeholder="请输入数值"�? clearable @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="学号/工号" prop="studentId">
        <el-input v-model="queryParams.studentId" placeholder="请输入学�?工号" clearable @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入患者姓�? clearable @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="医生名字" prop="doctorName">
        <el-input v-model="queryParams.doctorName" placeholder="请输入医生名�? clearable @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="临床诊断" prop="diagnosis">
        <el-input v-model="queryParams.diagnosis" placeholder="请输入临床诊�? clearable @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="就诊时间">
      <el-date-picker
      v-model="outpatientTime"
      type="daterange"
      range-separator="�?
      start-placeholder="开始日�?
      end-placeholder="结束日期"
      clearable
      @change="changeTime"
      />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
                   v-hasPermi="['os:patientDiagnosis:add']">接诊
        </el-button>
      </el-col>
      <el-col v-if="false" :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['os:patientDiagnosis:edit']">修改
        </el-button>
      </el-col>
      <el-col v-if="false" :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
                   v-hasPermi="['os:patientDiagnosis:remove']">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
                   v-hasPermi="['os:patientDiagnosis:export']">导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="patientDiagnosisList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!-- <el-table-column label="编号" align="center" prop="id"/> -->
      <el-table-column label="学号/工号" align="center" prop="studentId"/>
      <el-table-column label="患者姓�? align="center" prop="name"/>
      <el-table-column label="是否医保" align="center" prop="isInsured">
        <template #default="scope">
          <dict-tag :options="healthcare_os_insured" :value="scope.row.isInsured"/>
        </template>
</el-table-column>
<el-table-column label="病人类型" align="center" prop="patientType">
        <template #default="scope">
          <dict-tag :options="healthcare_os_patient_type" :value="scope.row.patientType"/>
        </template>
      </el-table-column>
<el-table-column label="就诊时间" align="center" prop="outpatientTime" />
<el-table-column label="就诊地址" align="center" prop="storeroomName" />
<el-table-column label="临床诊断" align="center" prop="diagnosis" />
<el-table-column label="医生名字" align="center" prop="doctorName" />
<el-table-column label="判断类型" align="center" prop="diagnosisType">
        <template #default="scope">
          <dict-tag :options="healthcare_os_diagnosis_type" :value="scope.row.diagnosisType"/>
        </template>
      </el-table-column>
<el-table-column label="发药状�? align=" center" prop="status">
        <template #default="scope">
          <dict-tag :options="healthcare_os_diagnosis_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- 修改 -->
          <el-button v-if="scope.row.status == 2 || scope.row.status == 3" link type="primary" icon="Edit"
                     @click="handleUpdate(scope.row)" v-hasPermi="['os:patientDiagnosis:update']">修改
          </el-button>
          <!-- check 查看  Button   -->
          <el-button link type="primary" icon="Search" @click="checkButton(scope.row)"
                     v-hasPermi="['os:patientDiagnosis:getInfo']">查看
          </el-button>
          <!-- 删除  commonDictionary -->
          <el-button v-if="scope.row.status == 3" link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['os:patientDiagnosis:remove']">删除
          </el-button>
          <!-- 打印及下方调�?-> 知无涯添�?-->
          <el-button v-if="scope.row.status == 1" link type="primary" icon="Printer" @click="handlePrint(scope.row)"
                     v-hasPermi="['os:patientDiagnosis:print']">打印
          </el-button>
        </template>
      </el-table-column>
</el-table>

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

<!-- 添加或修改患者诊断信息对话框 -->
<!-- 控制  -->
<el-dialog :title="title" v-model="open" :width="`${(width = '100%')}`" append-to-body>
  <el-form ref="patientDiagnosisRef" :model="form" :rules="rules" label-width="100px">
    <el-row :gutter="20">
          <!-- 病人信息 -->
          <el-col :span="12">
            <!-- 患者信�?change -->
            <el-col :span="24">
              <!--  -->
              <el-row>
                <el-col :span="12">
                  <!-- :disabled="true" -->
                  <el-form-item label="就诊人类�? prop="patientType">
                    <el-select v-model="form.patientType" placeholder="请选择就诊人类�?>
                      <el-option v-for="dict in healthcare_os_patient_type" :key="dict.value" :label="dict.label"
                                 :value="parseInt(dict.value)"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="学号/工号" prop="studentId">
                    <!-- change   -->
                    <el-input ref="studentIdRef" v-model="form.studentId" placeholder="请输入学�?工号"
                              @click="selectPatient()"/>
                  </el-form-item>
                </el-col>
              </el-row>
    <!--  -->
    <el-row>
                <el-col :span="12">
                  <el-form-item label="患者姓�? prop="name">
                    <el-input v-model="form.name" placeholder="请输入患者姓�? clearable/>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="诊断类型" prop="diagnosisType">
                    <el-select v-model="form.diagnosisType" placeholder="请选择诊断类型类型">
                      <el-option v-for="dict in healthcare_os_diagnosis_type" :key="dict.value" :label="dict.label"
                                 :value="parseInt(dict.value)"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
    <el-row>
                <el-col :span="12">
                  <el-form-item label="性别" prop="gender">
                    <el-select v-model="form.gender" placeholder="请输入性别" clearable>
                      <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label"
                                 :value="dict.value"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="年龄" prop="age">
                    <el-input v-model="form.age" clearable placeholder="请输入年�?/>
                  </el-form-item>
                </el-col>
              </el-row>
    <el-row v-if="form.patientType === 0">
                <el-col :span="12">
                  <el-form-item label="专业" prop="major">
                    <el-input v-model="form.major" clearable placeholder="请输入专�?/>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="班级" prop="classInfo">
                    <el-input v-model="form.classInfo" clearable placeholder="请输入班�?/>
                  </el-form-item>
                </el-col>
              </el-row>
    <el-row>
                <el-col :span="12">
                  <el-form-item label="电话" prop="phone">
                    <el-input v-model="form.phone" clearable placeholder="请输入电�?/>
                  </el-form-item>
                </el-col>
                <el-col v-if="form.patientType === 0" :span="12">
                  <el-form-item label="辅导�? prop="counselor">
                    <el-input v-model="form.counselor" clearable placeholder="请输入辅导员"/>
                  </el-form-item>
                </el-col>
                <el-col v-if="form.patientType === 1 || form.patientType === 2" :span="12">
                  <el-form-item label="部门" prop="department">
                    <el-input v-model="form.department" clearable placeholder="请输入部�?/>
                  </el-form-item>
                </el-col>
              </el-row>
    <el-row>
                <el-col :span="12">
                  <el-form-item label="是否医保" prop="isInsured">
                    <el-select v-model="form.isInsured"
                               placeholder="是否医保"
                               clearable
                               @change="handleInsuranceChange"
                               @clear="handleInsuranceClear"
                               :disabled="insuranceDisabled">
                      <el-option
                          v-for="dict in healthcare_os_insured"
                          :key="dict.value"
                          :label="dict.label"
                          :value="parseInt(dict.value)"
                          @click="calculationWholeTotal()">
                      </el-option>
                    </el-select>
                    <el-icon
                        v-if="form.isInsured === 0"
                        style="color: #67C23A; margin-left: 8px; position: absolute; right: 30px;"
                        :size="20">
                      <Check/>
                    </el-icon>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item v-if="form.isInsured == 0" label="报销比率"
                                prop="value">
                    <el-input-number
                        v-model="form.value"
                        :step="0.1"
                        :precision="2"
                        :min="0"
                        :max="100"
                        :formatter="insuranceFormatter"
                        :parser="insuranceParser"
                        @change="calculationWholeTotal()"
                        placeholder="请输入报销比率"/>   <span>%</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="已报销总额/限额">
                    <span>
                      ￥{{ Number(historyReimbursement || 0).toFixed(2) }} / ￥{{ Number(reimbursementLimit).toFixed(2) }}
                    </span>
                  </el-form-item>
                </el-col>
              </el-row>
    </el-col>
    <el-col :span="24">
      <el-form-item label="主诉" prop="chiefComplaint" class="complaint-form-item">
        <div class="complaint-input">
          <el-autocomplete v-model="form.chiefComplaint" :fetch-suggestions="queryComplaintSuggestions"
            placeholder="请输入主诉内容或选择常用主诉" clearable @select="selectComplaint" @clear="clearComplaint"
            @focus="handleComplaintFocus" style="width: 85%" :loading="loadingComplaints" class="complaint-autocomplete"
            popper-class="complaint-popper">
            <template #default="{ item }">
                      <div class="complaint-option">
                        <span class="complaint-label">{{ item.label }}</span>
                        <span v-if="!item.isCustom" class="complaint-hint">
                          ({{ item.currentHistory ? item.currentHistory.substring(0, 20) + '...' : '无现病史' }})
                        </span>
                      </div>
                    </template>
            <template #prefix>
                    </template>
          </el-autocomplete>
        </div>
      </el-form-item>
    </el-col>
    <el-col :span="24">
      <el-form-item label="现病�? prop=" presentIllness">
        <el-input v-model="form.presentIllness" type="textarea" placeholder="请输入内�?/>
              </el-form-item>
            </el-col>
            <el-col :span=" 24">
          <el-form-item label="既往�? prop=" pastHistory">
            <el-input v-model="form.pastHistory" type="textarea" placeholder="请输入内�?/>
              </el-form-item>
            </el-col>
            <el-col :span=" 24">
              <el-form-item label="临床诊断" prop="diagnosis">
                <el-input v-model="form.diagnosis" type="textarea" placeholder="请输入内�?/>
              </el-form-item>
            </el-col>
            <el-col :span=" 24">
                  <el-form-item label="医嘱事项" prop="medicalAdvice">
                    <el-input v-model="form.medicalAdvice" type="textarea" placeholder="请输入内�?/>
              </el-form-item>
            </el-col>
          </el-col>
          <!-- 病人病历 -->
          <el-col :span=" 12">
                      <h3>就诊记录</h3>
                      <!-- border height="250" -->
                      <el-table :data="nameDiagnosisList" style="width: 100%" max-height="1000px">
              <el-table-column prop="outpatientTime" label="就诊时间" width="180">
              </el-table-column>
              <el-table-column prop="chiefComplaint" label="主诉" width="180">
              </el-table-column>
              <el-table-column prop="status" label="状�?>
                <template #default="scope">
                  <dict-tag :options="healthcare_os_diagnosis_status" :value="scope.row.status"/>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button @click="checkInformation(scope.row.id)" link type="primary" icon="Edit">查看</el-button>
                </template>
              </el-table-column>
            </el-table>
    </el-col>
    </el-row>
    <!-- os:patientDiagnosis:conventionalPrescription -->
    <el-divider content-position="center"> 处方详情</el-divider>
    <el-row class="prescriptionAdd">
          <el-button type="primary" plain size="mini" @click="addPrescriptionButton()">新增处方</el-button>
        </el-row>
    <!-- 处方 -->
    <el-row v-for="(index, item) in form.prescriptionDetailsList" :key="item">
          <el-row :gutter="10" class="mb8">
            <el-button v-if="false" type="primary" plain size="mini"
                       @click="prescriptionAddDruyAddChoice()">扫描添加
            </el-button>
            <!-- 6 -->
            <el-button type="primary" plain size="mini" @click="conventionalPrescriptionButton(item)"
                       v-hasPermi="['os:patientDiagnosis:conventionalPrescription']">常规处方
            </el-button>
            <!-- 6 -->
            <el-button type="primary" plain size="mini" @click="addDrugButton(item)">添加药品</el-button>
            <!-- 6 -->
            <el-button type="primary" plain size="mini" @click="removePrescription(item)">删除处方</el-button>
          </el-row>
    <!-- border -->
    <el-table :data="form.prescriptionDetailsList[item]" style="width: 100%" class="prescription">
            <el-table-column prop="name" label="编号" width="100">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <!-- 药品名称 -->
            <el-table-column prop="medicineName" label="药名" min-width="260">
              <template #default="scope">
                <el-form-item label-width="0px" :prop="`prescriptionDetailsList.${item}.${scope.$index}.medicineName`"
                              :rules="[
                    {
                      required: true,
                      message: '药名不能为空',
                      trigger: 'blur',
                    },
                  ]">
                  <!--  一�?隐藏 �?  v-if="false"  -->
                  <el-select v-model="form.prescriptionDetailsList[item][scope.$index].medicineName
                    " filterable placeholder="请选择" v-if="false">
                    <el-option v-for="item1 in druyNameList" :key="item1" :label="item1.medicineName"
                               :value="item1.medicineName" @click="choiceDruyName(item, scope.$index, item1)">
                    </el-option>
                  </el-select>
                  <!-- 输入框弹�? focus  -->
                  <!--  一�?隐藏 �?v-if="false"  -->
                  <el-input v-if="false" v-model="form.prescriptionDetailsList[item][scope.$index].medicineName
                    " @focus="drugArchivesBulletFrameOperation(item, scope.$index)"></el-input>
                  <!-- 输入框弹�?药品 �?批次 库存   focus -->
                  <el-input v-model="form.prescriptionDetailsList[item][scope.$index].medicineName
                    " @click="selectDrugPriceInputButton(item, scope)"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="batch" label="批次" min-width="170">
              <template #default="scope">
                <el-form-item label-width="0px" :prop="`prescriptionDetailsList.${item}.${scope.$index}.batch`">
                  <el-input :disabled="true" v-model="form.prescriptionDetailsList[item][scope.$index].batch
                    "></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="expiryDate" label="有效�? min-width="150">
              <template #default="scope">
                <el-form-item label-width="0px" :prop="`prescriptionDetailsList.${item}.${scope.$index}.expiryDate`">
                  <el-input :disabled="true" v-model="form.prescriptionDetailsList[item][scope.$index].expiryDate
                    "></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <!-- 规格  -->
            <el-table-column prop="specification" label="规格" min-width="220">
              <template #default="scope">
                <el-form-item label-width="0px" :prop="`prescriptionDetailsList.${item}.${scope.$index}.specification`"
                              :rules="[
                    {
                      required: true,
                      message: '规格不能为空',
                      trigger: 'blur',
                    },
                  ]">
                  <el-input v-model="form.prescriptionDetailsList[item][scope.$index].specification
                    "></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <!-- 用法 -->
            <el-table-column prop="usageValue" label="用法" width="120">
              <template #default="scope">
                <el-form-item label-width="0px" :prop="`prescriptionDetailsList.${item}.${scope.$index}.usageValue`"
                              :rules="[
                    {
                      required: true,
                      message: '用法不能为空',
                      trigger: 'blur',
                    },
                  ]">
                  <el-select v-model="form.prescriptionDetailsList[item][scope.$index].usageValue" filterable
                             placeholder="请选择">
                    <el-option v-for="item in commonUsageList" :key="item.value" :label="item.value"
                               :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <!-- 用量 -->
            <el-table-column prop="dosageValue" label="一次使用的�? width="200">
              <template #default="scope">
                <el-row>
                  <el-col :span="12">
                    <el-form-item label-width="0px"
                                  :prop="`prescriptionDetailsList.${item}.${scope.$index}.dosageValue`" :rules="[
                        {
                          required: true,
                          message: '用量不能为空',
                          trigger: 'blur',
                        },
                        {
                          pattern: /^\S+.*$/,
                          message: '开头有空格',
                          trigger: 'blur',
                        },
                        {
                          pattern: /^(?:\d+(?:\.\d+)?|\.\d+)$/,
                          message: '请输入一个有效的�?,
                          trigger: 'blur',
                        },
                        {
                          validator: checkValueRules,
                          trigger: 'blur',
                        },
                      ]">
                      <el-input v-model="form.prescriptionDetailsList[item][scope.$index].dosageValue
                        " @input="calculationTotal(item, scope.$index)"/>
                    </el-form-item>
                  </el-col>
                  <!-- 单位 -->
                  <el-col :span="12">
                    <el-form-item label-width="0px" :prop="`prescriptionDetailsList.${item}.${scope.$index}.splitUnit`"
                                  :rules="[
                        {
                          required: true,
                          message: '单位不能为空',
                          trigger: 'blur',
                        },
                      ]">
                      <el-select v-model="form.prescriptionDetailsList[item][scope.$index].splitUnit
                        " filterable placeholder="请选择">
                        <el-option v-for="dict in healthcare_packaging_unit" :key="dict.value" :label="dict.label"
                                   :value="dict.value">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
              </template>
            </el-table-column>
            <el-table-column prop="frequency" label="一天使用的次数" width="140">
              <template #default="scope">
                <el-form-item label-width="0px" :prop="`prescriptionDetailsList.${item}.${scope.$index}.frequency`"
                              :rules="[
                    {
                      required: true,
                      message: '次数不能为空',
                      trigger: 'blur',
                    },
                  ]">
                  <el-select v-model="form.prescriptionDetailsList[item][scope.$index].frequency" filterable
                             placeholder="请选择">
                    <el-option v-for="item1 in frequencyList" :key="item1.value" :label="item1.name"
                               :value="parseInt(item1.value)" @click="calculationTotal(item, scope.$index)">
                    </el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="eatingTime" label="使用时间" width="120">
              <template #default="scope">
                <el-form-item label-width="0px" :prop="`prescriptionDetailsList.${item}.${scope.$index}.eatingTime`"
                              :rules="[
                    {
                      required: true,
                      message: '使用时间不能为空',
                      trigger: 'blur',
                    },
                  ]">
                  <el-select v-model="form.prescriptionDetailsList[item][scope.$index].eatingTime" filterable
                             placeholder="请选择">
                    <el-option v-for="item in eatingTimeList" :key="item.value" :label="item.value" :value="item.value">
                    </el-option>
                  </el-select>

                </el-form-item>
              </template>
            </el-table-column>
            <!-- 使用 -->
            <!-- <el-table-column prop="eatingDays" label="使用天数" width="120">
              <template #default="scope">
                <el-form-item label-width="0px" :prop="`prescriptionDetailsList.${item}.${scope.$index}.eatingDays`" :rules="[
                    {
                      required: true,
                      message: '使用天数不能为空',
                      trigger: 'blur',
                    },
                    {
                      pattern: /^\S+.*$/,
                      message: '开头有空格',
                      trigger: 'blur',
                    },
                    {
                      pattern: /^-?\d+$/,
                      message: '请输入一个有效的整数',
                      trigger: 'blur',
                    },
                    {
                      pattern: /^(?!0\d)\d+$/,
                      message: '请输入一个有效的整数',
                      trigger: 'blur',
                    },
                    {
                      validator: checkValueRules,
                      trigger: 'blur',
                    },
                  ]">
                  <el-input @input="calculationTotal(item, scope.$index)" v-model="form.prescriptionDetailsList[item][scope.$index].eatingDays" />
                </el-form-item>
              </template>
            </el-table-column> -->
            <!-- 总量 1 可以 �? -->
            <el-table-column prop="totalQuantity" label="总量" width="150">
              <template #default="scope">
                <!--  进行 修改 进行 隐藏 form.prescriptionDetailsList[item][scope.$index].isSplit == 'Y' -->
                <el-row v-if="false">
                  <el-col :span="8">
                    <el-form-item label-width="0px"
                                  :prop="`prescriptionDetailsList.${item}.${scope.$index}.totalQuantity`" :rules="[
                        {
                          required: true,
                          message: '总量不能为空',
                          trigger: 'blur',
                        },
                        {
                          pattern: /^\S+.*$/,
                          message: '开头有空格',
                          trigger: 'blur',
                        },
                        {
                          pattern: /^(?:\d+(?:\.\d+)?|\.\d+)$/,
                          message: '请输入一个有效的�?,
                          trigger: 'blur',
                        },
                        {
                          validator: checkValueRules,
                          trigger: 'blur',
                        },
                      ]">
                      {{ form.prescriptionDetailsList[item][scope.$index].totalQuantity }}
                    </el-form-item>
                  </el-col>
                  <el-col :span="14">
                    <el-form-item label-width="0px"
                                  :prop="`prescriptionDetailsList.${item}.${scope.$index}.packageUnit`" :rules="[
                        {
                          required: true,
                          message: '单位不能为空',
                          trigger: 'blur',
                        },
                      ]">
                      <el-select v-model="form.prescriptionDetailsList[item][scope.$index].packageUnit
                        " filterable placeholder="请选择">
                        <el-option v-for="dict in healthcare_packaging_unit" :key="dict.value" :label="dict.label"
                                   :value="dict.value">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <!-- splitUnit  packageUnit-->
                <!-- 总量 2  �?可以 拆分   -->
                <el-row>
                  <el-col :span="8">
                    <el-form-item label-width="0px"
                                  :prop="`prescriptionDetailsList.${item}.${scope.$index}.totalQuantity`" :rules="[
                        {
                          required: true,
                          message: '总量不能为空',
                          trigger: 'blur',
                        },
                        {
                          pattern: /^\S+.*$/,
                          message: '开头有空格',
                          trigger: 'blur',
                        },
                        {
                          pattern: /^(?:\d+(?:\.\d+)?|\.\d+)$/,
                          message: '请输入一个有效的�?,
                          trigger: 'blur',
                        },
                        {
                          validator: checkValueRules,
                          trigger: 'blur',
                        },
                      ]">
                      <el-input v-model="form.prescriptionDetailsList[item][scope.$index].totalQuantity
                        " prescription="请输入总量" @input="calculationTotal(item, scope.$index)"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="14">
                    <el-form-item label-width="0px"
                                  :prop="`prescriptionDetailsList.${item}.${scope.$index}.packageUnit`" :rules="[
                        {
                          required: true,
                          message: '单位不能为空',
                          trigger: 'blur',
                        },
                      ]">
                      <el-select v-model="form.prescriptionDetailsList[item][scope.$index].packageUnit
                        " filterable placeholder="请选择">
                        <el-option v-for="dict in healthcare_packaging_unit" :key="dict.value" :label="dict.label"
                                   :value="dict.value">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
              </template>
            </el-table-column>
            <!--  -->
            <el-table-column prop="unitPrice" label="单价/�?可�?" width="120">
              <template #default="scope">
                <!--  selectDrugPriceInputButton  selectDrugPriceInput -->
                <el-form-item label-width="0px" :prop="`prescriptionDetailsList.${item}.${scope.$index}.unitPrice`"
                              :rules="[
                    {
                      required: true,
                      message: '单价不能为空',
                      trigger: 'blur',
                    },
                  ]">
                  <el-button width="100%" @click="selectDrugPriceInputButton(item, scope)">
                    {{ form.prescriptionDetailsList[item][scope.$index].unitPrice }}
                  </el-button>
                </el-form-item>
                <!--  -->
                <el-form-item v-if="false" label-width="0px"
                              :prop="`prescriptionDetailsList.${item}.${scope.$index}.unitPrice`" :rules="[
                    {
                      required: true,
                      message: '单价不能为空',
                      trigger: 'blur',
                    },
                  ]">
                  <el-button width="100%">
                    {{ form.prescriptionDetailsList[item][scope.$index].unitPrice }}
                  </el-button>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="totalPrice" label="总价" width="120">
              <template #default="scope">
                <el-form-item label-width="0px" :prop="`prescriptionDetailsList.${item}.${scope.$index}.totalPrice`"
                              :rules="[
                    {
                      required: true,
                      message: '总价不能为空',
                      trigger: 'blur',
                    },
                  ]">
                  {{
                    form.isInsured === 0
                      ? (
                          Number(form.prescriptionDetailsList[item][scope.$index].totalPrice || 0) *
                          (1 - Number(form.value || 0) / 100)
                        ).toFixed(2)
                      : form.prescriptionDetailsList[item][scope.$index].totalPrice
                  }}
                  �?
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="remarks" label="备注" min-width="120">
              <template #default="scope">
                <el-form-item label-width="0px">
                  <el-input v-model="form.prescriptionDetailsList[item][scope.$index].remarks"/>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="100" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button link type="primary" icon="Edit" @click="removeDrug(item, scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
    </el-row>
    <!-- 展示结算金额与原始总额 -->
    <el-row>
          <el-col :span="24">
            <div style="text-align: right; margin-top: 20px;color: red">
              <span>
                应收金额:{{ form.isInsured === 0 ? Number(patientPay).toFixed(2) : Number(totalPriceSum).toFixed(2) }} �?
              </span>
              <span style="margin-left: 16px; color: #666">
                处方总金�?{{ Number(totalPriceSum).toFixed(2) }} �?
              </span>
              <span v-if="form.isInsured === 0" style="margin-left: 16px; color: #333">
                预计报销:{{ Number(currentReimbursement).toFixed(2) }} �?
              </span>
            </div>
          </el-col>
        </el-row>
  </el-form>
  <template #footer>
    <div class="dialog-footer">
      <el-button type="primary" v-if="form.status != 2" @click="saveDiagnosisButton()">�?�?/el-button>
        <el-button type="primary" v-if="form.status == 3" @click="saveAddDiagnosisButton()">�?�?/el-button>
          <el-button type="primary" v-if="form.status != 3" @click="submitForm">�?�?/el-button>
            <el-button @click="cancel">�?�?/el-button>
    </div>
  </template>
</el-dialog>
<!-- 患者档�?-->
<PatientDossier ref="patientDossierRef" :title="ttto" :width="'80%'" :open="patientOpen" :patientQuery="patientQuery"
  @select-value="select" @input-query="updatePatientType()" />
<!-- 药品库存 v-model="drugOpen" -->
<DrugInventory ref="drugInventoryRef" :style="{ width: '100%' }" :title="druyTitle" :open="drugOpen"
  :medicineName="medicineName" :queryParams="queryParamsDrugInventory" @input-medicine-name="updateMedicineName()"
  @select-value="obtainDrugInventoryData" @input-queryParams="drugInventoryInputQueryParams()" />
<!-- 常规处方 -->
<ConventionalPrescription v-hasPermi="['os:patientDiagnosis:conventionalPrescription']"
  :title="conventionalPrescriptionTitle" v-model="conventionalPrescriptionOpen"
  @select-value="conventionalPrescriptionSelect" />
<!-- 药品档案 -->
<DrugArchives ref="childComponentRef" :widthBf="sdada" :title="titleDrugArchives" :openAssembly="openDrugArchives"
  :queryParams="queryParamsDrugArchives" :controlQuery="controlQueryDrugArchives" :controlData="controlDataDrugArchives"
  @input-data="paginationDataFq()" @select-value="selectDrugData" />
<!-- 患者诊断信�?-->
<DiagnosisInformation ref="diagnosisInformationRef" :style="styleDiagnosisInformation"
  :controlData="controlDataDiagnosisInformation" />
</div>
</template>


<script setup name="PatientDiagnosis">
import { onActivated, ref, watch } from 'vue'


import { getHealthcareOsPatientInfo } from '@/api/healthcare/outpatientService/healthcareOsPatientInfo'
import {
  addPatientDiagnosis, delPatientDiagnosis,
  getHistoryReimbursement,
  getPatientDiagnosis, listPatientDiagnosis,
  saveAddDiagnosis, saveDiagnosis, saveUpdate, updatePatientDiagnosis, verifyInsuranceStatus
} from '@/api/healthcare/outpatientService/patientDiagnosis'
// healthcare/outpatientService/patientDiagnosis
// src\components\Healthcare\OutpatientService\PatientDossier\index.vue
//  healthcareOsComplaints  DrugArchives
import {
  listCommonUsage,
  listEatingTime,
  listFrequency
} from '@/api/healthcare/outpatientService/healthcareOsConventionalValue'

const { proxy } = getCurrentInstance()
// 在setup脚本中添�?
onActivated(() => {
  // 当组件被激活时刷新数据
  getList()
})
const dsada = ref()

// 患者类�?
const { healthcare_os_patient_type } = proxy.useDict('healthcare_os_patient_type')
// os_patient_type
const { healthcare_os_diagnosis_type } = proxy.useDict('healthcare_os_diagnosis_type')
// 医药包装单位
const { healthcare_packaging_unit } = proxy.useDict('healthcare_packaging_unit')
//
const { sys_user_sex } = proxy.useDict('sys_user_sex')
//
const { healthcare_dose_unit } = proxy.useDict('healthcare_dose_unit')
// healthcare_os_insured  是否 医保
const { healthcare_os_insured } = proxy.useDict('healthcare_os_insured')
// healthcare_os_diagnosis_status    诊断状�?
const { healthcare_os_diagnosis_status } = proxy.useDict('healthcare_os_diagnosis_status')

// 系统 �?是否
const { sys_yes_no } = proxy.useDict('sys_yes_no')

// 获取 常用用法
common()
const commonUsageList = ref([]) // 用法
const eatingTimeList = ref([]) //  食用时间
const frequencyList = ref([]) //   次数
const totalPriceSum = ref(0) //所有药品总价�?
// 历史累计医保报销金额与限额、当前报销估算
const historyReimbursement = ref(0)
const reimbursementLimit = ref(300)
const currentReimbursement = ref(0)
const patientPay = ref(0)
function common() {
  listCommonUsage().then(res => {
    commonUsageList.value = res.rows
  })
  listEatingTime().then(res => {
    eatingTimeList.value = res.rows
  })
  listFrequency().then(res => {
    frequencyList.value = res.rows
  })
}

//
const patientDiagnosisList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')

//
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    patientId: null,
    diagnosisType: null,
    isInsured: null,
    value: null,
    studentId: null,
    name: null,
    patientType: null,
    chiefComplaint: null,
    presentIllness: null,
    pastHistory: null,
    diagnosis: null,
    medicalAdvice: null,
    doctorName: null,
    status: null,
    startTime: null,
    endTime: null
  },
  // vue3 �?封装 的好 �?检�?写法   pattern: /^1(3|4|5|7|8|9)\d{9}$/,
  rules: {
    patientType: [
      {
        required: true,
        message: '就诊类型不能为空',
        trigger: 'change'
      }
    ],
    diagnosisType: [
      {
        required: true,
        message: '判断类型不能为空',
        trigger: 'change'
      }
    ],
    studentId: [
      { required: true, message: '学号/工号不能为空', trigger: 'blur' },
      { pattern: /^\d+(\.\d+)?$/, message: '请输入一个有效的正数', trigger: 'blur' },
      { pattern: /^\S+.*$/, message: '开头有空格', trigger: 'blur' }
    ],
    name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
    phone: [{ required: false, message: '手机不能为空', trigger: 'blur' }],
    isInsured: [{ required: true, message: '是否医保不能为空', trigger: 'blur' }],
    value: [
      { required: true, message: '报销比率不能为空', trigger: 'blur' },
      { pattern: /^\d+(\.\d+)?$/, message: '请输入一个有效的小数', trigger: 'blur' },
      {
        pattern: /^(?:\d+(?:\.\d+)?|\.\d+)$/,
        message: '请输入一个有效的小数',
        trigger: 'blur'
      },
      {
        pattern: /^\d+(\.\d{0,2})?$/,
        message: '最多两位小数',�?,
        trigger: 'blur'
      },
      {
        pattern: /^\S+.*$/,
        message: '开头有空格',
        trigger: 'blur'
      },
      {pattern: /^\S+.*$/, message: '开头有空格', trigger: 'blur'}
    ],
    prescriptionDetailsList: [{required: true, message: '处方不能为空', trigger: 'blur'}]
  }
})

// 方法 没有 �?调用
// 计算所有药品总价�?
function calculationTotalSum(index, index2) {
  const totalPrice = ref(0)
  if (form.value.isInsured == healthcare_os_insured.value[0].value) {
    totalPrice.value = form.value.prescriptionDetailsList[index][index2].totalQuantity * form.value.prescriptionDetailsList[index][index2].unitPrice * form.value.value
  } else {
    totalPrice.value = form.value.prescriptionDetailsList[index][index2].totalQuantity * form.value.prescriptionDetailsList[index][index2].unitPrice
  }

  if (!Number.isNaN(totalPrice.value)) {
    totalPrice.value = totalPrice.value.toFixed(2)
    form.value.prescriptionDetailsList[index][index2].totalPrice = totalPrice.value
  } else {
    form.value.prescriptionDetailsList[index][index2].totalPrice = 0
  }

  // 更新总价�? 进行 再次 计算 
  totalPriceSumF()
}


// 转接 使用 诊断 �?使用 数据 �?   显示 变量 进行 计算 
function totalPriceSumF() {
  // 更新总价�?
  totalPriceSum.value = form.value.prescriptionDetailsList
      .reduce((sum, prescription) => {
        return sum + prescription.reduce((innerSum, drug) => innerSum + parseFloat(drug.totalPrice || 0), 0)
      }, 0)
      .toFixed(2)
}

// 校验 方法
function checkValueRules(rule, value, callback) {
  const num = Number(value)
  const minValue = 0
  const maxValue = 1000
  if (isNaN(num)) {
    callback(new Error('请输入一个数字'))�?))
  } else {
    callback()
  }
}

const {queryParams, form, rules} = toRefs(data)

// 实时联动预计报销与自付金�?放在 form 初始化之�?
watch([
  () => form.value?.value,
  () => form.value?.isInsured,
  () => totalPriceSum.value
], () => {
  const insured = form.value?.isInsured
  const sum = Number(totalPriceSum.value || 0)
  if (insured === 0) {
    const rate = Number(form.value?.value || 0) / 100
    const r = isNaN(rate) ? 0 : rate
    currentReimbursement.value = sum * r
    patientPay.value = (sum - Number(currentReimbursement.value || 0)).toFixed(2)
  } else {
    currentReimbursement.value = 0
    patientPay.value = sum.toFixed(2)
  }
})

const nameDiagnosisList = ref([])

// 患�?�?诊断 �?列表
watch(
    () => form.value.studentId,
    (newValue, odlValue) => {
      if (form.value.studentId != null) {
        listPatientDiagnosis({studentId: newValue}).then(res => {
          nameDiagnosisList.value = res.rows
          console.log('就诊记录', nameDiagnosisList)
        })
      } else {
        nameDiagnosisList.value = []
      }
    }
)
const insuranceDisabled = ref(false)

// 输入百分比的展示与解�?用于 el-input-number)
const insuranceFormatter = (value) => {
  if (value === undefined || value === null || value === '') return ''
  return `${value}%`
}
const insuranceParser = (value) => {
  if (value === undefined || value === null) return 0
  const v = String(value).replace(/%/g, '')
  const num = parseFloat(v)
  return isNaN(num) ? 0 : num
}

const handleInsuranceClear = () => {
  insuranceDisabled.value = false;
  form.value.isInsured = null;
  form.value.value = null;
  currentReimbursement.value = 0;
  // 清空为总价作为自付金额
  patientPay.value = Number(totalPriceSum.value || 0).toFixed(2);
};
// 判断患者是否可用医保方�?
const handleInsuranceChange = async (value) => {
  if (value === null || value === undefined) return;
  try {

    // 获取身份证信息和姓名
    let name = form.value.name;
    let idCard = form.value.idCard;

    if (value === 1) {
      insuranceDisabled.value = false; // 保持可编辑状�?
      return;
    }
    // 如果没有身份证信�?尝试通过 patientId 自动补全
    if (!idCard) {
      if (form.value.patientId) {
        try {
          const p = await getHealthcareOsPatientInfo(form.value.patientId)
          if (p && p.code === 200 && p.data) {
            idCard = p.data.idCard
            name = p.data.name || name
            form.value.idCard = idCard
            form.value.name = name
          }
        } catch (e) {
          // 忽略补全失败
        }
      }
      if (!idCard) {
        form.value.isInsured = 1; // 假设字典�?表示�?
        insuranceDisabled.value = true; // 锁定选择
        proxy.$modal.msgWarning('请先选择患者并获取身份证信�?);
        return;
      }
    }

    // 调用后端接口验证医保状�?
    const res = await verifyInsuranceStatus(idCard, name);
    // 无论是否通过都先重置状�?
    insuranceDisabled.value = false;

    if (res.code === 200) {
      if (res.data === 0) {
        proxy.$modal.msgSuccess('医保可用');
        // 获取历史累计医保报销金额
        if (form.value.patientId) {
          try {
            const his = await getHistoryReimbursement(form.value.patientId, new Date())
            if (his && his.code === 200) {
              historyReimbursement.value = Number(his.data || 0)
            }
          } catch (e) {
            historyReimbursement.value = 0
          }
        }
        // 初步校验当前处方是否可能超限
        if (Array.isArray(form.value.prescriptionDetailsList) && form.value.isInsured === 0 && form.value.value) {
          // 以当前总价和乘报销比率作为本次报销估算
          const rate = Number(form.value.value || 0) / 100
          currentReimbursement.value = Number(totalPriceSum.value || 0) * (isNaN(rate) ? 0 : rate)
          patientPay.value = (Number(totalPriceSum.value || 0) - Number(currentReimbursement.value || 0)).toFixed(2)
          if (historyReimbursement.value + currentReimbursement.value > reimbursementLimit.value) {
            proxy.$modal.msgWarning('累计医保报销超出300元限�?已切换为自费');
            form.value.isInsured = 1;
            insuranceDisabled.value = true;
          }
        }
      } else {
        form.value.isInsured = 1; // 假设字典�?表示�?
        insuranceDisabled.value = true; // 锁定选择
        proxy.$modal.msgWarning('该患者医保未缴费,不可使用医保!');
      }
    }
  } catch (error) {
    form.value.isInsured = 1;
    insuranceDisabled.value = true;
    proxy.$modal.msgError('医保验证失败');

  }
};
// 选择 医生 对应 库房 对应 诊断信息列表
import { getWarehouse } from '@/api/healthcare/warehouse'
import { getUserProfile } from '@/api/system/user.js'

/** 查询患者诊断信息列�?*/
function getList() {
  loading.value = true
  //  获取 医生(用户) 信息
  getUserProfile().then(userInfoRow => {
    // 获取 库房 信息
    getWarehouse(userInfoRow.data.userId).then(res => {
      // 赋�?库房id
      queryParams.value.storeroomId = res.data.storeroomId
      queryParams.value.storeroomName = res.data.storeroomName
      // 获取 患者诊断信息列�?
      listPatientDiagnosis(queryParams.value).then(response => {
        patientDiagnosisList.value = response.rows
        total.value = response.total
        loading.value = false
      })
    })
  })
}

// 获取 库房 信息 存储
const userInfoWarehouse = ref({})

// 获取 库房 信息 �?方法
function getWarehouseInfo() {
  //
  getUserProfile().then(res => {
    getWarehouse(res.data.userId).then(response => {
      userInfoWarehouse.value = response.data
    })
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
  totalPriceSum.value = 0
  currentReimbursement.value = 0
  patientPay.value = 0
}

// 表单重置
function reset() {
  form.value = {
    patientDiagnosisId: null, //  患者诊断信息ID
    patientType: null,
    studentId: null,
    name: null,
    gender: null,
    age: null,
    major: null,
    classInfo: null,
    phone: null,
    counselor: null,
    department: null,
    patientId: null,
    diagnosisType: null,
    isInsured: null,
    value: 0,
    chiefComplaint: null,
    presentIllness: null,
    pastHistory: null,
    diagnosis: null,
    medicalAdvice: null,
    doctorName: null,
    status: null,
    outpatientTime: null,
    storeroomId: null,
    storeroomName: null,
    idCard: null,
    prescriptionDetailsList: []
    // 新增医保状态重�?
  }
  insuranceDisabled.value = false
  // 清空报销相关显示数据,避免出现上一次的�?
  historyReimbursement.value = 0
  currentReimbursement.value = 0
  totalPriceSum.value = 0
  patientPay.value = 0
  proxy.resetForm('patientDiagnosisRef')
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  outpatientTime.value = []
  queryParams.value.startTime = null
  queryParams.value.endTime = null
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加患者诊断信�?
  // 自动触发医保验证
  if (form.value.idCard) {
    handleInsuranceChange()
  }
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getPatientDiagnosis(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = '修改患者诊断信�?
    // 进行 价格 计算 显示 对话�?
    totalPriceSumF()
    // 重新刷新数据
    getList()
    // 编辑场景下自动补齐身份证和历史累计医保金�?
    if (form.value.patientId && !form.value.idCard) {
      getHealthcareOsPatientInfo(form.value.patientId).then(p => {
        if (p && p.code === 200 && p.data) {
          form.value.idCard = p.data.idCard
          if (!form.value.name) form.value.name = p.data.name
        }
      }).catch(() => {})
    }
    if (form.value.patientId) {
      getHistoryReimbursement(form.value.patientId, new Date()).then(his => {
        if (his && his.code === 200) {
          historyReimbursement.value = Number(his.data || 0)
        }
      }).catch(() => {
        historyReimbursement.value = 0
      })
    }
  })
}

/** 提交按钮 */
function submitForm() {
  // 提交前进行医保报销额度最终校�?
  // 先重新计算当前处方可报销金额
  calculationWholeTotal()
  if (form.value.isInsured === 0) {
    const sum = Number(historyReimbursement.value || 0) + Number(currentReimbursement.value || 0)
    if (sum > Number(reimbursementLimit.value || 300)) {
      proxy.$modal.msgWarning('累计医保报销超出300元限�?请调整处方或切换为自�?)
      return
    }
  }
  // console.log('提交按钮', form, form.value)
  //  获取 库房 信息
  getUserProfile().then(res => {
    getWarehouse(res.data.userId).then(response => {
      //
      form.value.storeroomId = response.data.storeroomId
      form.value.storeroomName = response.data.storeroomName
      //
      proxy.$refs['patientDiagnosisRef'].validate(valid => {
        if (valid) {
          if (form.value.patientDiagnosisId != null && form.value.status == 2) {
            updatePatientDiagnosis(form.value).then(response => {
              proxy.$modal.msgSuccess('修改成功')
              open.value = false
              getList()
              totalPriceSum.value = 0
              currentReimbursement.value = 0
              patientPay.value = 0
            })
          } else {
            addPatientDiagnosis(form.value).then(response => {
              proxy.$modal.msgSuccess('新增成功')
              open.value = false
              getList()
              totalPriceSum.value = 0
              currentReimbursement.value = 0
              patientPay.value = 0
            })
          }
        }
      })
    })
  })
}

// saveDiagnosis保存接诊信息
function saveDiagnosisButton() {
  // console.log('保存成功', form, form.value)
  //  获取 库房 信息
  getUserProfile().then(res => {
    getWarehouse(res.data.userId).then(response => {
      // 赋�?
      form.value.storeroomId = response.data.storeroomId
      form.value.storeroomName = response.data.storeroomName
      // 请求 修改 保存
      // proxy.$refs['patientDiagnosisRef'].validate(valid => {
      //   if (valid) {
      //     if (form.value.patientDiagnosisId != null && form.value.status == 3) {
      //       saveUpdate(form.value).then(response => {
      //         proxy.$modal.msgSuccess('修改保存成功')
      //         open.value = false
      //         getList()
      //       })
      //     } else {
      //       saveDiagnosis(form.value).then(response => {
      //         proxy.$modal.msgSuccess('保存成功')
      //         open.value = false
      //         getList()
      //       })
      //     }
      //   }
      // })
      if (form.value.patientDiagnosisId != null && form.value.status == 3) {
        saveUpdate(form.value).then(response => {
          proxy.$modal.msgSuccess('修改保存成功')
          open.value = false
          getList()
          totalPriceSum.value = 0
          currentReimbursement.value = 0
          patientPay.value = 0
        })
      } else {
        saveDiagnosis(form.value).then(response => {
          proxy.$modal.msgSuccess('保存成功')
          open.value = false
          getList()
          totalPriceSum.value = 0
          currentReimbursement.value = 0
          patientPay.value = 0
        })
      }
      // if(form.value.chiefComplaint != '' || form.value.presentIllness != '' || form.value.diagnosis != '' || form.value.medicalAdvice != '') {
      //   proxy.$refs['patientDiagnosisRef'].validate(valid => {
      //   if (valid) {
      //     if (form.value.patientDiagnosisId != null && form.value.status == 3) {
      //       saveUpdate(form.value).then(response => {
      //         proxy.$modal.msgSuccess('修改保存成功')
      //         open.value = false
      //         getList()
      //       })
      //     } else {
      //       saveDiagnosis(form.value).then(response => {
      //         proxy.$modal.msgSuccess('保存成功')
      //         open.value = false
      //         getList()
      //       })
      //     }
      //   }
      // })
      // }
      // else {
      //   if (form.value.patientDiagnosisId != null && form.value.status == 3) {
      //       saveUpdate(form.value).then(response => {
      //         proxy.$modal.msgSuccess('修改保存成功')
      //         open.value = false
      //         getList()
      //       })
      //     } else {
      //       saveDiagnosis(form.value).then(response => {
      //         proxy.$modal.msgSuccess('保存成功')
      //         open.value = false
      //         getList()
      //       })
      //     }
      // }

    })
  })
}

// 修改 保存 库存 操作 �?方法
function saveAddDiagnosisButton() {
  // console.log('保存成功', form, form.value)
  // 获取 选择 �?库房
  //  获取 库房 信息
  getUserProfile().then(res => {
    getWarehouse(res.data.userId).then(response => {
      // 赋�?
      form.value.storeroomId = response.data.storeroomId
      form.value.storeroomName = response.data.storeroomName
      // 请求
      proxy.$refs['patientDiagnosisRef'].validate(valid => {
        if (valid) {
          saveAddDiagnosis(form.value).then(response => {
            proxy.$modal.msgSuccess('添加成功')
            open.value = false
            getList()
            totalPriceSum.value = 0
            currentReimbursement.value = 0
            patientPay.value = 0
          })
        }
      })

    })
  })
}

// 取消 处方  cancel  prescription
function cancelPrescription() {
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal
      .confirm('是否确认删除患者诊断信息编号为"' + _ids + '"的数据项?')
      .then(function () {
        return delPatientDiagnosis(_ids)
      })
      .then(() => {
        getList()
        proxy.$modal.msgSuccess('删除成功')
      })
      .catch(() => {
      })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
      'outpatientService/patientDiagnosis/export',
      {
        ...queryParams.value
      },
      `patientDiagnosis_${new Date().getTime()}.xlsx`
  )
}

//
import { listHealthcareOsComplaints } from '@/api/healthcare/outpatientService/healthcareOsComplaints'
import PatientDossier from '@/components/Healthcare/OutpatientService/PatientDossier/index.vue'
// 患�?档案  组件
// 请求 参数
const patientOpen = ref(false)
const ttto = ref('患者档�?)
const patientDossierRef = ref(null)
//
const studentIdRef = ref(null)
const patientQuery = ref({
  pageNum: 1,
  pageSize: 10,
  patientType: null,
  patientId: null,
  name: null
})

// 更新 患�? 事件 处理 方法 input-patient-type
const updatePatientType = value => {
  // console.log('药品名称', value)
  patientQuery.value = value
}

// 获取 患�?信息 �?方法
function selectPatient() {
  //
  patientDossierRef.value.openDialog()
  ttto.value = '患者档�?
  updatePatientType({
    pageNum: 1,
    pageSize: 10,
    patientType: form.value.patientType,
    studentId: form.value.studentId
  })
}

// 接收 �?数据  患者基�?
const select = value => {
  // console.log('接收子数�?, value)
  // console.log('接收子数�?2:', value.patientType)
  form.value.patientId = value.id
  form.value.patientType = Number(value.patientType)
  form.value.studentId = value.studentId
  form.value.name = value.name
  form.value.gender = value.gender
  form.value.age = value.age
  form.value.major = value.major
  form.value.classInfo = value.classInfo
  form.value.phone = value.phone
  form.value.counselor = value.counselor
  form.value.department = value.department
  form.value.idCard = value.idCard
  // console.log('接收子数�?, form.value)
  //
  studentIdRef.value.blur()
  // console.log('hdsahjk觉得撒打�?, studentIdRef.value.blur())
  //
  patientDossierRef.value.closeDialog()
  // 新增医保状态重�?
  insuranceDisabled.value = false;
  form.value.isInsured = null // 重置医保选择
  form.value.value = null     // 重置报销比率
  // 获取历史医保累计金额
  if (form.value.patientId) {
    getHistoryReimbursement(form.value.patientId, new Date()).then(his => {
      if (his && his.code === 200) {
        historyReimbursement.value = Number(his.data || 0)
      }
    }).catch(() => {
      historyReimbursement.value = 0
    })
  }
}
reset()
// selectComplaints
const queryComplaints = ref({
  complaintName: null
})
const complaintsValue = ref([])
const options = ref([])

/** 查询主诉列表 */
function getListComplaints() {
  listHealthcareOsComplaints(queryComplaints).then(response => {
    options.value = response.rows
  })
}

// getListComplaints();

/*  选择 主诉 内容 进行 赋�?�?方法  */

function selectComplaints(value) {
  // console.log('选择主诉', value.currentHistory)
  form.value.chiefComplaint = value.complaintName
  form.value.presentIllness = value.currentHistory
  form.value.pastHistory = value.pastHistory
  form.value.diagnosis = value.diagnosis
  form.value.medicalAdvice = value.medicalAdvice
}

import DrugInventory from '@/components/Healthcare/OutpatientService/DrugInventory/index.vue'

/* 处理 处方 药品 信息 价格 子组�?使用  */

//  药品 批次 列表  弹框 显示 变量
const drugOpen = ref(false)
// 药品 批次 列表  弹框 标题
const druyTitle = ref('药品价格')
// 处方 序号  �?确定 哪一�?处方
const prescriptionItem = ref(0)
// 药品 序号 �?确定 哪一�?药品
const drugItem = ref(0)
// 数据  传�?�? 参数
const medicineName = ref('')
//
const drugInventoryRef = ref(null)
// 请求 参数
const queryParamsDrugInventory = ref({
  pageNum: 1,
  pageSize: 10,
  medicineName: null
})

// 重置请求 参数
function resetQueryParamsDrugInventory() {
  queryParamsDrugInventory.value = {
    pageNum: 1,
    pageSize: 10,
    medicineName: null
  }
}

// 更新 药品 名称 事件 处理 方法
const updateMedicineName = value => {
  // console.log('药品名称', medicineName.value)
  medicineName.value = value
}

// 处方 列表 里面 输入�? 点击 事件 处理 方法
function selectDrugPriceInput(item, row) {
  // 药品 批次 列表  弹框 显示 变量
  // 进行 判断 是否 �?药品 名字
  if (form.value.prescriptionDetailsList[item][row.$index].medicineName != null) {
    drugOpen.value = true
  } else {
    proxy.$modal.msgWarning('请先输入药品名称')
    retrun
  }
  // 药品 批次 弹框 组件 里面 �?方法
  drugInventoryRef.value.openDialog()
  // 处方 �?序号
  prescriptionItem.value = item
  // 药品 �?序号
  drugItem.value = row.$index
  // 药品 �?名字
  updateMedicineName(form.value.prescriptionDetailsList[prescriptionItem.value][drugItem.value].medicineName)
}

// 处理 药品 批次 库存 �?按钮
function selectDrugPriceInputButton(item, row) {
  // console.log('row', drugInventoryRef.value.updateQueryParams(queryParamsDrugInventory.value), queryParamsDrugInventory.value.medicineName, row.row.medicineName, item, row.$index)
  // 重置请求 参数 �?方法
  resetQueryParamsDrugInventory()
  // 判断 row 里面 �?没有 medicineName 属�?
  if (row.row.hasOwnProperty('medicineName')) {
    queryParamsDrugInventory.value.medicineName = row.row.medicineName
    // drugInventoryRef.value.updateQueryParams(queryParamsDrugInventory.value);
  }
  // 药品 批次 弹框 组件 里面 �?方法
  drugInventoryRef.value.openDialog(queryParamsDrugInventory.value)
  prescriptionItem.value = item
  drugItem.value = row.$index
}

// 事件 修改 �?组件 �?请求 参数
const drugInventoryInputQueryParams = value => {
  queryParamsDrugInventory.value.medicineName = value
}

const inputPrice = ref(null)

// 药品 批次 列表 库存  返回  事件 处理 接收 子组�?传输 过来的数�?
const drugPriceSelect = value => {
  // console.log('接收药品档案数据', prescriptionItem.value, drugItem.value, form.value.prescriptionDetailsList[prescriptionItem.value][drugItem.value].medicineName, value.medicineName, value, form, sys_yes_no, sys_yes_no.value[0].value, sys_yes_no.value[1].value, value.minNumber)
  drugOpen.value = false
  // 比配 名字 是否 相同
  if (form.value.prescriptionDetailsList[prescriptionItem.value][drugItem.value].medicineName == value.medicineName) {
    form.value.prescriptionDetailsList[prescriptionItem.value][drugItem.value].medicineId = value.filingId
    // 药品 名称 赋�?
    if (form.value.prescriptionDetailsList[prescriptionItem.value][drugItem.value].isSplit != null) {
      // 判断 是否 可以  拆分
      if (form.value.prescriptionDetailsList[prescriptionItem.value][drugItem.value].isSplit == 'Y') {
        //
        form.value.prescriptionDetailsList[prescriptionItem.value][drugItem.value].unitPrice = value.minNumberRetailPrice
      }
      // 判断 是否 可以  拆分
      else if (form.value.prescriptionDetailsList[prescriptionItem.value][drugItem.value].isSplit == 'N') {
        //
        form.value.prescriptionDetailsList[prescriptionItem.value][drugItem.value].unitPrice = value.filingRetailPrice
      }
      // 进行 计算  �?�?�?药品 进行 计算 价格
      calculationTotal(prescriptionItem.value, drugItem.value)
      // 库存进行 计算 想要 �?数据 �?赋�?
      const boxCount = value.boxCount
      const packCount = value.packCount
      // 库存 处理 方法
      drugInventoryHandleInsufficient(prescriptionItem.value, drugItem.value, boxCount, packCount)
    } else {
      proxy.$modal.msgSuccess('错误提示 isSplit = null ')
    }
  } else {
    proxy.$modal.msgSuccess('错误提示 药品名称错误')
  }
  // console.log('赋�?, form)
}

// 选择 药品 �?批次 �?库存 �?操作
// obtain  drug   inventory   data
const obtainDrugInventoryData = value => {
  // console.log('选择 药品 �?批次 �?库存 �?操作', value)
  // 药品 id 赋�?
  form.value.prescriptionDetailsList[prescriptionItem.value][drugItem.value].medicineId = value.filingId
  //  药品 名称
  form.value.prescriptionDetailsList[prescriptionItem.value][drugItem.value].medicineName = value.medicineName
  // 批次
  form.value.prescriptionDetailsList[prescriptionItem.value][drugItem.value].batch = value.batch
  // 有效期至
  form.value.prescriptionDetailsList[prescriptionItem.value][drugItem.value].expiryDate = value.expiryDate

  // 规格
  form.value.prescriptionDetailsList[prescriptionItem.value][drugItem.value].specification = value.specification
  // 药品 使用 单位  最小包装单�?
  if (!form.value.prescriptionDetailsList[prescriptionItem.value][drugItem.value].hasOwnProperty('splitUnit')) {
    form.value.prescriptionDetailsList[prescriptionItem.value][drugItem.value].splitUnit = value.splitUnit
  }
  // 包装单位
  if (!form.value.prescriptionDetailsList[prescriptionItem.value][drugItem.value].hasOwnProperty('packageUnit')) {
    form.value.prescriptionDetailsList[prescriptionItem.value][drugItem.value].packageUnit = value.packageUnit
  }
  // 是否允许拆分
  form.value.prescriptionDetailsList[prescriptionItem.value][drugItem.value].isSplit = value.isSplit
  // 判断 是否 可以  拆分
  if (form.value.prescriptionDetailsList[prescriptionItem.value][drugItem.value].isSplit == 'Y') {
    // 药品 单价
    form.value.prescriptionDetailsList[prescriptionItem.value][drugItem.value].unitPrice = value.minNumberRetailPrice
    if (value.state == 0) {
      // 最小单位数�?
      form.value.prescriptionDetailsList[prescriptionItem.value][drugItem.value].unitQuantity = value.minNumber
    }
    //
    if (value.state == 1) {
      // 最小包装数�?
      form.value.prescriptionDetailsList[prescriptionItem.value][drugItem.value].unitQuantity = value.unitQuantity
    }
  }
  // 判断 是否 可以  拆分
  else if (form.value.prescriptionDetailsList[prescriptionItem.value][drugItem.value].isSplit == 'N') {
    // 药品 单价
    form.value.prescriptionDetailsList[prescriptionItem.value][drugItem.value].unitPrice = value.filingRetailPrice
  }
  // 进行 计算 
  calculationTotal(prescriptionItem.value, drugItem.value)
  // 库存进行 计算 想要 �?数据 �?赋�?
  const boxCount = value.boxCount
  const packCount = value.packCount
  // 库存 处理 方法
  drugInventoryHandleInsufficient(prescriptionItem.value, drugItem.value, boxCount, packCount)
}

/* 获取 药品 名称 列表 药品 基本 档案 药品 名称 �?唯一�? */
import { gainMedicineArchiveList } from '@/api/healthcare/outpatientService/patientDiagnosis'
// reactive
const druyNameList = ref([])
const druyName = ref([])

//
function getDruyNameListQuer() {
  gainMedicineArchiveList({medicineName: druyName.value}).then(response => {
    druyNameList.value = response.rows
    // console.log('药品名称:', response.rows)
  })
  // console.log('获取 药品 信息 列表 药品 基本 档案 药品 名称 �?唯一�?', druyName.value, druyNameList.value)
}

// 控制 是否 显示 可以 拆分 总量  总量  可以 拆分  总量  �?可以 拆分
const isDisplayTotalQuantity = ref(0)

// 点击 事件 choiceDruyName
function choiceDruyName(index, index2, value) {
  // console.log('点击 事件 choiceDruyName', form.value.prescriptionDetailsList[0], index, index2, value.packageUnit)
  form.value.prescriptionDetailsList[index][index2].splitUnit = value.splitUnit
  form.value.prescriptionDetailsList[index][index2].packageUnit = value.packageUnit
  form.value.prescriptionDetailsList[index][index2].isSplit = value.isSplit
  // 控制 药品 输入 �?�?控制
  // form.value.prescriptionDetailsList[index][index2].isSplit == 'Y'
  // 1 => 可以 拆分 ; 0 => �?可以 拆分�?
  isDisplayTotalQuantity.value = 0
}

// 点击 输入 �? 触发 事件 处理 药品 名称 列表 显示
const queryDrugName = async (queryString, cb) => {
  druyName.value = queryString
  getDruyNameListQuer()
  cb(druyNameList)
}

// getDruyNameListQuer();

/* 处方 添加 drug 按钮 点击 事件 处理  */
function addPrescriptionButton() {
  // console.log('处方 添加 drug 按钮 点击 事件 处理 ', form)
  const listCf = []
  form.value.prescriptionDetailsList.push(listCf)
  // console.log('处方 添加 drug 按钮 点击 事件 处理 ', form)
}

/*  添加 药品  按钮 点击 事件 处理  */
function addDrugButton(index) {
  // console.log('添加 药品  按钮 点击 事件 处理 ', eatingTimeList.value)
  // if (commonUsageList.value.length == 0 || commonUsageList.value == null) {
  //   proxy.$modal.msgError('没有用法数据')
  //   return
  // } else if (frequencyList.value.length == 0 || frequencyList.value == null) {
  //   proxy.$modal.msgError('没有次数数据')
  //   return
  // } else if (eatingTimeList.value.length == 0 || eatingTimeList.value == null) {
  //   proxy.$modal.msgError('没有食用时间数据')
  //   return
  // }
  // form.value.prescriptionDetailsList[index].push({
  //   usageValue: commonUsageList.value[0].value, //
  //   splitUnit: '1', // 单位
  //   frequency: Number(frequencyList.value[0].value), // 次数
  //   eatingTime: eatingTimeList.value[0].value, // 食用时间
  //   packageUnit: '1' // 单位1
  // })
  // 确保 eatingTimeList 中包�?饭后"选项
  if (!eatingTimeList.value.some(option => option.value === '饭后')) {
    eatingTimeList.value.push({value: '饭后', name: '饭后'});
  }

  form.value.prescriptionDetailsList[index].push({
    usageValue: commonUsageList.value[0].value, //
    splitUnit: '1', // 单位
    frequency: Number(frequencyList.value[0].value), // 次数
    eatingTime: '饭后', // 默认值设置为"饭后"
    packageUnit: '1' // 单位1
  });

  // console.log('添加 药品  按钮 点击 事件 处理 ', form)
}

/*  删除药品  */
function removeDrug(index, index2) {
  form.value.prescriptionDetailsList[index].splice(index2, 1)
}

/*  删除处方  */
function removePrescription(index) {
  form.value.prescriptionDetailsList.splice(index, 1)
  totalPriceSum.value = 0;
}

// 组件 常规处方 �?弹框
import ConventionalPrescription from '@/components/Healthcare/OutpatientService/ConventionalPrescription'
// 弹框 �?显示
const conventionalPrescriptionOpen = ref(false)
//
const conventionalPrescriptionTitle = ref('常规处方')

// 处方 �?位置
const conventionalPrescriptionIndex = ref(null)

// 常规 处方
function conventionalPrescriptionButton(index) {
  // console.log('常规 处方 ', index)
  conventionalPrescriptionIndex.value = index
  conventionalPrescriptionOpen.value = true
}

// 接收 子组�?传�?�?数据
const conventionalPrescriptionSelect = value => {
  form.value.prescriptionDetailsList[conventionalPrescriptionIndex.value] = value
  conventionalPrescriptionOpen.value = false
}

// 医保 计算 �?�?
function calculationWholeTotal() {
  //
  if (form.value.prescriptionDetailsList != null) {
    const totalPrescriptionDetailsList = form.value.prescriptionDetailsList
    for (let i = 0; i < totalPrescriptionDetailsList.length; i++) {
      for (let j = 0; j < totalPrescriptionDetailsList[i].length; j++) {
        calculationTotal(i, j)
      }
    }
    // 更新当前报销估算并校验限�?总价不按比率,报销金额按比�?
    if (form.value.isInsured === 0) {
      const rate = Number(form.value.value || 0) / 100
      currentReimbursement.value = Number(totalPriceSum.value || 0) * (isNaN(rate) ? 0 : rate)
      // 计算患者需自付金额
      patientPay.value = (Number(totalPriceSum.value || 0) - Number(currentReimbursement.value || 0)).toFixed(2)
      if (historyReimbursement.value + currentReimbursement.value > reimbursementLimit.value) {
        proxy.$modal.msgWarning('累计医保报销超出300元限�?已切换为自费');
        form.value.isInsured = 1;
        insuranceDisabled.value = true;
      }
    } else {
      currentReimbursement.value = 0
      patientPay.value = Number(totalPriceSum.value || 0).toFixed(2)
    }
  }
}

// 修改 药品 价格 计算
// 计算 总量  总价  �?一�?药品 �?价格 总价
function calculationTotal(index, index2) {
  //
  const totalAmount = ref(0)
  //  进行  是否 拆分 �?  数据 处理 计算 拆分 总量 计算 �?方法 ,
  // if (form.value.prescriptionDetailsList[index][index2].isSplit == 'Y') {
  //   // �?拆分 �?总量 �?计算 拆分 �?总量 = 用量 * 频次 * 天数
  //   totalAmount.value = form.value.prescriptionDetailsList[index][index2].dosageValue * form.value.prescriptionDetailsList[index][index2].frequency * form.value.prescriptionDetailsList[index][index2].eatingDays
  //   if (!Number.isNaN(totalAmount.value)) {
  //     // 进行赋�?
  //     form.value.prescriptionDetailsList[index][index2].totalQuantity = totalAmount.value
  //   } else {
  //     //
  //     form.value.prescriptionDetailsList[index][index2].totalQuantity = 0
  //   }
  // }
  //
  // console.log('totalAmount:', totalAmount, healthcare_os_insured.value[0].value)
  // 总量

  // 在不 修改 由有 的代�?进行 修改 进行 一�?不可 拆分

  const totalPrice = ref(0)
  // 总价
  // 总价始终为数�?单价,不直接乘报销比率
  totalPrice.value = form.value.prescriptionDetailsList[index][index2].totalQuantity * form.value.prescriptionDetailsList[index][index2].unitPrice

  // console.log('totalPrice�?', totalPrice.value)
  if (!Number.isNaN(totalPrice.value)) {
    // 进行 四舍五入 0.00
    const tp = Number(totalPrice.value).toFixed(2)
    form.value.prescriptionDetailsList[index][index2].totalPrice = tp
  } else {
    form.value.prescriptionDetailsList[index][index2].totalPrice = 0
  }

  // 更新总价�?
  totalPriceSum.value = form.value.prescriptionDetailsList
      .reduce((sum, prescription) => {
        return sum + prescription.reduce((innerSum, drug) => innerSum + parseFloat(drug.totalPrice || 0), 0)
      }, 0)
      .toFixed(2)

  // console.log('prescriptionDetailsList�?', form.value.prescriptionDetailsList)
}

// 药品 档案 弹框
import DrugArchives from '@/components/Healthcare/OutpatientService/DrugArchives'
import drugArchivesUse from '@/components/Healthcare/OutpatientService/DrugArchives/use.ts'

let {
  controlQueryDrugArchives,
  queryParamsDrugArchives,
  controlDataDrugArchives,
  openDrugArchives,
  titleDrugArchives
} = drugArchivesUse()

// 显示 数据 控制
controlDataDrugArchives.value[6].display = false

// 控制 弹框 �?�?
const sdada = ref('1600px')

// 药品 �?位置 处方
const drugFanIndex = ref(null)
// 药品 �?位置 处方
const drugFanDrugIndex = ref(null)
//
const childComponentRef = ref(null)

// 点击 事件 处理 药品 档案 弹框
function drugArchivesBulletFrameOperation(index, index2) {
  drugFanIndex.value = index
  drugFanDrugIndex.value = index2
  openDrugArchives.value = true
  titleDrugArchives.value = '药品档案'
  childComponentRef.value.openDialog()
  // console.log('药品档案', index, index2)
}

// 获取 药品 档案 里面 �?数据
const selectDrugData = value => {
  // console.log('获取 药品 档案 里面 �?数据', drugFanIndex.value, drugFanDrugIndex.value, value, value.minNumber)
  //
  childComponentRef.value.closeDialog()
  // 药品 名称
  form.value.prescriptionDetailsList[drugFanIndex.value][drugFanDrugIndex.value].medicineName = value.medicineName
  // 药品 �?转化�?固�?液�?�?转化�?不一�?0 固�?1 液�?
  if (value.state == '0') {
    // 药品 �?最小单位数�?
    form.value.prescriptionDetailsList[prescriptionItem.value][drugItem.value].unitQuantity = value.minNumber
  }
  if (value.state == '1') {
    // 药品 �?最小包装数�?
    form.value.prescriptionDetailsList[prescriptionItem.value][drugItem.value].unitQuantity = value.unitQuantity
  }

  // 药品 使用 单位  最小包装单�?
  // form.value.prescriptionDetailsList[drugFanIndex.value][
  //   drugFanDrugIndex.value
  // ].splitUnit = value.splitUnit;
  // 包装单位
  // form.value.prescriptionDetailsList[drugFanIndex.value][
  //   drugFanDrugIndex.value
  // ].packageUnit = value.packageUnit;
  // 是否 可以 拆分
  form.value.prescriptionDetailsList[drugFanIndex.value][drugFanDrugIndex.value].isSplit = value.isSplit
  // 控制 可以 拆分 总量  总价  显示 隐藏  0 => 可以 拆分 1 => 不可�?拆分
  // form.value.prescriptionDetailsList[index][index2].isSplit == 'Y'
  // 修改 进行 不可 拆分 显示
  isDisplayTotalQuantity.value = 0
}

// 药品 �?库存 处理 逻辑  库存 不足  stock  inventory handle Insufficient
function drugInventoryHandleInsufficient(index, index2, boxCount, packCount) {
  if (form.value.prescriptionDetailsList[index][index2].isSplit == 'Y') {
    // 处理
    const unitQuantity = form.value.prescriptionDetailsList[index][index2].unitQuantity
    if (unitQuantity != null) {
      // 库存 不足 处理 逻辑
      form.value.prescriptionDetailsList[index][index2].inventoryCount = boxCount * unitQuantity + packCount
      // console.log(' 库存 处理 逻辑 ', form.value.prescriptionDetailsList[index][index2])
    }
  } else {
    form.value.prescriptionDetailsList[index][index2].inventoryCount = boxCount
  }
}

// 判断 库存 是否 不足  Insufficient
function judgeInventoryIsInsufficient(index, index2) {
  const total = form.value.prescriptionDetailsList[index][index2].totalQuantity
  const inventoryCount = form.value.prescriptionDetailsList[index][index2].inventoryCount
  if (total != null && inventoryCount != null) {
    if (total > inventoryCount) {
      // proxy.$modal.error("库存不足");
    }
  }
}

// 患�?诊断 信息 弹框
import DiagnosisInformation from '@/components/Healthcare/OutpatientService/DiagnosisInformation'
import DiagnosisInformationUse from '@/components/Healthcare/OutpatientService/DiagnosisInformation/use.ts'
import { Check } from "@element-plus/icons-vue"

const diagnosisInformationRef = ref(null) // 引用子组�?


let {controlDataDiagnosisInformation, styleDiagnosisInformation} = DiagnosisInformationUse()

// check
function checkInformation(id) {
  console.log(id);
  diagnosisInformationRef.value.openDialog(id)
}

//  按钮
function checkButton(row) {
  // console.log('row:', row)
  diagnosisInformationRef.value.openDialog(row.id)
}

//就诊时间选择
// 格式�?Date �?YYYY-MM-DD
const outpatientTime = ref([])
function formatDate(date) {
  if (!date) return ''
  const y = date.getFullYear()
  const m = String(date.getMonth() + 1).padStart(2, '0')
  const d = String(date.getDate()).padStart(2, '0')
  return `${y}-${m}-${d}`
}
function changeTime() {
  if (outpatientTime.value && Array.isArray(outpatientTime.value)) {
    queryParams.value.startTime = formatDate(outpatientTime.value[0])
    queryParams.value.endTime = formatDate(outpatientTime.value[1])
    //console.log('startTime:', queryParams.value.startTime)
    //console.log('endTime:', queryParams.value.endTime)
  } else {
    startTime.value = ''
    endTime.value = ''
  }
}

/** 打印按钮操作 */
function handlePrint(row) {
  // 获取打印数据
  getPatientDiagnosis(row.id).then(response => {
    const printData = response.data;

    // 调用打印方法
    printPrescription(printData);
  });
}

/** 打印方法 */
function printPrescription(data) {
  // 处理性别显示 (0=�?1=�?
  const genderDisplay = data.gender == 0 ? '�? : (data.gender == 1 ? '�? : '');
  // 单位映射字典(键值对反转后的版本,便于查找)
  const unitMap = {
    '1': '�?,
    '2': '�?,
    '3': '�?,
    '4': '�?,
    '5': '�?,
    '6': '�?,
    '7': '�?,
    '8': '�?,
    '9': '�?,
    '10': 'g',
    '11': '�?,
    '12': '�?,
    '13': '�?,
    '14': '�?,
    '15': '�?,
    '16': '�?,
    '17': '�?,
    '18': '�?,
    '19': '�?,
    '20': 'mg',
    '21': '�?,
    '22': '�?,
    '23': '�?,
    '24': '�?,
    '25': '�?,
    '26': '�?,
    '27': '�?,
    '28': '�?,
    '29': '�?,
    '30': 'ml',
    '31': '�?,
    '32': '�?,
    '33': '�?,
    '34': '�?,
    '35': '�?,
    '36': '�?,
    '37': '�?,
    '38': '�?,
    '39': '�?,
    '40': 'IU'
  };

  // 增强版单位转换函�?
  function formatUnit(value) {
    if (value == null || value === '') return '';

    // 如果已经是中文单�?直接返回
    if (Object.values(unitMap).includes(value.toString())) {
      return value;
    }

    // 处理可能带数字后缀的情�?�?"1" �?1)
    const strValue = value.toString().trim();

    // 检查是否是纯数�?
    if (/^\d+$/.test(strValue)) {
      return unitMap[strValue] || strValue;
    }

    // 检查是否是数字+单位格式(�?"1�?)
    const match = strValue.match(/^(\d+)([^\d]*)$/);
    if (match) {
      const num = match[1];
      const unit = match[2];
      return (unitMap[num] || num) + unit;
    }

    // 其他情况返回原�?
    return strValue;
  }

  // 频次映射字典(键值对)
  const frequencyMap = {
    '1': '每天1�?,
    '2': '每天2�?,
    '3': '每天3�?,
    '4': '每天4�?,
    '5': '隔日1�?,
    '6': '每周1�?,
    '7': '每周2�?,
    '8': '临睡�?,
    '9': '每晚1�?,
    '10': '�?小时1�?,
    '11': '�?小时1�?,
    '12': '�?小时1�?,
    '13': '�?小时1�?,
    '14': '�?2小时1�?,
    '15': '立即',
    '16': '需要时',
    '17': '需要时(长期)',
    '18': 'N�?�?,
    '19': 'N�?�?,
    '20': 'N小时1�?,
    '21': '每周N�?
  };

  // 频次格式化函�?只保留中�?
  function formatFrequency(value) {
    if (value == null || value === '') return '';

    // 如果已经是中文频�?直接返回
    if (Object.values(frequencyMap).includes(value.toString())) {
      return value;
    }

    // 如果是数字键�?转换为中文频�?
    const strValue = value.toString().trim();
    if (frequencyMap[strValue]) {
      return frequencyMap[strValue];
    }

    // 如果是英文缩�?中文格式(�?qd 每天1�?),提取中文部分
    const chineseMatch = value.match(/[\u4e00-\u9fa5]+/g);
    if (chineseMatch && chineseMatch.length > 0) {
      return chineseMatch.join('');
    }

    // 其他情况返回原�?
    return strValue;
  }

  // 处理日期数据 - 只保留年月日部分
  const currentDate = new Date();
  const dateObj = {
    year: data.year || currentDate.getFullYear(),
    month: data.month || currentDate.getMonth() + 1,
    day: data.day || currentDate.getDate()
  };

  // 如果传入的是完整日期时间字符�?自动拆分
  if (data.outpatientTime && !data.year) {
    const [datePart] = data.outpatientTime.split(' ');
    const dateParts = datePart.split(/[-/]/);
    if (dateParts.length >= 3) {
      dateObj.year = dateParts[0];
      dateObj.month = dateParts[1];
      dateObj.day = dateParts[2];
    }
  }

  // 从表单数据结构中获取医保信息
  const insuranceInfo = data.isInsured == 0 ? '□自�?离休 二乙 ☑医�?自治区、市、县)' : '☑自�?□医�?自治区、市、县)';

  // 新窗�?
  const printWindow = window.open('', '_blank');


  // 打印内容HTML
  const printContent = `
   <html>
  <head>
    <title>处方打印</title>
    <style>
      body {
        font-family: "SimSun", serif;
        margin: 0;
        padding: 10px;
      }
      .prescription-container {
        width: 210mm;
        margin: 0 auto;
        padding: 10mm;
      }
      .header {
        text-align: center;
        margin-bottom: 10px;
      }
      .header h2 {
        font-size: 35px;
        font-weight: bold;
        margin: 5px 0;
      }
      .patient-info-container {
        display: flex;
        flex-direction: column;
        margin-bottom: 10px;
      }
      .patient-info-row {
        display: flex;
        align-items: center;
        padding: 5px 0;
        min-height: 30px;
      }
      .patient-info-label {
        margin-left: 6px;
        font-weight: bold;
        min-width: 50px;
      }
      .patient-info-value {
        flex: 1;
        border-bottom: 1px solid #000;
        margin-right: 20px;
        min-width: 100px;
      }
      .date-container {
        display: flex;
        align-items: center;
      }
      .date-part {
        display: inline-block;
        min-width: 30px;
        border-bottom: 1px solid #000;
        margin-right: 5px;
        text-align: center;
      }
      .footer {
        margin-top: 20px;
      }
      .signature-row {
        display: flex;
        justify-content: space-between;
        margin-bottom: -10px;
      }
      .divider {
        border-top: 1px solid #000;
        margin: 20px 20px 10px 2px;
      }
      .patient-opinion {
        display: flex;
        align-items: center;
        margin-top: 15px;
      }
      .opinion-option {
        margin-right: 20px;
      }
      .contact-info {
        margin-top: 10px;
        font-size: 16px;
      }
      .doctor-signature {
        margin-left: 400px;
      }
      .no-print {
        display: none;
      }
      .doctor{
        margin-left: 185px;
      }
      .collector {
        margin-right: 19px;
      }
      .examine {
        margin-right: 20px;
      }
      .check {
        margin-right: 20px;
      }
      .patient {
        margin-left: 250px;
      }
      .section {
        margin-bottom: 15px;
        margin-right: 20px;
      }
      .section-title {
        font-weight: bold; margin-bottom: 5px;
      }
      table {
        width: 100%; 
        border-collapse: collapse;
        margin-bottom: 15px;
      }
      th, td {
        border: 1px solid #ddd;
        padding: 8px;
        text-align: left;

      }
      @media print {
        body {
          margin: 0;
          padding: 10px;
        }
        .no-print {
          display: none;
        }
        .prescription-container {
          padding: 0;
        }
        
      }
      @page {
        size: A4;
        margin: 0;
      }
    </style>
  </head>
  <body>
    <div class="prescription-container">
      <!-- 头部信息 -->
      <div class="header">
        <h2>南宁市社会医疗机构专用处方笺</h2>
      </div>

      <!-- 患者基本信�?-->
      <div class="patient-info-container">
        <div class="patient-info-row">
          <div class="patient-info-label">费别:</div>
          <div class="patient-info-value">
            ${insuranceInfo} 对号划✓
          </div>
        </div>
        
        <div class="patient-info-row">
          <div class="patient-info-label">姓名:</div>
          <div class="patient-info-value">${data.name || ''}&nbsp</div>
          
          <div class="patient-info-label">性别:</div>
          <div class="patient-info-value">${genderDisplay}&nbsp</div>
          
          <div class="patient-info-label">年龄:</div>
          <div class="patient-info-value">${data.age || ''}&nbsp</div>
        </div>
        
        <div class="patient-info-row">
          <div class="patient-info-label">门诊病历�?</div>
          <div class="patient-info-value">${data.medicalRecordNo || ''}&nbsp</div>
          
          <div class="patient-info-label">科别:</div>
          <div class="patient-info-value">${data.classInfo || ''}</div>
        </div>
        
        <div class="patient-info-row">
          <div class="patient-info-label">临床诊断:</div>
          <div class="patient-info-value">${data.diagnosis || ''}&nbsp</div>
        </div>
        
        <div class="patient-info-row">
          <div class="patient-info-label">开具日�?</div>
          <div class="date-container">
            <span class="date-part">${dateObj.year}</span>�?
            <span class="date-part">${dateObj.month}</span>�?
            <span class="date-part">${dateObj.day}</span>�?
          </div>
        </div>


      <!-- 患者信�?-->
      </div>
      <div><strong>主诉:</strong> ${data.chiefComplaint || '�?}</div>
      <div><strong>现病�?</strong> ${data.presentIllness || '�?}</div>
      <div><strong>既往�?</strong> ${data.pastHistory || '�?}</div>
      <!-- 医嘱信息 -->
      <div style="margin: 10px 0;">
        <div><strong>Rp:</strong>${data.medicalAdvice || ''}</div>
      </div>
      


<div class="section">
  <div class="section-title">处方详情</div>
  <table>
    <thead>
      <tr>
        <th>序号</th>
        <th>药品名称</th>
        <th>规格</th>
        <th>用法</th>
        <th>用量</th>
        <th>频次</th>
        <th>总量</th>
      </tr>
    </thead>
    <tbody>
      ${data.prescriptionDetailsList?.flat().map((item, index) => `
        <tr>
          <td>${index + 1}</td>
          <td>${item.medicineName || ''}</td>
          <td>${item.specification || ''}</td>
          <td>${item.usageValue || ''}</td>
          <td>${item.dosageValue || ''} ${formatUnit(item.splitUnit) || ''}</td>
          <td>${formatFrequency(item.frequency) || ''}</td>
          <td>${item.totalQuantity || ''} ${formatUnit(item.packageUnit) || ''}</td>
        </tr>
      `).join('') || '<tr><td colspan="7">无处�?/td></tr>'}
    </tbody>
  </table>
</div>
      
      <!-- 底部签名�?-->
      <div class="footer">
        <!-- 医师签名 -->
        <div class="signature-row doctor-signature">
          <div class="doctor">医师签名:${data.doctorName || ''}</div>
        </div>
        
        <!-- 分隔�?-->
        <div class="divider"></div>
        
        <!-- 药品金额和收费员 -->
        <div class="signature-row">
          <p>药品金额:${data.prescriptionDetailsList?.flat().reduce((sum, item) => sum + (parseFloat(item.totalPrice) || 0), 0).toFixed(2) || '0.00'}�?/p>
          <div class="patient-info-row">
          <div class="patient-info-label">收费�?&nbsp&nbsp</div>
          <div class="patient-info-value">${data.doctorName || ''}&nbsp</div>
          </div>
        </div>
        
        <!-- 注射费和审核调配 -->
        <div class="signature-row">
          <p>注射�?________�?/p>
          <div class="patient-info-row">
          <div class="patient-info-label">审核、调�?</div>
          <div class="patient-info-value">&nbsp</div>
          </div>
        </div>
        
        <!-- 收款票据和核对发�?-->
        <div class="signature-row">
        <p>(收款票据请贴附处方背�? </p>
          <div class="patient-info-row">
          <div class="patient-info-label">核对、发�?</div>
          <div class="patient-info-value">${data.doctorName || ''}&nbsp</div>
          </div>
        </div>
        
        <!-- 大额处方患者意见和签名 -->
        <div class="patient-opinion">
          <div style="margin-right: 20px;">大额处方患者意�?</div>
          <div class="opinion-option">�?同意</div>
          <div class="opinion-option">�?不同�?/div>
          <div class="patient">患者签�?______________</div>
        </div>
        <!-- 联系地址或电�?-->
        <div class="contact-info">联系地址或电�?患者志愿填�?:________________________</div>
      </div>
      
      <!-- 打印控制按钮 -->
      <div class="no-print" style="margin-top: 20px; text-align: center;">
        <button onclick="window.print()" style="padding: 5px 15px; background: #409EFF; color: white; border: none; border-radius: 4px; cursor: pointer;">打印</button>
        <button onclick="window.close()" style="padding: 5px 15px; background: #F56C6C; color: white; border: none; border-radius: 4px; cursor: pointer; margin-left: 10px;">关闭</button>
      </div>
    </div>
  </body>
</html>
  `;

  // 写入打印内容
  printWindow.document.write(printContent);
  printWindow.document.close();

  // 等待内容加载完成后自动打�?
  printWindow.onload = function () {
    setTimeout(() => {
      printWindow.print();
    }, 500);
  };
}

// 主诉相关数据
const complaintsOptions = ref([])
const loadingComplaints = ref(false)

// 初始化时加载主诉模板
onMounted(() => {
  loadComplaintsOptions()
})

// 加载主诉模板
const loadComplaintsOptions = async () => {
  try {
    loadingComplaints.value = true
    const response = await listHealthcareOsComplaints({status: 0})
    complaintsOptions.value = response.rows.map(item => ({
      value: item.complaintName,
      label: item.complaintName,
      ...item
    }))
  } catch (error) {
    console.error('加载主诉模板失败:', error)
  } finally {
    loadingComplaints.value = false
  }
}

// 处理输入框获取焦点事�?
const handleComplaintFocus = () => {
  if (!loadingComplaints.value && complaintsOptions.value.length === 0) {
    loadComplaintsOptions()
  }
}

// 查询主诉建议
const queryComplaintSuggestions = async (queryString, cb) => {
  try {
    // 如果没有查询字符串或为空,返回所有选项
    if (!queryString || queryString.trim() === '') {
      cb(complaintsOptions.value);
      return;
    }

    // 将查询字符串转为小写以便不区分大小写
    const searchTerm = queryString.toLowerCase();

    // 过滤匹配的选项
    const filteredOptions = complaintsOptions.value.filter(option => {
      // 检查选项的label或value是否包含搜索�?
      return (
          (option.label && option.label.toLowerCase().includes(searchTerm)) ||
          (option.value && option.value.toLowerCase().includes(searchTerm))
      );
    });

    cb(filteredOptions);
  } catch (error) {
    console.error('查询主诉失败:', error);
    cb([]);
  }
};

// 选择主诉
const selectComplaint = (item) => {
  if (item.isCustom) {
    // 自由输入
    form.value.chiefComplaint = item.value
  } else {
    // 选择模板
    form.value.chiefComplaint = item.label
    form.value.presentIllness = item.currentHistory || ''
    form.value.pastHistory = item.pastHistory || ''
    form.value.diagnosis = item.diagnosis || ''
    form.value.medicalAdvice = item.medicalAdvice || ''
  }
}
// 清空主诉及相关字�?
const clearComplaint = () => {
  form.value.chiefComplaint = ''
  form.value.presentIllness = ''
  form.value.pastHistory = ''
  form.value.diagnosis = ''
  form.value.medicalAdvice = ''
}

//
const timesData = ref('饭后')
const xuanZheData = (val, index) => {
  console.log('选中12345');
  console.log(val, index);
}


getList()
</script>

<style>
.el-input__wrapper {
  width: 702px;
}

.el-input__inner {
  font-size: 14px;
}

.prescriptionAdd {
  margin-bottom: 20px;
}

.prescription {
  margin-bottom: 20px;
}

/*  */
.buttonPrescription {
  float: right;
}
</style>
