<script setup lang="ts">
</script>

<template>
  <div class="prescription-module">
    <div style="width: 0; height: 0; overflow: hidden">
      <ImagePreviewGroup
        :preview="{
          visible,
          onVisibleChange: setVisible,
        }"
        :style="{ display: 'none' }"
      >
        <Image
          v-for="image in previewImage"
          v-if="visible === true"
          :src="image"
          :width="200"
        />
      </ImagePreviewGroup>
    </div>

    <!-- 患者信息 -->
    <Descriptions
      v-if="patientInfo"
      :column="{ xxl: 2, xl: 2, lg: 2, md: 2, sm: 2, xs: 2 }"
      bordered
      title="患者信息"
      class="mb-5"
    >
      <Descriptions.Item label="患者姓名">
        {{ patientInfo.user_patient?.name }}
      </Descriptions.Item>
      <Descriptions.Item label="患者年龄">
        {{ patientInfo.user_patient?.age }}
      </Descriptions.Item>
      <Descriptions.Item label="患者性别">
        {{
          patientInfo.user_patient?.sex === 1
            ? '男'
            : patientInfo.user_patient?.sex === 2
              ? '女'
              : '未填写'
        }}
      </Descriptions.Item>
    </Descriptions>

    <Descriptions
      v-if="userPatientHealthInquiry"
      :column="{ xxl: 2, xl: 2, lg: 2, md: 2, sm: 2, xs: 2 }"
      bordered
      class="mt-5 mb-5"
      title="健康信息"
    >
      <Descriptions.Item label="肝功能">
        <span>{{
            userPatientHealthInquiry.liver_function === 0 ? '正常' : '异常'
          }}</span>
        <p
          v-if="userPatientHealthInquiry.liver_function === 1"
          class="mt-3"
        >
          <Tag
            v-for="item in splitString(
              userPatientHealthInquiry.liver_index,
            )"
            color="#455cda"
          >
            {{ item }}
          </Tag>
        </p>
      </Descriptions.Item>
      <Descriptions.Item label="肾功能">
        <span>{{
            userPatientHealthInquiry.renal_function === 0 ? '正常' : '异常'
          }}</span>
        <p
          v-if="userPatientHealthInquiry.renal_function === 1"
          class="mt-3"
        >
          <Tag
            v-for="item in splitString(
              userPatientHealthInquiry.renal_index,
            )"
            color="#455cda"
          >
            {{ item }}
          </Tag>
        </p>
      </Descriptions.Item>
      <Descriptions.Item label="既往史">
        <span>{{
            userPatientHealthInquiry.person_status === 0 ? '无' : '有'
          }}</span>
        <p v-if="userPatientHealthInquiry.person_status === 1" class="mt-3">
          <Tag
            v-for="item in splitString(
              userPatientHealthInquiry.person_history,
            )"
            color="#455cda"
          >
            {{ item }}
          </Tag>
        </p>
      </Descriptions.Item>
      <Descriptions.Item label="过敏史">
        <span>{{
            userPatientHealthInquiry.allergic_status === 0 ? '无' : '有'
          }}</span>
        <p
          v-if="userPatientHealthInquiry.allergic_status === 1"
          class="mt-3"
        >
          <Tag
            v-for="item in splitString(
              userPatientHealthInquiry.allergic_history,
            )"
            color="#455cda"
          >
            {{ item }}
          </Tag>
        </p>
      </Descriptions.Item>
      <Descriptions.Item label="家庭遗传史">
        <span>{{
            userPatientHealthInquiry.family_status === 0 ? '无' : '有'
          }}</span>
        <p v-if="userPatientHealthInquiry.family_status === 1" class="mt-3">
          <Tag
            v-for="item in splitString(
              userPatientHealthInquiry.family_history,
            )"
            color="#455cda"
          >
            {{ item }}
          </Tag>
        </p>
      </Descriptions.Item>
    </Descriptions>

    <Descriptions
      :column="{ xxl: 1, xl: 1, lg: 1, md: 1, sm: 1, xs: 1 }"
      class="mt-5 mb-5"
      title="处方记录"
    >
      <Descriptions.Item>
        <Timeline>
          <TimelineItem v-for="item in prescriptionList" :key="item.id">
            <Tag color="#455cda">{{ item.prescription_no }}</Tag>
            <span class="time-line-item-created">{{
                item.created_at
              }}</span>
            <Tag class="ml-5" :color="item.category === 1? '' : '#455cda'">
              {{ item.prescription_type === 1 ? '中药处方' : item.prescription_type === 5 ? '产品服务包' : '西药处方' }} /
              {{ item.category === 1 ? '自费' : '医保' }}
            </Tag>

            <Tag v-if="item.status === 0" color="warning">待审核</Tag>
            <Tag v-else-if="item.status === 1" color="success">已通过</Tag>
            <Tag v-else-if="item.status === 2" color="error">未通过</Tag>
            <Tag v-else-if="item.status === 3" color="#455cda">无需审核</Tag>
            <Tag v-else-if="item.status === 4" color="#455cda">无需审核</Tag>
            <Tag color="#455cda">处方ID：{{ item.id }}</Tag>
          </TimelineItem>
        </Timeline>
      </Descriptions.Item>
    </Descriptions>

    <!-- 药品分类导航 -->
    <div class="drug-categories">
      <button
        v-for="categoryItem in categories"
        :key="categoryItem.value"
        :class="{ active: activeCategory === categoryItem.value }"
        @click="tabChange(categoryItem.value)"
      >
        {{ categoryItem.label }}
      </button>
    </div>

    <div class="mt-5">
      <RadioGroup
        v-model:value="category"
      >
        <RadioButton :value="1">自费</RadioButton>
        <RadioButton :value="2">医保</RadioButton>
      </RadioGroup>
    </div>

    <!-- 已选药品列表 -->
    <!-- 中药 -->
    <div v-if="activeCategory === 1" class="mb-5 mt-3 flex" style="flex-wrap: wrap; width: 100%;">
      <Row :gutter="[16, 16]">
        <Col
          v-for="(drug, index) in currentDrugs"
          :key="drug.id"
          :lg="12"
          :md="24"
          :sm="24"
          :xl="12"
          :xs="24"
          :xxl="8"
        >
          <Card class="mt-0 prescription-card" title="">
            <div>
              <span class="card-index">{{ index + 1 }}、</span>
              <p>
                <Select
                  v-model:value="drug.id"
                  :filter-option="false"
                  class="old-select-drug-name"
                  style="min-width: 100px"
                  placeholder="药名"
                  show-search
                  @change="selectOldDrugInfo"
                  @dropdown-visible-change="
                    setSelectChineseIndex(index, drug.id)
                  "
                  @search="searchOption"
                >
                  <SelectOption v-if="drugList.length === 0" :value="drug.id">
                    {{ drug.drug_name }}
                  </SelectOption>
                  <SelectOption
                    v-for="(value, index) in drugList"
                    v-else
                    :key="index"
                    :value="value.drug.id"
                  >
                    {{ value.drug.drug_name }}
                  </SelectOption>
                </Select>
                ,
                <InputNumber
                  v-model:value="drug.number"
                  :class="`w-1/5 old-number-input-${index}`"
                  style="min-width: 100px"
                  :controls="false"
                  @blur="updateChineseNumber"
                  @keydown="updateChineseNumberGoNewDrug($event)"
                >
                  <template #addonAfter> g</template>
                </InputNumber>
                ,
                <span>
                  <Select
                    :value="drug?.way_id"
                    placeholder="用法"
                    @change="selectDrugUseWayChange"
                    @dropdown-visible-change="
                      selectProductChange(drug.index_id)
                    "
                  >
                    <SelectOption :value="0">煎服</SelectOption>
                    <SelectOption
                      v-for="(value, index) in drugUseWay"
                      :key="index"
                      :value="value.id"
                    >
                      {{ value.name }}
                    </SelectOption>
                  </Select>
                </span>
                <p class="card-price">
                  ￥<span>{{ (drug.price * drug.number).toFixed(2) }}</span>
                </p>
                <Button
                  class="card-delete"
                  type="link"
                  @click="removeDrug(index)"
                >
                  <DeleteTwoTone/>
                </Button>
              </p>
            </div>
          </Card>
        </Col>
        <Col
          :lg="12"
          :md="24"
          :sm="24"
          :xl="12"
          :xs="24"
          :xxl="8"
        >
          <Card class="prescription-card" title="">
            <div>
              <span class="card-index">{{ currentDrugs.length + 1 }}、</span>
              <div>
                <Select
                  v-model:value="newDrugInfo.id"
                  :filter-option="false"
                  class="new-select-drug-name w-1/5"
                  style="min-width: 100px"
                  placeholder="药名"
                  show-search
                  @change="selectNewDrugInfo"
                  @search="searchOption"
                >
                  <SelectOption
                    v-for="(value, index) in drugList"
                    :key="index"
                    :value="value.drug_id"
                  >
                    {{ value.drug.drug_name }}
                  </SelectOption>
                </Select>
                ,
                <InputNumber
                  v-model:value="newDrugInfo.number"
                  class="new-number-input w-1/5"
                  style="min-width: 100px"
                  @blur="newDrugBlur"
                  @keydown="selectDrugByNewDrugInfo($event, true)"
                >
                  <template #addonAfter> g</template>
                </InputNumber>
                ,
                <span>
                  <Select
                    v-model:value="newDrugInfo.way_id"
                    placeholder="用法"
                    @keydown="selectDrugByNewDrugInfo($event, true)"
                  >
                    <SelectOption :value="0">煎服</SelectOption>
                    <SelectOption
                      v-for="(value, index) in drugUseWay"
                      :key="index"
                      :value="value.id"
                    >
                      {{ value.name }}
                    </SelectOption>
                  </Select>
                </span>
                <p class="card-price">
                  ￥<span>{{
                    (
                      (newDrugInfo.price || 0) * (newDrugInfo.number || 1)
                    ).toFixed(2)
                  }}元</span>
                </p>
              </div>
            </div>
          </Card>
        </Col>
      </Row>
    </div>

    <!-- 西（中成）药列表 -->
    <div v-else class="selected-drugs">
      <div class="drug-table">
        <div class="table-header">
          <span v-if="activeCategory !== 1">商品图片</span>
          <span>商品名称</span>
          <span>数量</span>
          <span>单价</span>
          <span>操作</span>
        </div>
        <div class="table-body">
          <div
            v-for="(drug, index) in currentDrugs"
            :key="drug.id"
            class="table-row"
          >
            <div
              v-if="activeCategory !== 1"
              style="width: 120px; margin: 0 auto"
            >
              <Image :src="drug.image"/>
            </div>
            <div>
              <p>
                <span>药品名称：{{ drug.drug_name }}</span>
              </p>
              <p>
                <span>用法：{{
                    `${drug.use_type?.name}，${drug.use_frequency?.name}，${drug.use_num?.name}，每次${drug.number}${drug.unit?.name}`
                  }}</span>
              </p>
            </div>
            <div>
              <div v-if="activeCategory === 1" class="quantity-control">
                <InputNumber
                  v-model:value="drug.select_number"
                  class="w-full"
                  @blur="updateChineseNumber"
                >
                  <template #addonAfter> g</template>
                </InputNumber>
              </div>
              <div v-else class="quantity-control">
                <Button type="primary" @click="decrement(index)">-</Button>
                <span style="margin: 0 20px">{{ drug.select_number }}</span>
                <Button type="primary" @click="increment(index)">+</Button>
              </div>
            </div>
            <span>{{ drug.price }}</span>
            <div>
              <Button type="link" @click="removeDrug(index)">删除</Button>
              <Button
                v-if="drug.instruction !== ''"
                type="link"
                @click="setVisible(true, drug.instruction)"
              >
                查看说明书
              </Button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 诊断和医嘱 -->
    <div class="diagnosis-area">
      <div v-if="activeCategory === 1" class="mb-5">
        <RadioGroup v-model:value="ruleType">
          <RadioButton :value="1">自制剂</RadioButton>
          <RadioButton :value="2">委托调剂</RadioButton>
        </RadioGroup>
        <div v-if="ruleType === 1">
          <!-- 选择包法-->
          <Select
            :value="packageMethodId"
            class="mt-3 w-1/5"
            placeholder="请选择包法"
            @change="selectPackageMethod"
          >
            <SelectOption
              v-for="(value, index) in packageMethod"
              :key="index"
              :value="value.value"
            >
              {{ value.label }}
            </SelectOption>
          </Select>
        </div>
        <div v-else-if="ruleType === 2">
          <!-- 选择制剂-->
          <Select
            v-model:value="processRuleId"
            class="mt-3 w-1/5"
            placeholder="请选择制剂"
            @change="selectProcessRule"
          >
            <SelectOption
              v-for="(value, index) in processRuleList"
              :key="index"
              :value="value.id"
            >
              {{ value.name }}
            </SelectOption>
          </Select>
          <!-- 选择规格-->
          <Select
            v-model:value="childProcessRuleId"
            class="ml-3 mt-3 w-1/5"
            placeholder="请选择煎法"
            @change="selectProcessRuleNot"
          >
            <SelectOption
              v-for="(value, index) in childProcessRuleList"
              :key="index"
              :value="value.id"
            >
              {{ value.name }}
            </SelectOption>
          </Select>
          <!-- 选择备注-->
          <Select
            v-model:value="processRuleNoteId"
            class="ml-3 mt-3 w-1/5"
            placeholder="请选择备注"
            @change="selectProcessRuleNotCommit"
          >
            <SelectOption
              v-for="(value, index) in processRuleNoteList"
              :key="index"
              :value="value.id"
            >
              {{ value.note }}
            </SelectOption>
          </Select>
        </div>
        <div class="mt-5">
          用量：
          <InputNumber v-model:value="dosage" class="w-1/5">
            <template #addonBefore>
              <MinusOutlined
                key="prop"
                @click="dosage = dosage > 1 ? dosage - 1 : 1"
              />
            </template>
            <template #addonAfter>
              <PlusOutlined
                key="add"
                @click="dosage = dosage < 100 ? dosage + 1 : 100"
              />
            </template>
          </InputNumber>
          天 / {{ dosage }} 剂
        </div>
        <div class="mt-5">
          频次：
          <InputNumber v-model:value="dayDosage" class="w-1/5">
            <template #addonBefore>
              <MinusOutlined
                key="prop"
                @click="dayDosage = dayDosage > 1 ? dayDosage - 1 : 1"
              />
            </template>
            <template #addonAfter>
              <PlusOutlined
                key="add"
                @click="dayDosage = dayDosage < 100 ? dayDosage + 1 : 100"
              />
            </template>
          </InputNumber>
          次/天
        </div>
      </div>

      <Textarea v-model:value="diagnosis" placeholder="输入诊断结果..." class="mb-3"/>
      <Textarea v-model:value="medicalAdvice" placeholder="输入医嘱..." class="mb-3"/>

      诊疗费用：
      <InputNumber
        v-model:value="treatmentPrice"
        placeholder="请输入诊疗价格"
        class="mb-3"
      >
        <template #addonAfter> /元</template>
      </InputNumber>
    </div>

    <!-- 费用总计 -->
    <div class="price-box">
      <div class="total-cost">加工费：¥{{ processingFee.toFixed(2) }}</div>
      <div class="total-cost">
        商品价格：¥{{ totalProductCost.toFixed(2) }}
      </div>
      <div class="total-cost">总计：¥{{ totalCost.toFixed(2) }}</div>

      <Button class="mt-5 w-full" style="display: block" type="primary" @click="checkChineseMedicineConflict">
        发送处方
      </Button>
    </div>

    <Modal v-model:open="showNewDrugModal" @ok="newDrugModalOk">
      要把【{{ newDrugInfo.name }}】添加到清单吗？
    </Modal>
    <Modal title="二次签名" v-model:open="doctorSecondSignModal" @ok="doctorSecondSignModalOk">
      <div class="doctor-second-sign-title">有毒：</div>
      <p v-for="item in checkData.message?.poisonous || []">【{{ item }}】</p>
      <div class="doctor-second-sign-title">十八反：</div>
      <p v-for="item in checkData.message?.opposition || []">【{{ item }}】</p>
      <div class="doctor-second-sign-title">十九畏：</div>
      <p v-for="item in checkData.message?.conflict || []">【{{ item }}】</p>
      <p class="mt-5" style="color: red;">如需继续开方需要二次签名，确认要二次签名吗？</p>
    </Modal>
  </div>
</template>

<style scoped>
.doctor-second-sign-title {
  font-size: 16px;
  margin: 10px 0;
  font-weight: bold;
  border-left: 5px solid rgb(55, 71, 162);
  padding-left: 10px;
}

.card-index {
  font-size: 20px;
  font-weight: bold;
  position: absolute;
  left: 10px;
  top: 0;
}

.card-price {
  position: absolute;
  bottom: 10px;
  right: 8px;
  color: red;
}

.card-delete {
  position: absolute;
  top: 3px;
  right: 0;
}

.prescription-card {
  position: relative;
  min-height: 120px;
}

.drug-categories {
  display: flex;
  gap: 1rem;
  margin: 1rem 0;
}

.drug-categories button {
  padding: 8px 16px;
  border: 1px solid #ddd;
  border-radius: 10px;
  cursor: pointer;
  background: transparent;
  color: inherit;
}

.dark .drug-categories button {
  border: 1px solid #333;
}

.drug-categories button.active {
  color: #fff;
  border-color: transparent;
  animation: pulse 0.5s /*infinite*/;
  animation-fill-mode: forwards;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    background: #455cda;
    transform: scale(1);
  }
}

.selected-drugs {
  margin: 1rem 0;
  border: 1px solid #eee;
  border-radius: 8px;
}

.dark .selected-drugs {
  border: 1px solid #333;
}

.table-body {
  max-height: 30vh;
  overflow-y: auto;
}

.table-header {
  display: grid;
  grid-template-columns: 0.5fr 1fr 1fr 1fr 1fr;
  padding: 12px;
  font-weight: bold;
  text-align: center;
}

.table-row {
  display: grid;
  grid-template-columns: 0.5fr 1fr 1fr 1fr 1fr;
  padding: 12px;
  border-bottom: 1px solid #eee;
  text-align: center;
  height: auto;
  align-items: center;
}

.dark .table-row {
  border-bottom: 1px solid #333;
}

.diagnosis-area textarea {
  width: 100%;
  height: 100px;
  padding: 8px;
  margin: 8px 0;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: transparent;
  color: inherit;
}

.dark .diagnosis-area textarea {
  border: 1px solid #333;
}

.price-box {
  margin-top: 20px;
}

.total-cost {
  text-align: right;
  font-size: 1.2em;
  font-weight: bold;
  color: #f56c6c;
  margin-top: 1rem;
}

.time-line-item-created {
  color: #909399;
  font-size: 0.8em;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .drug-categories {
    flex-wrap: wrap;
  }

  .table-header,
  .table-row {
    grid-template-columns: 1fr 1fr 1fr;
  }

  .table-header span:nth-child(4),
  .table-header span:nth-child(5),
  .table-row > span:nth-child(4),
  .table-row > div:nth-child(5) {
    display: none;
  }
}
</style>