<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item v-if="false" 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>
        <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 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="outpatientTime" />
      <el-table-column label="就诊地址" align="center" prop="storeroomName" />
      <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" prop="outpatientTime" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['os:patientDiagnosis:getInfo']">查看详情</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="80px">
        <el-row :gutter="20">
          <!-- 病人信息 -->
          <el-col :span="12">
            <!-- 患者信息 -->
            <el-col :span="24">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="学号/工号" prop="studentId">
                    <el-input v-model="form.studentId" placeholder="请输入学号/工号" @change="selectPatient()"
                      :disabled="true" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="诊断类型" prop="diagnosisType">
                    <el-select v-model="form.diagnosisType" placeholder="请选择诊断类型类型" :disabled="true">
                      <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="name">
                    <el-input v-model="form.name" placeholder="请输入姓名" :disabled="true" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="就诊人类型" prop="patientType">
                    <el-select v-model="form.patientType" placeholder="请选择就诊人类型" :disabled="true">
                      <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-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="性别" prop="gender">
                    <!-- <el-select placeholder="请输入性别" :disabled="true" clearable>
                      <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
                    </el-select> -->
                    <slot v-for="dict in sys_user_sex" :key="dict.value">
                      <el-input v-if="dict.value == form.gender" :value="form.gender == dict.value ? dict.label : ''"
                        placeholder="请输入性别" disabled="true"></el-input>
                    </slot>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="年龄" prop="age">
                    <el-input v-model="form.age" clearable placeholder="请输入年龄" :disabled="true" />
                  </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="请输入专业" :disabled="true" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="班级" prop="classInfo">
                    <el-input v-model="form.classInfo" clearable placeholder="请输入班级" :disabled="true" />
                  </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="请输入电话" :disabled="true" />
                  </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="请输入辅导员" :disabled="true" />
                  </el-form-item>
                </el-col>
                <el-col v-if="form.patientType === 1 || form.patientType === 2" :span="12">
                  <el-form-item label="部门" prop="counselor">
                    <el-input v-model="form.counselor" clearable placeholder="请输入部门" :disabled="true" />
                  </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 :disabled="!editMode">
                      <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-col>
                <el-col :span="12">
                  <el-form-item v-if="form.isInsured == 0" label="报销比率" prop="value">
                    <el-input @input="calculationWholeTotal()" v-model="form.value" clearable placeholder="请输入报销比率"
                      :disabled="!editMode" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="24">
              <el-form-item label="主诉" prop="chiefComplaint">
                <el-input v-model="form.chiefComplaint" type="textarea" placeholder="请输入内容" :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="现病史" prop="presentIllness">
                <el-input v-model="form.presentIllness" type="textarea" placeholder="请输入内容" :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="既往史" prop="pastHistory">
                <el-input v-model="form.pastHistory" type="textarea" placeholder="请输入内容" :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="临床诊断" prop="diagnosis">
                <el-input v-model="form.diagnosis" type="textarea" placeholder="请输入内容" :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="医嘱事项" prop="medicalAdvice">
                <el-input v-model="form.medicalAdvice" type="textarea" placeholder="请输入内容" :disabled="true" />
              </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>
        <el-divider content-position="center"> 处方详情</el-divider>
        <!-- 处方 -->
        <el-row v-for="(index, item) in form.prescriptionDetailsList" :key="item">
          <el-table :data="form.prescriptionDetailsList[item]" border style="width: 100%" class="prescription">
            <el-table-column fixed prop="name" label="编号" width="80">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>

            <el-table-column fixed prop="medicineName" label="药名" min-width="230">
              <template #default="scope">
                <el-form-item label-width="0px" :prop="`prescriptionDetailsList.${item}.${scope.$index}.medicineName`"
                  :rules="[{ required: true, message: '药名不能为空', trigger: 'blur' }]">
                  <!--  -->
                  <el-select v-model="form.prescriptionDetailsList[item][scope.$index].medicineName
                    " filterable placeholder="请选择" :disabled="true" 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>
                  <!-- 输入框弹框 -->
                  <el-input
                  v-if="isTextOverflow(scope.row.medicineName)"
                  type="textarea"
                  rows="2"
                  v-model="form.prescriptionDetailsList[item][scope.$index].medicineName" 
                  disabled
                  />
                  <el-input v-else :disabled="true" v-model="form.prescriptionDetailsList[item][scope.$index].medicineName
                    " @focus="drugArchivesBulletFrameOperation(item, scope.$index)"></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="200">
              <template #default="scope">
                <el-form-item label-width="0px" :prop="`prescriptionDetailsList.${item}.${scope.$index}.specification`"
                  :rules="[{ required: true, message: '规格不能为空', trigger: 'blur' }]">
                  <el-input :disabled="true" v-model="form.prescriptionDetailsList[item][scope.$index].specification
                    "></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <!-- 用法 -->
            <el-table-column prop="usageValue" label="用法" width="100">
              <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="请选择" :disabled="true">
                    <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' },
                      ]">
                      <el-input :disabled="true" 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="请选择" :disabled="true">
                        <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="130">
              <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="请选择" :disabled="true">
                    <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="108">
              <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="请选择" :disabled="true">
                    <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' },
                  ]"
                >
                  <el-input
                    :disabled="true"
                    @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">
                <!--  -->
                <el-row v-if="form.prescriptionDetailsList[item][scope.$index].isSplit == 'Y'">
                  <el-col :span="8">
                    <el-form-item label-width="0px"
                      :prop="`prescriptionDetailsList.${item}.${scope.$index}.totalQuantity`" :rules="[
                        { required: true, message: '总量不能为空', trigger: 'blur' },
                        { required: true, message: '总量不能为空', 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="请选择" :disabled="true">
                        <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>
                    <!-- splitUnit  packageUnit -->
                  </el-col>
                </el-row>
                <!-- 总量 2  不 可以 拆分  -->
                <el-row v-if="form.prescriptionDetailsList[item][scope.$index].isSplit == 'N'">
                  <el-col :span="8">
                    <el-form-item label-width="0px"
                      :prop="`prescriptionDetailsList.${item}.${scope.$index}.totalQuantity`" :rules="[
                        { required: true, message: '总量不能为空', trigger: 'blur' },
                      ]">
                      <el-input v-model="form.prescriptionDetailsList[item][scope.$index].totalQuantity
                        " prescription="请输入总量" :disabled="true" @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="请选择" :disabled="true">
                        <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)">
                    {{ Number(form.prescriptionDetailsList[item][scope.$index].unitPrice || 0).toFixed(2) }}
                  </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%">
                    {{ Number(form.prescriptionDetailsList[item][scope.$index].unitPrice || 0).toFixed(2) }}
                  </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
                      ? ceilPrice(
                          Number(form.prescriptionDetailsList[item][scope.$index].totalPrice || 0) *
                          (1 - Number(form.value || 0) / 100)
                        )
                      : ceilPrice(form.prescriptionDetailsList[item][scope.$index].totalPrice || 0)
                  }}
                  元
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="notes" label="备注" min-width="220">
              <template #default="scope">
                <el-input
                  v-if="isTextOverflow(scope.row.remarks)"
                  type="textarea"
                  rows="2"
                  v-model="form.prescriptionDetailsList[item][scope.$index].remarks" 
                  disabled
                  />
                <el-input v-else :disabled="true" v-model="form.prescriptionDetailsList[item][scope.$index].remarks" />
              </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 ? patientPay : ceilPrice(totalPriceSum) }} 元
              </span>
              <span style="margin-left: 16px; color: #666">
                处方总金额：{{ ceilPrice(totalPriceSum) }} 元
              </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">
          <!-- :disabled="isDisabled"  :disabled="isDisabled" -->
          <el-button type="primary" @click="submitForm" v-if="form.status == 0"
            v-hasPermi="['os:patientDiagnosis:deliverMedicine']">发药</el-button>
          <el-button type="danger" @click="withdrawal" v-if="form.status == 0 || form.status == 1"
            v-hasPermi="['os:patientDiagnosis:returnedMedication']">
            驳回</el-button>
          <el-button type="warning" @click="startAdjust" v-if="form.status == 1 && !editMode"
            v-hasPermi="['os:patientDiagnosis:adjustBasic']">更正</el-button>
          <el-button type="primary" @click="saveAdjust" v-if="form.status == 1 && editMode"
            v-hasPermi="['os:patientDiagnosis:adjustBasic']">保存更正</el-button>
          <el-button @click="cancelAdjust" v-if="form.status == 1 && editMode">取消</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 患者诊断信息 -->
    <DiagnosisInformation ref="diagnosisInformationRef" :style="styleDiagnosisInformation"
      :controlData="controlDataDiagnosisInformation" />
    <!-- 药品库存 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()" />
  </div>
</template>

<script setup name="PatientDiagnosis">
const dsada = ref()

// 价格向上取整到小数点后两位（进一法）
// 例如: 8.123 → 8.13, 2.234 → 2.24, 8.02 → 8.02, 0.55 → 0.55
// 先缩放到整数避免浮点精度问题（0.55*100=55.0000001 会导致 Math.ceil 错误进位）
function ceilPrice(value) {
  const num = Number(value)
  if (isNaN(num)) return '0.00'
  const scaled = Math.round(num * 10000)
  const cents = Math.ceil(scaled / 100)
  return (cents / 100).toFixed(2)
}

import { adjustBasic, deliverMedicine, delPatientDiagnosis, getPatientDiagnosis, listPatientDiagnosis, returnedMedication } 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'
import DrugInventory from '@/components/Healthcare/OutpatientService/DrugInventory/index.vue'

const { proxy } = getCurrentInstance()

// 汇总展示变量（查看详情页）
const currentReimbursement = ref(0)
const patientPay = ref(0)

// 新增  选择诊断地址后刷新页面数据--知无涯
onActivated(() => {
  // 当组件被激活时刷新数据
  getList()
})


// 患者类型
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')

//  药品 批次 列表  弹框 显示 变量
const drugOpen = ref(false)
const drugInventoryRef = ref(null)

// 获取 常用用法
common()
const commonUsageList = ref([]) // 用法
const eatingTimeList = ref([]) //  食用时间
const frequencyList = ref([]) //   次数
const totalPriceSum = 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 queryParamsDrugInventory = ref({
  pageNum: 1,
  pageSize: 10,
  medicineName: null
})

//
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 editMode = ref(false)

const ListTotalPrice = ref(0)

//
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
  },
  // vue3 的 封装 的好 的 检验 写法   pattern: /^1(3|4|5|7|8|9)\d{9}$/,
  rules: {}
})

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

const nameDiagnosisList = ref([])

// 患者 的 诊断 的 列表
watch(
  () => form.value.patientId,
  (newValue, odlValue) => {
    if (form.value.patientId != null) {
      listPatientDiagnosis({ patientId: newValue }).then(res => {
        nameDiagnosisList.value = res.rows
      })
    } else {
      nameDiagnosisList.value = []
    }
  }
)

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

// /** 查询患者诊断信息列表 */
function getList() {
  loading.value = true
  // 获取 库房
  getUserProfile().then(userInfo => {
    getWarehouse(userInfo.data.userId).then(res => {
      // 库房id 赋值
      queryParams.value.storeroomId = res.data.storeroomId
      // 获取 诊断信息列表
      listPatientDiagnosis(queryParams.value).then(response => {
        patientDiagnosisList.value = response.rows
        total.value = response.total
        loading.value = false
      })
    })
  })
}

/** 查询患者诊断信息列表  新增自定义编号处理---知无涯*/
// function getList() {
//   loading.value = true
//   getUserProfile().then(userInfoRow => {
//     getWarehouse(userInfoRow.data.userId).then(res => {
//       queryParams.value.storeroomId = res.data.storeroomId
//       listPatientDiagnosis(queryParams.value).then(response => {
//         // 获取所有数据(不分页)
//         listPatientDiagnosis({ ...queryParams.value, pageSize: 1000 }).then(allResponse => {
//           // 对完整数据集进行排序
//           const sortedData = sortDiagnosisData(allResponse.rows)

//           // 只显示当前页的数据
//           const startIndex = (queryParams.value.pageNum - 1) * queryParams.value.pageSize
//           patientDiagnosisList.value = sortedData.slice(startIndex, startIndex + queryParams.value.pageSize)

//           total.value = allResponse.total
//           loading.value = false
//         })
//       })
//     })
//   })
// }

// // 自定义排序函数
// function sortDiagnosisData(data) {
//   // 按就诊地址分组
//   const groupedByLocation = data.reduce((acc, item) => {
//     const location = item.storeroomName || '未知地址'
//     if (!acc[location]) {
//       acc[location] = []
//     }
//     acc[location].push(item)
//     return acc
//   }, {})

//   // 对每个地址组内的数据按就诊时间倒序排序(最新的在前面)
//   Object.keys(groupedByLocation).forEach(location => {
//     groupedByLocation[location].sort((a, b) => {
//       return new Date(b.outpatientTime) - new Date(a.outpatientTime)
//     })
//   })

//   // 合并所有组的数据并生成连续编号
//   const result = []
//   Object.keys(groupedByLocation).forEach(location => {
//     const group = groupedByLocation[location]
//     const groupCount = group.length

//     // 为当前组的每条数据分配编号(从总数递减)
//     group.forEach((item, index) => {
//       result.push({
//         ...item,
//         // 编号从总数据量开始递减
//         id: data.length - result.length
//       })
//     })
//   })

//   return result
// }


// 取消按钮
function cancel() {
  open.value = false
  reset()
  editMode.value = false
}

// 表单重置
function reset() {
  form.value = {
    patientDiagnosisId: null,
    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: null,
    chiefComplaint: null,
    presentIllness: null,
    pastHistory: null,
    diagnosis: null,
    medicalAdvice: null,
    doctorName: null,
    status: null,
    outpatientTime: null,
    prescriptionDetailsList: []
  }
  proxy.resetForm('patientDiagnosisRef')
}

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

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  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 = '添加患者诊断信息'
}

const isDisabled = ref(false)
/** 查看按钮操作 */
function handleUpdate(row) {
  console.log('查看详情', row.status)
  reset()
  if (row.status == 1 || row.status == 2) {
    isDisabled.value = true
  }

  const _id = row.id || ids.value
  getPatientDiagnosis(_id).then(response => {
    form.value = response.data
    console.log('处方信息---', form.value)
    open.value = true
    title.value = '查看患者诊断信息'
    editMode.value = false
    // 更新总价和（优先用行总价，缺失时用数量*单价回算）
    const sumAll = (Array.isArray(form.value.prescriptionDetailsList) ?
      form.value.prescriptionDetailsList.reduce((sum, prescription) => {
        return sum + prescription.reduce((innerSum, drug) => {
          const tp = parseFloat(drug.totalPrice)
          if (!isNaN(tp)) return innerSum + tp
          const qty = parseFloat(drug.totalQuantity || 0)
          const up = parseFloat(drug.unitPrice || 0)
          return innerSum + (qty * up)
        }, 0)
      }, 0) : 0)
    totalPriceSum.value = ceilPrice(sumAll)
    // 计算本次预计报销与应收
    const insured = form.value?.isInsured
    const sum = Number(totalPriceSum.value || 0)
    if (insured === 0) {
      const rate = Number(form.value?.value ?? form.value?.value) / 100
      const r = isNaN(rate) ? 0 : rate
      // 先计算个人应付（向上取整）
      const pay = ceilPrice(sum * (1 - r))
      patientPay.value = pay
      // 预计报销 = 总价 - 个人应付
      currentReimbursement.value = (sum - Number(pay)).toFixed(2)
    } else {
      currentReimbursement.value = '0.00'
      patientPay.value = ceilPrice(sum)
    }
  })
}

function startAdjust() {
  editMode.value = true
  proxy.$modal.msgInfo('已进入更正模式：可修改是否医保与报销比率')
}

function cancelAdjust() {
  editMode.value = false
}

function saveAdjust() {
  const payload = {
    patientDiagnosisId: form.value.patientDiagnosisId,
    isInsured: form.value.isInsured,
    value: form.value.value
  }
  adjustBasic(payload).then(() => {
    proxy.$modal.msgSuccess('更正已保存')
    editMode.value = false
    getList()
  })
}
/** 发药按钮 */
function submitForm() {
  // console.log("新增成功", form, form.value);
  proxy.$refs['patientDiagnosisRef'].validate(valid => {
    if (valid) {
      if (form.value.patientDiagnosisId != null) {
        deliverMedicine(form.value.patientDiagnosisId).then(response => {
          proxy.$modal.msgSuccess('发药成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

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)
  // 总价
  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
  }

  // console.log('totalPrice值:', totalPrice.value)
  if (!Number.isNaN(totalPrice.value)) {
    // 进行 四舍五入 0.00
    totalPrice.value = ceilPrice(totalPrice.value)
    form.value.prescriptionDetailsList[index][index2].totalPrice = totalPrice
  } else {
    form.value.prescriptionDetailsList[index][index2].totalPrice = 0
  }

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

  // console.log('prescriptionDetailsList值:', form.value.prescriptionDetailsList)
}

// 处理 药品 批次 库存 的 按钮
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
}

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

/** 退药按钮 */
function withdrawal() {
  proxy.$refs['patientDiagnosisRef'].validate(valid => {
    if (valid && form.value.status != 2) {
      if (form.value.patientDiagnosisId != null) {
        returnedMedication(form.value.patientDiagnosisId).then(response => {
          proxy.$modal.msgSuccess('退药成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
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/totalPriceExport',
    {
      ...queryParams.value
    },
    `patientDiagnosisListTotalPrice${new Date().getTime()}.xlsx`
  )
}

// 处方 列表 里面 输入框  点击 事件 处理 方法
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)
}

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

// 患者 诊断 信息 弹框
import DiagnosisInformation from '@/components/Healthcare/OutpatientService/DiagnosisInformation'
import DiagnosisInformationUse from '@/components/Healthcare/OutpatientService/DiagnosisInformation/use.ts'

const diagnosisInformationRef = ref(null)

let { controlDataDiagnosisInformation, styleDiagnosisInformation } = DiagnosisInformationUse()

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

// 判断文本是否超出限制长度（比如超过20个字符）
const isTextOverflow = (text) => {
  const maxLength = 12; // 根据实际情况调整这个值
  return text && text.length > maxLength;
};

// 获取 列表
getList()
</script>

<style>
.prescription {
  margin-bottom: 20px;
}

.el-form-item__label {
  padding: 0 10px 0 0;
}

.el-table--default .cell {
  padding: 0 5px;
}

.el-input.is-disabled .el-input__inner {
  -webkit-text-fill-color: #131416;
}

.el-select__wrapper.is-disabled .el-select__selected-item {
  color: #0e0f0f;
}

/* .el-input {
    width: 335px;
} */
/* 主诉等信息字体颜色 */
/* .el-textarea.is-disabled .el-textarea__inner {
    color: #202021;
} */
</style>
