<template>
  <view class="container" v-if="showCon">
    <view class="content pb150">
      <!-- 医生信息 -->
      <view class="user p_flexCenter" v-if="serviceType !== 'tdwz'">
        <image class="user_img" :src="queryBean.DoctorPhotourl"></image>
        <view class="user_box p_flexBetween">
          <view class="user_con p_flexCenter">
            <view class="user_name">{{ queryBean.DoctorName }}</view>
            <view class="user_tip">{{ queryBean.DeptName }} {{ queryBean.TitleName }}</view>
          </view>
        </view>
      </view>

      <!-- 团队问诊 -->
      <view v-if="serviceType == 'tdwz'" class="group_box displayFlexCol">
        <text class="group_title">{{ queryBean.GroupName }}</text>
        <view class="group_introduce">
          <text>擅长：</text>
          <text>{{ queryBean.GroupSkill }}</text>
        </view>
      </view>

      <!-- 就诊人信息 -->
      <view class="block">
        <view class="member p_flexBetween">
          <view class="member_con">
            <view class="member_info_con p_flexCenter">
              <view class="member_name">{{ currentUser.MemberName || currentUser.memberName }}</view>
              <view class="member_info">{{ currentUser.Sex == 1 || currentUser.sex == 1 ? '男' : '女' }} {{ currentUser.Age || currentUser.age }}岁</view>
            </view>
            <view class="member_id p_color_6">身份证号：{{ currentUser.CertNum || currentUser.certNum }}</view>
          </view>
          <view class="member_btn p_bgcolor p_flexCenter" @click="selectMember">换个就诊人</view>
        </view>

        <!-- 是否初诊 -->
        <view class="info p_format">
          <view class="info_box p_flexBetween p_border_top">
            <view class="info_tit">是否初诊</view>
            <view class="radios p_flexCenter">
              <view
                class="radio_item p_flexCenter"
                :class="followUp ? 'p_color_6' : 'p_color_9'"
                @click="diagnosisClick('other')"
              >
                <image class="radio_item_img" :src="diagnosisType == 'other' && !isFirstVisit ? iconUrl.circle_active : iconUrl.circle"></image>
                复诊
              </view>
            </view>
          </view>
        </view>

        <!-- 问诊目的 -->
        <view class="info">
          <view class="info_box p_border_top p_flexBetween" @click="purSelect">
            <view class="info_tit">本次问诊目的</view>
            <view class="info_val_con p_flexBetween">
              <view class="info_val p_color_9">{{ purSelected.tit || '选择本次问诊目的' }}</view>
              <image class="info_right" :src="iconUrl.home_right"></image>
            </view>
          </view>

          <!-- 处方信息 -->
          <view class="info_box p_border_top" v-if="diagnosisType == 'other' && (purSelected.key == 'yyzx' || purSelected.key == 'fzxf')">
            <view class="info_box_inner p_flexBetween" @click="prescSelect">
              <view class="info_tit">处方信息<text class="info_subtit p_color_9">（可选项）</text></view>
              <view class="info_val_con p_flexBetween">
                <view class="info_val p_color_9">选择处方记录</view>
                <image class="info_right" :src="iconUrl.home_right"></image>
              </view>
            </view>
            <view class="info_pres" v-if="recSelected.HisOrderId">
              <view class="info_pres_con p_flexBetween">
                <view class="info_pres_inner p_flexCenter">
                  <view class="info_pres_time p_color_9">{{ recSelected.Registerdate }}</view>
                  <view class="info_pres_tit">{{ recSelected.DeptName }} {{ recSelected.DoctorName }}</view>
                  <view class="info_pres_subtit p_color_6"><text class="report_item_val_titval">诊断：</text>{{ recSelected.Diagnosis }}</view>
                </view>
                <view class="info_pres_detailbtn p_bgcolor p_flexCenter" @click="setVal('showPrescDetailDialog', true)">查看详情
                  <image class="info_doctor_arrow" :src="iconUrl.doctor_arrow_bottomf"></image>
                </view>
              </view>
              <view class="info_pres_btns p_flexCenter p_border_top">
                <view class="info_pres_btn p_flexCenter p_border p_color" @click="prescSelect">重新选择</view>
                <view class="info_pres_btn p_flexCenter p_border p_color" @click="clearPur">清空处方</view>
              </view>
            </view>
          </view>

          <!-- 咨询时间 -->
          <view class="info_box p_flexBetween p_border_top" @click="consultSelect">
            <view class="info_tit">咨询时间<text class="info_subtit p_color_9">（必选项）</text></view>
            <view class="info_val_con p_flexBetween">
              <view class="info_val p_color" v-if="!consultDate.Data_1">{{ earlyTime }}</view>
              <view class="info_val p_color" v-else>
                {{ consultDate.Data_1[consultDateIndSelected]?.RegDate }}
                {{ consultTimeList[consultTimeIndSelected]?.CommendTime }}
              </view>
              <image class="info_right" :src="iconUrl.home_right"></image>
            </view>
          </view>
        </view>
      </view>

      <!-- 病情采集 -->
      <view class="block">
        <view class="info">
          <view class="info_box p_border_bottom">
            <view class="info_box_inner p_flexBetween">
              <view class="info_tit">病情采集<text class="info_subtit p_color_9">（必选项）</text></view>
            </view>
          </view>
          <view class="info_box" style="padding-top: 30upx;" v-if="!illness.MedicalInfo">
            <textarea
              class="info_box_textarea"
              :disabled="disabledArea"
              placeholder-class="placeholder"
              auto-height
              maxlength="200"
              placeholder="请详细描述您的症状、疾病、身体状况等,越详细越好,便于医生更准确得为您分析解答..."
              @input="inputVal"
              :data-key="'illnessInfo'"
              :value="illnessInfo"
            ></textarea>
            <view class="text_tip_box p_flexBetween">
              <view class="text_tip p_border p_flexCenter p_color" @click="setVal('showExampleDialog', true)">查看示例</view>
              <view class="text_num p_color_9"><text class="p_color_3">{{ illnessInfo?.length || 0 }}</text>/200</view>
            </view>
          </view>
        </view>
      </view>

      <!-- 添加图片 -->
      <view class="block">
        <view class="info">
          <view class="info_box">
            <view class="info_tit">添加图片<text class="info_subtit p_color_9">（可选项，图片不超过8张）</text></view>
            <view class="coll_con">
              <view class="coll_img_con p_flexBetween" v-if="imgList.length > 0">
                <view
                  class="coll_con_img_box"
                  v-for="(item, index) in imgList"
                  :key="index"
                  @click="showImg(index)"
                >
                  <image class="coll_con_img" :src="item" mode="aspectFit"></image>
                  <image class="doctor_cha" :src="iconUrl.doctor_cha" @click.stop="delImg(index)"></image>
                </view>
              </view>
            </view>
            <view class="coll_con p_flexBetween">
              <view class="coll_img_box p_flexCenter" @click="addImg('imgList')">
                <image class="coll_img" :src="iconUrl.doctor_jia"></image>
              </view>
              <view class="coll_tip p_color_9">
                为了提升医患双方的沟通效率，系统将通过AI预问诊的形式详细采集您的主诉、现病史、既往史、过敏史等病情相关信息，敬请理解与配合!(点击左侧+按钮开始采集)
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 希望得到的帮助 -->
      <view class="block">
        <view class="info">
          <view class="info_box">
            <view class="info_tit">希望得到的帮助<text class="info_subtit p_color_9">（可选项）</text></view>
            <textarea
              class="info_box_textarea info_box_help"
              :disabled="disabledArea"
              auto-height
              placeholder-class="placeholder"
              maxlength="200"
              placeholder="请详细描述您的症状、疾病、身体状况等,越详细越好,便于医生更准确得为您分析解答..."
              :value="helpInfo"
              @input="inputVal"
              :data-key="'helpInfo'"
            ></textarea>
            <view class="text_tip_box p_flexBetween">
              <view></view>
              <view class="text_num p_color_9"><text class="text_num_now p_color_3">{{ helpInfo?.length || 0 }}</text>/200</view>
            </view>
          </view>
        </view>
      </view>

      <!-- 提交按钮 -->
      <view class="p_btn_con">
        <view class="p_form p_btn" @click="submitFnClick">
          <button
            class="p_form_btn p_flexCenter p_bgcolor"
            :class="{ 'btnBgcolor': !getNext }"
            v-if="!isFirstVisit"
          >
            提交咨询({{ selectedType == 'twzx' ? queryBean.consultFeeDiy : selectedType == 'dhzx' ? queryBean.phoneFeeDiy : selectedType == 'spzx' ? queryBean.videoFeeDiy : 0 }}元)
          </button>
          <button
            v-if="isFirstVisit || options.serviceType == 'hzzx'"
            class="p_form_btn p_flexCenter"
            :class="[(selectedType == 'spzx' || selectedType == 'twzx') && consultDate.Data_1?.length > 0 || onlyCons ? 'backgroundCustom' : 'backgroundCustom_D9', { 'btnBgcolor': !getNext }]"
          >
            提交咨询(免费)
          </button>
        </view>
      </view>

      <!-- 问诊目的弹窗 -->
      <view class="p_mask p_flexCenter p_mask_bottom" v-if="showPurDialog">
        <view class="p_dialog">
          <view class="p_dialog_tit p_flexCenter">
            <view class="p_dialog_tit_val">请选择问诊目的</view>
            <image class="p_dialog_cha" :src="iconUrl.doctor_cha" @click="setValAndClose('purClick', purSelected)"></image>
          </view>
          <view class="p_dialog_inner p_format p_scroll">
            <view class="pur_list">
              <view
                class="pur_item p_border_bottom p_flexCenter"
                v-for="(item, index) in filteredPurList"
                :key="index"
                @click="setVal('purClick', item)"
              >
                <image class="pur_icon" :src="item.key == purClick.key ? iconUrl.circle_active : iconUrl.circle"></image>
                <view class="pur_con">
                  <view class="pur_tit">{{ item.tit }}</view>
                  <view class="pur_subtit p_color_9">{{ item.subtit }}</view>
                </view>
              </view>
            </view>
          </view>
          <view class="p_dialog_btn_list p_flexBetween">
            <view class="p_dialog_btn p_border p_flexCenter" @click="setValAndClose('purClick', purSelected)">取消</view>
            <view class="p_dialog_btn p_flexCenter p_bgcolor" @click="purConfirm">确定</view>
          </view>
        </view>
      </view>

      <!-- 示例弹窗 -->
      <view class="p_mask p_flexCenter" v-if="showExampleDialog">
        <view class="p_dialog p_dialog_center">
          <view class="p_dialog_tit p_flexCenter">
            <view class="p_dialog_tit_val">示例</view>
          </view>
          <view class="p_dialog_inner p_format p_scroll">
            <view class="example_con">
              <view class="example_val p_color_6">
                3天前崴了脚，当时感觉有点疼，但是还可以走路，所以冰敷了10分钟。昨天疼的有点厉害就涂了点红花油，今天发现有点肿了，我需要去医院拍片子看一下吗?
              </view>
              <image class="example_img" :src="iconUrl.doctor_back"></image>
            </view>
          </view>
          <view class="p_dialog_longbtn p_flexCenter p_color p_border_top" @click="closeDialog">我已知晓</view>
        </view>
      </view>

      <!-- 选择咨询时间弹窗 -->
      <view class="p_mask p_flexCenter p_mask_bottom" v-if="showConsultDialog">
        <view class="p_dialog">
          <view class="p_dialog_tit p_flexCenter">
            <view class="p_dialog_tit_val">选择咨询时间</view>
            <image class="p_dialog_cha" :src="iconUrl.doctor_cha" @click="closeDialog"></image>
          </view>
          <view class="p_dialog_inner p_format">
            <view class="date_list p_scroll">
              <view
                class="date_item p_border_right p_color"
                :class="[
                  index == consultDateIndClick ? 'date_item_ac' : '',
                  item.IsHalt == '7' || item.IsHalt == '2' ? 'p_color_9' : 'p_color_6'
                ]"
                v-for="(item, index) in consultDate.Data_1 || []"
                :key="index"
                @click="consultDateClick(index)"
              >
                <image class="date_item_icon" :src="iconUrl.doctor_stop" v-if="item.IsHalt == '7' || item.IsHalt == '2'"></image>
                {{ formatDate(item.RegDate) }} {{ item.WeekName }} {{ item.TimeSliceStr }}
              </view>
            </view>
            <view class="num_con p_format p_scroll">
              <view class="num_tit">
                咨询费用：
                <text class="num_tit_price">{{ queryBean.videoFeeDiy || 0 }}元</text>
              </view>
              <view class="num_list p_flexCenter">
                <view
                  class="num_item p_flexCenter"
                  :class="[
                    index == consultTimeIndClick ? 'p_border num_item_ac' : ''
                  ]"
                  v-for="(item, index) in consultTimeList"
                  :key="index"
                  @click="setVal('consultTimeIndClick', index)"
                >
                  <image class="num_item_img" :src="iconUrl.doctor_selected" v-if="index == consultTimeIndClick"></image>
                  <view class="num_item_ind" :class="index == consultTimeIndClick ? 'p_color' : 'p_color_6'">
                    {{ item.SqNo }}号
                  </view>
                  <view class="num_item_time" :class="index == consultTimeIndClick ? 'p_color' : 'p_color_9'">
                    {{ item.CommendTime }}
                  </view>
                </view>
              </view>
            </view>
          </view>
          <view class="p_dialog_btn_list p_flexBetween">
            <view class="p_dialog_btn p_border p_flexCenter" @click="cinsultCancel">取消</view>
            <view class="p_dialog_btn p_flexCenter p_bgcolor" @click="cinsultConfirm">确定</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 三个月内无就诊记录弹窗 -->
    <view class="mask displayFlexRow" v-if="!isHistory">
      <view class="non_record_box displayFlexCol">
        <text class="non_record_title">复诊须知</text>
        <view class="non_record_main displayFlexCol">
          <text>1、您暂无本院的就诊记录，建议您的健康需求均先选择我院进行线下就诊，未来移步至互联网医院进行线上复诊时将更好的享受医保待遇；</text>
          <text>2、若您有其他医院的病历、处方单、报告单，选择【我要上传】，上传提供给医生确认;</text>
          <text>3、若您无法提供就诊病历信息，建议选择【线下预约】，到院就诊，感谢您的支持！</text>
        </view>
        <view class="non_record_btn displayFlexCol">
          <text
            class="backgroundCustom_4aa7fe"
            v-if="serviceType == 'tdwz' && queryBean.EnableFirstApply == 1"
            @click="firstVisit"
          >
            初诊咨询（免费，不可开单）
          </text>
          <text class="backgroundCustom" @click="outerHos">我要上传</text>
          <text class="backgroundCustom_D9" @click="toHome">返回</text>
        </view>
      </view>
    </view>

    <!-- 隐藏的 canvas 用于图片压缩 -->
    <canvas canvas-id="pressCanvas" class="press-canvas" :style="'width: ' + windowWidth + 'px; height: ' + windowHeight + 'px;'"></canvas>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, getCurrentInstance, computed } from 'vue'
import { useOnLoad } from '@/hook'
import { onShow } from '@dcloudio/uni-app'
import icon from '@/utils/icon'
import { common } from '@/uni-app-base/utils'
import {
  queryConsultWaterList,
  queryConsultRoomList,
  queryClinicDoctorSchedule,
  queryNumbers,
  lockOrder,
  unlock,
  applyImgTxtConsult,
  applyVideoConsult,
  applyDoctorGroupConsult,
  QueryOutpatientVisitList
} from '@/pagesNetHos/st1/service/doctor'
import { queryArticleList } from '@/pagesNetHos/st1/service/news'
import { queryCardBalance_V3 } from '@/pagesNetHos/st1/service/order'
import { REQUEST_CONFIG } from '@/config'

const { proxy } = getCurrentInstance()
const app = getApp() as any

// 页面数据
const showCon = ref(true)
const iconUrl = ref(icon)
const like = ref(false)
const showPurDialog = ref(false)
const currentUser = ref<any>({})
const showRecDialog = ref(false)
const showExampleDialog = ref(false)
const showMemberDialog = ref(false)
const showConsultDialog = ref(false)
const consultDate = ref<any>({})
const consultTimeList = ref<any[]>([])
const consultDateIndClick = ref(0)
const consultDateIndSelected = ref(0)
const consultTimeIndClick = ref(0)
const consultTimeIndSelected = ref(0)

const purClick = ref<any>({})
const purSelected = ref<any>({})
const selectedType = ref('')
const diagnosisType = ref("other")
const imgList = ref<any[]>([])
const imgListSave = ref<any[]>([])
const imgPrescList = ref<any[]>([])
const imgPrescListSave = ref<any[]>([])
// 就诊记录
const recQueryData = reactive({
  BeginDate: '',
  EndDate: '',
  ClinicCard: "",
  MemberId: "",
})
const recDateIndex = ref(3)
const recList = ref<any[]>([])
const recClick = ref<any>({})
const recSelected = ref<any>({})
const showPrescDetailDialog = ref(false)

//// 创建 字符串key -> ref变量 的映射表
const refMap = {
  showPrescDetailDialog,
  showExampleDialog,
  purClick,
  consultTimeIndClick,
};

// 问诊目的列表
const purList = ref([
  {
    id: "2",
    tit: "在线复诊",
    subtit: "针对复诊患者病情情况给出诊疗建议(可开处方或检验检查的医嘱)。",
    type: "other",
    key: "zxfz",
    isShow: "1",
    value: ""
  }
])

// 过滤后的问诊目的列表（解决 v-for 与 v-if 混用问题）
const filteredPurList = computed(() => {
  return purList.value.filter((item: any) => item.type == diagnosisType.value && item.isShow == '1')
})

// 报告单
const reportQueryData = reactive({
  CardType: "",
  CardNo: "",
  MemberId: "",
  PatientName: "",
  StartDate: "",
  EndDate: "",
  ReportType: '0',
  Data_1: {
    queryType: "1",
  },
  Page: {
    PIndex: 1,
    PSize: 10
  }
})
const reportList = ref<any[]>([])
const showReportListDialog = ref(false)

// 其他数据
const followUp = ref(false)
const article = ref("")
const illness = ref<any>({})
const illnessInfo = ref("")
const helpInfo = ref("")
const earlyTime = ref("")
const loadFirst = ref(true)
const getNext = ref(false)
const disabledArea = ref(false)
const hasRecord = ref(false)

// 窗口尺寸
const windowWidth = ref(375)
const windowHeight = ref(667)

// 页面参数
const options = ref<any>({})
const queryBean = ref<any>({})
const serviceType = ref("")
const isHistory = ref(true)
const isFirstVisit = ref(false)
const isOuterHos = ref(false)
const onlyCons = ref(false)
const netHospageConfig = ref<any>({})

let timeIndex = 0
let submitFnClickIs = true

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 生命周期
useOnLoad((optionsData: any) => {
  // 初始化参数
  const queryBeanStr = optionsData.queryBean ? common.parse(optionsData.queryBean) : {}
  queryBean.value = queryBeanStr
  options.value = optionsData
  selectedType.value = optionsData.selectedType
  serviceType.value = optionsData.serviceType

  // 获取屏幕尺寸
  const systemInfo = uni.getSystemInfoSync()
  windowWidth.value = systemInfo.windowWidth
  windowHeight.value = systemInfo.windowHeight
  netHospageConfig.value = common.deepCopy(app.globalData.config.net_pageConfiguration_patient.netHos_orderPayment_config)

  // 初始化日期
  initDateQuery()
})

// 初始化日期查询参数
const initDateQuery = () => {
  const now = new Date()
  const sixMonthsAgo = new Date(now.getTime() - 180 * 24 * 60 * 60 * 1000)
  recQueryData.BeginDate = common.dateFormat(sixMonthsAgo).formatDay
  recQueryData.EndDate = common.dateFormat(now).formatDay
  reportQueryData.StartDate = common.dateFormat(now).formatDay
  reportQueryData.EndDate = common.dateFormat(now).formatDay
}

// 页面显示
onShow(() => {
  closeDialog()
  initPurList()
  getTimeEarly()
  main()
})

// 初始化问诊目的列表
const initPurList = () => {
  let list = purList.value
  const qb = queryBean.value
  const st = serviceType.value

  list.forEach((item: any) => {
    // 用药咨询只在图文咨询中展示
    if (item.key == "yyzx") {
      item.isShow = options.value.selectedType == "twzx" ? "1" : "0"
    }
    // 新冠入口只保留新冠咨询
    if (options.value.selectedType == "xgzx") {
      item.isShow = item.key == "xgzx" ? "1" : "0"
    }
    // 即时问诊开启后执行
    if (qb.doctorService1005 == 1) {
      item.isShow = "0"
    }
    // 团队问诊执行
    if (st == "tdwz") {
      item.isShow = item.key == "tdwz" ? "1" : "0"
    }
  })

  // 即时问诊
  if (qb.doctorService1005 == 1) {
    const obj = {
      id: "10",
      tit: "即时问诊",
      subtit: "",
      type: "other",
      key: "jswz",
      isShow: "1",
      value: ""
    }
    list = [obj]
  } else if (serviceType.value == "tdwz") {
    const obj = {
      id: "11",
      tit: "团队问诊",
      subtit: "",
      type: "other",
      key: "tdwz",
      isShow: "1",
      value: ""
    }
    list = [obj]
  }

  purList.value = list

  // 设置当前就诊人
  currentUser.value = app.globalData.currentUser || {}

  // 根据 serviceType 设置选中项
  if (common.isNotEmpty(serviceType.value)) {
    purList.value.forEach((item: any) => {
      if (item.key == serviceType.value) {
        purSelected.value = item
      }
    })
  }
}

// 主逻辑
const main = async () => {
  submitFnClickIs = true
  getNext.value = true

  const user = currentUser.value

  // 检查就诊人
  if (common.isEmpty(user)) {
    return
  }

  if (!user || !user.cardNo) {
    common.showModal('当前就诊人暂无就诊卡，请选择其他就诊人进行咨询')
    getNext.value = false
    return
  }

  // 是否有待支付订单
  if (await queryConsultStatus('0')) {
  }
  // 是否有正在咨询的订单
  if (options.value.serviceType !== "tdwz" && await queryConsultStatus('2')) {
  }

  let followUpStatus = false

  // 获取互联网复诊协议
  const tipsRespData = {
    Status: 1,
    HosId: app.globalData.hosId,
    TypeClass: '99'
  }

  const { resp: queryArticleListResp } = await queryArticleList(tipsRespData)
  if (!common.isEmpty(queryArticleListResp)) {
    article.value = unescape(queryArticleListResp[0].Contents).replace(/ style=".*?"/g, '')
  }

  queryOutpatientVisitList(serviceType.value == 'tdwz' ? 'history' : '')

  followUpStatus = true
  followUp.value = followUpStatus
  loadFirst.value = false
  hasRecord.value = false
  isFirstVisit.value = false
}

// 查询咨询记录状态
const queryConsultStatus = async (consultStatus: string) => {
  const user = currentUser.value
  const qb = queryBean.value

  const data = {
    ConsultStatus: consultStatus,
    DoctorUid: qb.DoctorUid,
    MemberId: user.memberId,
    IsHistory: '1'
  }

  let { resp } = await queryConsultWaterList(data)

  if (!common.isEmpty(resp)) {
    if (consultStatus == '0') {
      let url = `/pagesNetHos/st1/business/enquire/enquireList/enquireList`
      if (resp[0].ConsultType == '2') {
        url += `?consultType=2&pageType=2`
      }
      common.showModal(`就诊人【${user.memberName}】与【${qb.DoctorName}】医生之间已经存在了一条待支付订单，是否马上去支付？`, () => {
        common.goToUrl(url)
      }, { confirmText: "去支付" })
      return true
    }
    if (resp[0].ConsultType == '2') {
      common.showModal(`就诊人【${user.memberName}】与【${qb.DoctorName}】医生之间已经存在了一条视频咨询订单,请等待医生唤起视频`, () => {
        getNext.value = false
      }, { confirmText: "确定" })
      return true
    }
    common.showModal(`就诊人【${user.memberName}】与【${qb.DoctorName}】医生之间已经存在了一条咨询中订单，快去和医生沟通吧！`, async () => {
      const roomData = {
        MemberIds: user.memberId,
        DoctorUid: qb.DoctorUid
      }
      let { resp: roomList } = await queryConsultRoomList(roomData)
      if (!common.isEmpty(roomList)) {
        roomList[0].ConsId = resp[0].ConsId
        let url = `/pagesNetHos/st1/business/consult/consultChat/consultChat`
        let dataStr = "?conItem=" + common.stringify(roomList[0]) + "&goBottom=1&consultType=" + roomList[0].ConsultType
        common.goToUrl(url, { data: dataStr })
      }
    }, { cancelText: "取消", confirmText: "去沟通" })
  }
  return !common.isEmpty(resp)
}

// 选择就诊人
const selectMember = () => {
  const url = `/pagesPersonal/st1/business/patientManagement/selecteCardOrHos/selecteCardOrHos?fromComponent=true&type=card`
  common.goToUrl(url)
}

// 复诊初诊点击
const diagnosisClick = (value: string) => {
  if (!followUp.value && value == 'other') {
    return
  }
  diagnosisType.value = value
  purSelected.value = {}
  purClick.value = {}
  imgPrescList.value = []
  imgPrescListSave.value = []
  imgList.value = []
  imgListSave.value = []
}

// 选择问诊目的
const purSelect = () => {
  if (common.isEmpty(purClick.value)) {
    const found = purList.value.find((item: any) => item.isShow == '1' && item.type == diagnosisType.value)
    if (found) {
      purClick.value = found
    }
  }
  showPurDialog.value = true
}

// 问诊目的确认
const purConfirm = () => {
  if (purSelected.value.id !== purClick.value.id) {
    recList.value = []
    recClick.value = {}
    recSelected.value = {}
  }
  purSelected.value = purClick.value
  closeDialog()
}

// 选择复诊信息
const subSelect = () => {
  recDateIndex.value = 3
  const now = new Date()
  const sixMonthsAgo = new Date(now.getTime() - 180 * 24 * 60 * 60 * 1000)
  recQueryData.BeginDate = common.dateFormat(sixMonthsAgo).formatDay
  recQueryData.EndDate = common.dateFormat(now).formatDay
}

// 选择处方
const prescSelect = () => {
  showRecDialog.value = true
}

// 清空处方
const clearPur = () => {
  recSelected.value = {}
}

// 处方详情弹窗显示
const prescDetailDialogShow = () => {
  showPrescDetailDialog.value = true
}

// 添加图片
const addImg = (key: string) => {
  const imgDataList = imgList.value
  if (imgDataList.length >= 8) {
    common.showToast("图片最多不超过8张")
    return
  }
  const count = 8 - imgDataList.length
  uni.chooseImage({
    count: count,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    success: async (res) => {
      const tempFilePaths = res.tempFilePaths
      common.showLoading()
      for (let i = 0; i < tempFilePaths.length; i++) {
        const uploadRes = await uploadZxFile(tempFilePaths[i])
        if (uploadRes.RespCode == '10000') {
          let url = uploadRes.url.indexOf('http') == -1
            ? REQUEST_CONFIG.BASE_URL + uploadRes.url.replace(/\\/g, "/")
            : uploadRes.url.replace(/\\/g, "/")
            console.log(url,'urlurlurl')
          imgList.value.push(url)
          imgListSave.value.push(url)
        } else {
          common.showModal(uploadRes.RespMessage)
        }
      }
      common.hideLoading()
    }
  })
}

// 上传图片
const uploadZxFile = (url: string) => {
  return new Promise((resolve) => {
    uni.uploadFile({
      url: REQUEST_CONFIG.BASE_URL + '/upload/uploadZxFile.do',
      filePath: url,
      name: 'newsFile',
      formData: {
        user: 'test'
      },
      header: {
        token: uni.getStorageSync('token')
      },
      success(res) {
        resolve(JSON.parse(res.data))
      }
    })
  })
}

// 获取最早可约时间
const getTimeEarly = async () => {
  const qb = queryBean.value
  const user = currentUser.value
  const st = selectedType.value
  const opt = options.value

  const dateListData = {
    HosId: app.globalData.hosId,
    DeptCode: qb.DeptCode,
    DoctorCode: qb.DoctorCode,
    DoctorTitleCode: "",
    SourceType: opt.serviceType == "jswz" ? "fast" : st == "twzx" ? "019" : "006",
    ServiceId: '0',
    WeekType: '1',
    Store: {
      cardEncryptionStore: user.encryptionStore || '',
      baseMemberEncryptionStore: user.baseMemberEncryptionStore
    },
  }

  // 团队问诊入参
  if (opt.serviceType == "tdwz") {
    dateListData.DoctorCode = `group${qb.GroupId}`
    dateListData.SourceType = `group`
  }

  let { resp: dateListResp, resData: resData } = await queryClinicDoctorSchedule(dateListData)

  if (!common.isEmpty(dateListResp)) {
    consultDate.value = dateListResp[0]
    for (let i = 0; i < consultDate.value.Data_1.length; i++) {
      if (consultDate.value.Data_1[i].IsHalt !== '7' && consultDate.value.Data_1[i].IsHalt !== '2') {
        timeIndex = i
        break
      }
    }
  } else {
    common.showModal(`未查询到排班（${resData.RespCode}）`)
    return
  }
  getNextTime()
}

const getNextTime = async () => {
  const dateInfo = consultDate.value.Data_1[timeIndex]
  if (!dateInfo) return

  const qb = queryBean.value
  const st = selectedType.value
  const opt = options.value

  const numberListData = {
    HosId: app.globalData.hosId,
    DeptCode: consultDate.value.DeptCode,
    DoctorCode: consultDate.value.DoctorCode,
    ScheduleId: dateInfo.ScheduleId,
    RegDate: dateInfo.RegDate,
    TimeSlice: dateInfo.TimeSlice,
    SourceType: st == "twzx" ? "019" : "006"
  }

  if (opt.serviceType == "jswz") {
    numberListData.SourceType = "fast"
  } else if (opt.serviceType == "tdwz") {
    numberListData.SourceType = "group"
  }

  let { resp: timeListResp } = await queryNumbers(numberListData)

  if (!common.isEmpty(timeListResp)) {
    let date = dateInfo.RegDate
    if (dateInfo.RegDate == common.dateFormat(new Date()).formatYear) {
      date = "今天"
    } else if (dateInfo.RegDate == common.dateFormat(new Date(Date.now() + 24 * 60 * 60 * 1000)).formatYear) {
      date = "明天"
    } else {
      date = common.dateFormat(new Date(date)).formatMon_C
    }
    const earlyTimeStr = `最早 ${date} ${timeListResp[0].StartTime} 可约`
    earlyTime.value = earlyTimeStr
    consultDateIndClick.value = timeIndex
  } else {
    timeIndex += 1
    if (timeIndex == consultDate.value.Data_1.length) {
      timeIndex = 0
      return
    }
    getNextTime()
  }
}

// 选择咨询时间
const consultSelect = async () => {
  const user = currentUser.value
  const qb = queryBean.value
  const st = selectedType.value
  const opt = options.value
  let consultTimeListData: any[] = []

  // 没有日期列表 请求列表
  if (common.isEmpty(consultDate.value)) {
    const dateListData = {
      HosId: app.globalData.hosId,
      DeptCode: qb.DeptCode,
      DoctorCode: qb.DoctorCode,
      DoctorTitleCode: "",
      SourceType: opt.serviceType == "jswz" ? "fast" : st == "twzx" ? "019" : "006",
      ServiceId: '0',
      WeekType: '1',
      Store: {
        cardEncryptionStore: user.encryptionStore || '',
        baseMemberEncryptionStore: user.baseMemberEncryptionStore
      },
    }
    if (opt.serviceType == "tdwz") {
      dateListData.DoctorCode = `group${qb.GroupId}`
      dateListData.SourceType = `group`
    }

    let { resp: dateListResp, resData: resData } = await queryClinicDoctorSchedule(dateListData)

    if (!common.isEmpty(dateListResp)) {
      consultDate.value = dateListResp[0]
      consultDateIndSelected.value = timeIndex
    } else {
      common.showModal(`未查询到排班（${resData.RespCode}）`)
      return
    }
  }

  const dateInfo = consultDate.value.Data_1[consultDateIndClick.value]
  if (!dateInfo) return

  const numberListData = {
    HosId: app.globalData.hosId,
    DeptCode: consultDate.value.DeptCode,
    DoctorCode: consultDate.value.DoctorCode,
    ScheduleId: dateInfo.ScheduleId,
    RegDate: dateInfo.RegDate,
    TimeSlice: dateInfo.TimeSlice,
    SourceType: selectedType.value == "twzx" ? "019" : "006"
  }

  if (opt.serviceType == "jswz") {
    numberListData.SourceType = "fast"
  } else if (opt.serviceType == "tdwz") {
    numberListData.SourceType = "group"
  }

  let { resp: timeListResp } = await queryNumbers(numberListData)

  if (!common.isEmpty(timeListResp)) {
    consultTimeListData = timeListResp
  }

  consultTimeList.value = consultTimeListData
  consultTimeIndClick.value = 0
  consultTimeIndSelected.value = 0
  showConsultDialog.value = true
}

// 咨询日期点击
const consultDateClick = (index: number) => {
  consultDateIndClick.value = index
  consultSelect()
}

// 咨询时间取消
const cinsultCancel = () => {
  consultTimeIndClick.value = consultTimeIndSelected.value
  consultDateIndClick.value = consultDateIndSelected.value
  closeDialog()
}

// 咨询时间确定
const cinsultConfirm = () => {
  consultTimeIndSelected.value = consultTimeIndClick.value
  consultDateIndSelected.value = consultDateIndClick.value
  closeDialog()
}

// 赋值
const setVal = (key: string, value: any) => {
  if (key.indexOf('Dialog') !== -1 && !value) {
    disabledArea.value = true
  };
  const targetRef = refMap[key];
  if (targetRef) { // 增加安全校验，避免key不存在时报错
    targetRef.value = value;
  } else {
    console.warn(`未找到名为 ${key} 的ref变量`);
  }
}

// 赋值并关闭弹窗
const setValAndClose = (key: string, value: any) => {
  const targetRef = refMap[key];
  if (targetRef) { // 增加安全校验，避免key不存在时报错
    targetRef.value = value;
  } else {
    console.warn(`未找到名为 ${key} 的ref变量`);
  }
  closeDialog()
}

// 关闭弹窗
const closeDialog = () => {
  showConsultDialog.value = false
  showPurDialog.value = false
  showExampleDialog.value = false
  showRecDialog.value = false
  showPrescDetailDialog.value = false
  showReportListDialog.value = false
  disabledArea.value = false
}

// 输入框赋值
const inputVal = (e: any) => {
  const key = e.currentTarget?.dataset?.key
  const value = e.detail.value
  if (key == 'illnessInfo') {
    illnessInfo.value = value
  } else if (key == 'helpInfo') {
    helpInfo.value = value
  }
}

// 点击提交咨询
const submitFnClick = async () => {
  if (!getNext.value) {
    return
  }

  if (common.isEmpty(purSelected.value)) {
    common.showToast("请选择本次问诊目的")
    return
  }

  if (common.isEmpty(recList.value) && purSelected.value.key == 'bgdjd') {
    common.showToast("请选择报告单")
    return
  }

  if (common.isEmpty(recList.value) && purSelected.value.key == 'yyzx') {
    common.showToast("请选择就诊记录")
    return
  }

  if (common.isEmpty(consultTimeList.value[consultTimeIndSelected.value])) {
    common.showToast("请选择咨询时间")
    return
  }

  if (common.isEmpty(illness.value) && common.isEmpty(illnessInfo.value)) {
    common.showToast("请先选择病情报告或填写症状描述")
    return
  }

  const reg = /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/ig

  if (illnessInfo.value?.match(reg) || helpInfo.value?.match(reg)) {
    common.showToast('无法提交表情，请删除后重试')
    return
  }

  if (serviceType.value !== 'tdwz' && isOuterHos.value && imgListSave.value.length == 0) {
    common.showToast("请上传外院病例")
    return
  }

  illnessInfo.value = illnessInfo.value?.replace(/\?/g, "？") || ""
  helpInfo.value = helpInfo.value?.replace(/\?/g, "？") || ""

  if (submitFnClickIs) {
    submitFnClickIs = false

    const diyFee = selectedType.value == 'twzx'
      ? queryBean.value.consultFeeDiy
      : selectedType.value == 'dhzx'
        ? queryBean.value.phoneFeeDiy
        : selectedType.value == 'spzx'
          ? queryBean.value.videoFeeDiy
          : 0
    //前端控制缴费模式
    if(netHospageConfig.value.netHos_orderPaymentMode == 1){
      checkCardBalance(diyFee).then(() => {
        LockOrder()
      })
    }else if(netHospageConfig.value.netHos_orderPaymentMode == 2){
        LockOrder()
    }
  }
}

// 检查就诊卡余额是否充足
const checkCardBalance = (Fee: number) => {
  return new Promise((resolve) => {
    if (common.sub(Fee, 0) > 0) {
      getCardBalance().then((res: any) => {
        const balance = common.centToYuan(res[0]?.balance) || 0
        if ((Number(balance) < Number(Fee)) && purSelected.value.id !== "12" && !isFirstVisit.value) {
          uni.showModal({
            title: '温馨提示',
            content: '您的就诊卡余额不足（当前余额' + Number(balance) + '元），请先充值，谢谢！',
            confirmText: '去充值',
            success(res) {
              if (res.confirm) {
                common.goToUrl(`/pagesPatient/st1/business/recharge/rechargeMoney/rechargeMoney`)
              } else {
                return
              }
            },
          })
        } else {
          resolve(true)
        }
      })
    } else {
      resolve(true)
    }
  })
}

// 获取卡余额
const getCardBalance = async () => {
  const user = currentUser.value
  const data = {
    cardType: user.cardType,
    cardNo: user.cardNo,
    Store: {
      cardEncryptionStore: user.encryptionStore || '',
      baseMemberEncryptionStore: user.baseMemberEncryptionStore
    }
  }
  let { resp } = await queryCardBalance_V3(data)
  if (common.isNotEmpty(resp)) {
    return resp
  } else {
    return []
  }
}

// 锁号
const LockOrder = async () => {
  const user = currentUser.value
  const dateSelected = consultDate.value.Data_1[consultDateIndSelected.value]
  const timeSelected = consultTimeList.value[consultTimeIndSelected.value]

  const serviceId = dateSelected.RegDate == common.dateFormat(new Date()).formatDay ? '027' : '024'

  const queryData = {
    HosId: app.globalData.districtId || app.globalData.hosId,
    ScheduleId: dateSelected.ScheduleId,
    CardType: user.cardType,
    CardNo: user.cardNo,
    MemberId: user.MemberId || user.memberId,
    DeptCode: consultDate.value.DeptCode,
    DoctorCode: consultDate.value.DoctorCode,
    RegType: '1',
    RegDate: dateSelected.RegDate,
    TimeSlice: dateSelected.TimeSlice,
    SqNo: timeSelected.SqNo,
    CommendTime: timeSelected.EndTime ? `${timeSelected.StartTime}-${timeSelected.EndTime}` : timeSelected.StartTime,
    SourceCode: timeSelected.SourceCode,
    SourceType: selectedType.value == "twzx" ? "019" : "006",
    ServiceId: serviceId,
    AutoSignIn: selectedType.value == "twzx" ? 1 : 0,
    MemberStore: {
      "cardEncryptionStore": user.encryptionStore || '',
      "baseMemberEncryptionStore": user.baseMemberEncryptionStore
    },
    BookMode: "1",
  }

  if (timeSelected.CommendTime?.indexOf(":") == -1) {
    const nowTime = common.accessTimeInAnHour(3600000).time
    queryData.CommendTime = nowTime
  }

  // 团队问诊入参
  if (options.value.serviceType == "tdwz") {
    queryData.SourceType = `group`
  }

  let { resp: lockResp, resData: lockResData } = await lockOrder(queryData)

  if (lockResData.RespCode == '10000') {
    if (common.isNotEmpty(lockResp)) {
      // 订阅消息
      if (selectedType.value == 'twzx') {
        picSubmit(lockResp, serviceId)
      } else if (selectedType.value == 'spzx') {
        viaSubmit(lockResp, serviceId)
      }
    } else {
      submitFnClickIs = true
    }
  } else {
    submitFnClickIs = true
    common.showModal(lockResData.RespMessage)
  }
}

// 释号
const unlockOrder = async (lockResp: any) => {
  const data = {
    OrderId: lockResp[0].OrderId,
    SourceType: selectedType.value == "twzx" ? "019" : "006",
  }
  await unlock(data)
}

// 图文咨询提交
const picSubmit = async (lockResp: any, serviceId: string) => {
  const user = currentUser.value
  const dateSelected = consultDate.value.Data_1[consultDateIndSelected.value]
  const timeSelected = consultTimeList.value[consultTimeIndSelected.value]
  const qb = queryBean.value
  const Store = {
    cardEncryptionStore: user.encryptionStore || '',
    baseMemberEncryptionStore: user.baseMemberEncryptionStore
  }
  const purposeType = purSelected.value.id

  const tempData = JSON.stringify([
    { key: "initial", value: diagnosisType.value == 'first' ? '1' : '0' },
    { key: "consult", value: purSelected.value },
    { key: "visit_record", value: recSelected.value },
    {
      key: "yy_time",
      value: {
        SqNo: timeSelected.SqNo,
        StartTime: options.value.serviceType == "jswz" ? timeSelected.StartTime : timeSelected.CommendTime,
      }
    },
    { key: "desc", value: helpInfo.value },
    { key: "pics", value: imgListSave.value },
    { key: "chief_complaint", value: common.isEmpty(illness.value) ? "" : illness.value.MedicalInfo?.chief_complaint },
    { key: "illness_info", value: illnessInfo.value },
    { key: "pics_presc", value: imgPrescListSave.value },
    { key: "has_record", value: hasRecord.value },
    { key: "cancel_cause", value: '' },
    { key: "cardAndMember", value: Store },
    { key: "member_info", value: currentUser.value },
    { key: 'external_cases', value: isOuterHos.value },
    { key: 'first_visit_free', value: isFirstVisit.value },
    { key: 'transfer', value: "" }
  ])

  const data = {
    HosId: app.globalData.districtId || app.globalData.hosId || "",
    MemberId: user.memberId,
    CardType: user.cardType,
    CardNo: user.cardNo,
    DeptId: qb.DeptId,
    DeptName: qb.DeptName,
    DoctorName: qb.DoctorName,
    DoctorUid: qb.DoctorUid,
    DcotorTitleCode: qb.TitleCode,
    IllnessDesc: tempData,
    PreDiagnosisId: illness.value.Id || "",
    ConsultType: "1",
    PurposeType: purposeType,
    BookMode: "1",
    OrderId: lockResp[0].OrderId,
    AutoSignIn: 1,
    Fee: qb.ConsultFee,
    BookParam: {
      OperatorName: user.memberName,
      SourceType: "019",
      Store: Store,
      Data_1: {
        DoctorName: consultDate.value.DoctorName,
        DeptCode: consultDate.value.DeptCode,
        DoctorCode: consultDate.value.DoctorCode,
        DeptName: consultDate.value.DeptName,
        TimeSlice: dateSelected.TimeSlice,
        CommendTime: timeSelected.CommendTime,
        RegDate: dateSelected.RegDate,
        FeeInfo: "",
      },
      OperatorId: uni.getStorageSync('openid'),
      OrderId: lockResp[0].OrderId,
      ChannelId: "smallpro",
      HosId: app.globalData.hosId,
      PriceName: '图文咨询',
      ServiceId: serviceId,
      EqptType: 1,
      MemberName: user.memberName,
      MemberId: user.memberId,
      CardNo: user.cardNo,
      CardType: user.cardType,
      PrescNo: "",
      IsOnlinePay: lockResp[0].IsOnlinePay,
      ConsultType: "1",
      PayMoney: lockResp[0].Fee,
      TotalMoney: lockResp[0].Fee,
    },
    Store: Store,
  }

  // 即时问诊入参
  if (options.value.serviceType == "jswz") {
    data.BookParam.SourceType = "fast"
  }
  // 团队问诊入参
  else if (options.value.serviceType == "tdwz") {
    data.IsNew = 1
    data.GroupId = qb.GroupId
    data.GroupName = qb.GroupName
    data.DoctorName = qb.GroupName
    data.BookParam.DoctorName = qb.GroupName
    data.BookParam.SourceType = "group"
    data.TimeSlot = consultDate.value.Data_1[consultDateIndClick.value].TimeSlice
  }

  submitFnClickIs = true

  let { resp, resData } = options.value.serviceType == "tdwz"
    ? await applyDoctorGroupConsult(data, { showModal: false })
    : await applyImgTxtConsult(data, { showModal: false })

  if (resData.RespCode == '10000') {
    if (!common.isEmpty(resp)) {
      // 后端控制是否线上支付
      const consultIsOnlinePay = resp[0].IsOnlinePay
      if (consultIsOnlinePay == '1') {
        common.goToUrl(`/pagesNetHos/st1/business/pay/payment/payment?orderId=${resp[0].OrderId}`)
      } else {
        common.goToUrl(`/pagesNetHos/st1/business/pay/payState/payState`)
      }
    }
  } else {
    common.showModal(resData.RespMessage)
    unlockOrder(lockResp)
  }
}

// 视频咨询提交
const viaSubmit = async (lockResp: any, serviceId: string) => {
  common.showLoading()

  const user = currentUser.value
  const dateSelected = consultDate.value.Data_1[consultDateIndSelected.value]
  const timeSelected = consultTimeList.value[consultTimeIndSelected.value]
  const qb = queryBean.value

  submitFnClickIs = true

  const Store = {
    cardEncryptionStore: user.encryptionStore || '',
    baseMemberEncryptionStore: user.baseMemberEncryptionStore
  }

  const tempData = JSON.stringify([
    { key: "initial", value: diagnosisType.value == 'first' ? '1' : '0' },
    { key: "consult", value: purSelected.value },
    { key: "visit_record", value: recSelected.value },
    {
      key: "yy_time",
      value: {
        SqNo: timeSelected.SqNo,
        RegDate: dateSelected.RegDate,
        CommendTime: timeSelected.CommendTime,
        TimeSlice: dateSelected.TimeSlice
      }
    },
    { key: "desc", value: helpInfo.value },
    { key: "pics", value: imgListSave.value },
    { key: "chief_complaint", value: common.isEmpty(illness.value) ? "" : illness.value.MedicalInfo?.chief_complaint },
    { key: "illness_info", value: illnessInfo.value },
    { key: "pics_presc", value: imgPrescListSave.value },
    { key: "has_record", value: hasRecord.value },
    { key: "cancel_cause", value: '' },
    { key: "cardAndMember", value: Store },
    { key: "member_info", value: currentUser.value },
    { key: 'external_cases', value: isOuterHos.value }
  ])

  const data = {
    HosId: app.globalData.hosId || "",
    DeptId: qb.DeptId,
    DeptName: qb.DeptName,
    DoctorUid: qb.DoctorUid,
    DoctorName: qb.DoctorName,
    DcotorTitleCode: qb.TitleCode,
    OpenId: uni.getStorageSync('openid'),
    IllnessDesc: tempData,
    PreDiagnosisId: illness.value.Id || "",
    RegDate: dateSelected.RegDate,
    BookMode: "1",
    MemberId: user.memberId,
    CardType: user.cardType,
    CardNo: user.cardNo,
    PurposeType: purClick.value.id,
    OrderId: lockResp[0].OrderId,
    BookParam: {
      HosId: app.globalData.hosId,
      OrderId: lockResp[0].OrderId,
      MemberId: user.memberId,
      PrescNo: "",
      PayMoney: lockResp[0].Fee,
      TotalMoney: lockResp[0].Fee,
      PriceName: '视频咨询',
      CardType: user.cardType,
      CardNo: user.cardNo,
      OperatorId: uni.getStorageSync('openid'),
      OperatorName: user.memberName,
      ServiceId: serviceId,
      IsOnlinePay: lockResp[0].IsOnlinePay,
      EqptType: 1,
      HisMemberId: user.hisMemberId,
      ChannelId: app.globalData.channelId,
      MemberName: user.memberName,
      SourceType: "006",
      Data_1: {
        DeptCode: consultDate.value.DeptCode,
        DeptName: consultDate.value.DeptName,
        DoctorCode: consultDate.value.DoctorCode,
        DoctorName: consultDate.value.DoctorName,
        FeeInfo: "",
        RegDate: dateSelected.RegDate,
        CommendTime: timeSelected.CommendTime,
        TimeSlice: dateSelected.TimeSlice
      },
      Store: Store,
      ConsultType: "2"
    },
    Store: Store,
    ConsultType: "2"
  }

  let { resp, resData } = await applyVideoConsult(data, { showLoading: false })

  common.hideLoading()

  if (!common.isEmpty(resp)) {
    if (resp[0].IsOnlinePay == '1') {
      common.goToUrl(`/pagesNetHos/st1/business/pay/payment/payment?orderId=${resp[0].OrderId}`)
    } else {
      common.goToUrl(`/pagesNetHos/st1/business/pay/payState/payState`)
    }
  } else {
    common.showModal(resData.RespMessage)
    unlockOrder(lockResp)
  }
}

// 展示图片详情
const showImg = (ind: number) => {
  const newImgList = imgList.value.map((url: string) => {
    if (url && url.includes('_scale')) {
      return url.replace('_scale', '')
    }
    return url
  })
  uni.previewImage({
    current: newImgList[ind],
    urls: newImgList
  })
}

// 删除图片
const delImg = (index: number) => {
  imgList.value.splice(index, 1)
  imgListSave.value.splice(index, 1)
}

// 查询就诊记录
const queryOutpatientVisitList = async (tag: string) => {
  const user = currentUser.value
  const params = {
    CardNo: user.cardNo,
    CardType: "1",
    MemberId: user.memberId,
    OpenId: uni.getStorageSync("openid"),
    StartDate: common.dateFormat(new Date(Date.now() - (90 * 24 * 60 * 60 * 1000))).formatYear,
    EndDate: common.dateFormat(new Date(Date.now() + (1 * 24 * 60 * 60 * 1000))).formatYear,
    Store: {
      cardEncryptionStore: user.encryptionStore || '',
      baseMemberEncryptionStore: user.baseMemberEncryptionStore
    }
  }

  let { resp, resData } = await QueryOutpatientVisitList(params, { showModal: false })

  if (common.isEmpty(resp)) {
    isOuterHos.value = false
  } else {
    isOuterHos.value = true
    if (tag == "history" && imgList.value.length == 0) {
      isHistory.value = false
    }
  }
}

// 初诊咨询
const firstVisit = () => {
  isFirstVisit.value = true
  isHistory.value = true
}

// 外院病例
const outerHos = () => {
  isOuterHos.value = true
  isHistory.value = true
}

// 返回首页
const toHome = () => {
  common.goToUrl(`/pages/st1/business/tabbar/netHosIndex/netHosIndex`, {
    skipWay: 'switchTab'
  })
}
</script>

<style lang="scss" scoped>
@import "@/pagesNetHos/st1/static/css/common.scss";
@import "@/pagesNetHos/st1/static/css/dialog.scss";

.backgroundCustom_4aa7fe {
  background-color: #4aa7fe !important;
  color: #fff !important;
}

.p_content {
  padding-bottom: 150upx;
}

.user {
  padding: 30upx;
  justify-content: flex-start;
  background-color: #fff;
}

.user_img {
  width: 88upx;
  height: 88upx;
  border-radius: 50%;
  margin-right: 23upx;
  flex-shrink: 0;
}

.user_box {
  width: 100%;
}

.user_con {
  width: 100%;
  flex-direction: column;
  align-items: flex-start;
}

.user_name {
  font-size: 34upx;
  font-weight: 500;
}

.user_tip {
  font-size: 28upx;
  margin-top: 6upx;
}

.group_box {
  padding: 30upx;
  box-sizing: border-box;
  align-items: flex-start;
  background: white;
  margin-top: 20upx;
}

.group_title {
  font-weight: bold;
  margin-bottom: 14upx;
}

.group_box text {
  font-size: 30upx;
}

.group_introduce {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  flex-wrap: wrap;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  position: relative;
}

.group_introduce text {
  color: #666;
}

.block {
  width: 690upx;
  margin: 30upx;
  border-radius: 24upx;
  background-color: #fff;
}

.member {
  padding: 40upx 30upx;
}

.member_con {
  width: 100%;
}

.member_info_con {
  align-items: flex-start;
  justify-content: flex-start;
}

.member_name {
  font-size: 34upx;
  font-weight: 500;
  line-height: 1em;
}

.member_info {
  font-size: 28upx;
  margin-left: 19upx;
}

.member_id {
  font-size: 28upx;
  margin-top: 15upx;
}

.member_btn {
  padding: 0 30upx;
  height: 64upx;
  background: #01BF8E;
  border-radius: 32px;
  flex-shrink: 0;
  font-size: 28upx;
  font-weight: 800;
  color: #FFFFFF;
}

.info {
  padding-left: 30upx;
}

.info_box {
  padding: 40upx 30upx 40upx 0;
}

.info_tit {
  font-size: 32upx;
}

.info_subtit {
  font-size: 26upx;
}

.radio_item {
  margin-right: 57upx;
  font-size: 32upx;
}

.radio_item:nth-last-child(1) {
  margin-right: 0;
}

.radio_item_img {
  width: 36upx;
  height: 36upx;
  margin-right: 15upx;
}

.info_right {
  width: 22upx;
  height: 22upx;
  margin-left: 16upx;
}

.info_pres {
  margin: 22upx 0 10upx;
  background-color: rgb(235, 241, 255);
  border-radius: 20upx;
}

.info_pres_con {
  padding: 30upx 30upx 26upx;
}

.info_pres_inner {
  width: 100%;
  align-items: flex-start;
  flex-direction: column;
}

.info_pres_time {
  font-size: 26upx;
}

.info_pres_tit {
  margin: 5upx 0 3upx;
}

.info_pres_subtit {
  display: flex;
}

.report_item_val_titval {
  flex-shrink: 0;
}

.info_pres_detailbtn {
  flex-shrink: 0;
  height: 55upx;
  padding: 0 16upx;
  border-radius: 8px;
}

.info_doctor_arrow {
  width: 24upx;
  height: 24upx;
  margin-left: 5upx;
}

.info_pres_btns {
  justify-content: flex-end;
  height: 90upx;
  padding-right: 20upx;
}

.info_pres_btn {
  height: 55upx;
  padding: 0 19upx;
  font-size: 26upx;
  border-radius: 8px;
  margin-right: 10upx;
}

.coll_con {
  margin-top: 23upx;
}

.coll_img_con {
  justify-content: flex-start;
  flex-wrap: wrap;
}

.coll_con_img_box {
  width: 160upx;
  height: 160upx;
  margin-right: 16upx;
  margin-bottom: 16upx;
  position: relative;
}

.coll_con_img_box:nth-child(4n) {
  margin-right: 0;
}

.coll_con_img {
  border-radius: 10upx;
}

.doctor_cha {
  position: absolute;
  right: 0;
  top: 0;
  z-index: 1;
  width: 40upx;
  height: 40upx;
  width: 30upx;
  height: 30upx;
  background: #fff;
  border-radius: 50%;
}

.coll_img_box {
  width: 161upx;
  height: 161upx;
  background: #F6F7F8;
  border: 1px solid #CCCCCC;
  border-radius: 12upx;
  flex-shrink: 0;
  margin-right: 29upx;
}

.coll_img {
  width: 62upx;
  height: 62upx;
}

.coll_tip {
  width: 100%;
  font-size: 26upx;
  line-height: 38upx;
}

.info_box_textarea {
  width: 100%;
  min-height: 107upx;
  line-height: 40upx;
  font-size: 30upx;
  margin-bottom: 47upx;
}

.placeholder {
  color: #CCCCCC;
  font-size: 30upx;
  line-height: 40upx;
}

.text_tip {
  padding: 0 14upx;
  height: 45upx;
  background: #FFFFFF;
  border-radius: 6px;
  font-size: 26upx;
}

.text_num {
  font-size: 26upx;
}

.info_box_help {
  margin-top: 30upx;
}

/* 问诊目的 */
.pur_list {
  padding-left: 30upx;
}

.pur_item {
  padding: 40upx 30upx;
}

.pur_icon {
  width: 38upx;
  height: 38upx;
  margin-right: 27upx;
  flex-shrink: 0;
}

.pur_con {
  width: 100%;
}

.pur_tit {
  font-size: 32upx;
  font-weight: 500;
}

.pur_subtit {
  font-size: 28upx;
  color: #8A8A99;
  line-height: 38upx;
  margin-top: 6upx;
}

/* 咨询时间弹窗 */
.date_list {
  white-space: nowrap;
}

.date_item {
  display: inline-block;
  height: 80upx;
  line-height: 80upx !important;
  text-align: center;
  width: 252upx;
  background-color: #F6F7F8;
}

.date_item_ac::after {
  border-color: #e6e6e6;
}

.date_item:last-child::after {
  border-right: 0;
}

.date_item_ac {
  position: relative;
}

.date_item_ac::before {
  content: "";
  display: block;
  width: 32upx;
  height: 6upx;
  background-color: #01BF8E;
  position: absolute;
  left: 50%;
  right: 0;
  bottom: 0;
  transform: translateX(-50%);
  border-radius: 3px;
}

.date_item_icon {
  width: 48upx;
  height: 48upx;
  position: absolute;
  right: 4upx;
  top: 0;
}

/* 选择咨询时间弹窗 */
.num_con {
  padding: 0 30upx;
  height: 504upx;
}

.num_tit {
  font-size: 28upx;
  margin: 27upx 0 24upx;
}

.num_tit_price {
  color: #EE5253;
}

.num_list {
  flex-wrap: wrap;
  justify-content: flex-start;
}

.num_item {
  width: 160upx;
  height: 111upx;
  background: #f6f7f8;
  border-radius: 20upx;
  margin: 0 16upx 16upx 0;
  flex-direction: column;
}

.num_item:nth-child(4n) {
  margin: 0 0 16upx 0;
}

.num_item_ac {
  background-color: #F5FFFA;
}

.num_item_img {
  width: 52upx;
  height: 50upx;
  position: absolute;
  right: 0;
  bottom: 0;
}

.num_item_time {
  font-size: 26upx;
}

.btnBgcolor {
  background-color: #ddd !important;
}

.p_mask,
.p_btn_con {
  z-index: 100;
}

.press-canvas {
  position: absolute;
  top: -1000px;
  background-color: gray;
}

.pb150 {
  padding-bottom: 150upx;
}

.mask {
  z-index: 999;
}

.non_record_box {
  width: 80%;
  background: white;
  border-radius: 20upx;
  padding: 30upx;
  box-sizing: border-box;
}

.non_record_title {
  font-size: 32upx;
  font-weight: bold;
  color: #333;
}

.non_record_main {
  width: 100%;
  margin: 30upx 0;
}

.non_record_main text {
  line-height: 44upx;
  font-size: 30upx;
  color: #666;
  margin-bottom: 15upx;
}

.non_record_btn {
  width: 100%;
}

.non_record_btn text {
  width: 100%;
  line-height: 70upx;
  text-align: center;
  border-radius: 10upx;
  margin-top: 20upx;
}

.example_val {
  padding: 30upx;
  box-sizing: border-box;
  border: 1px solid #f5f5f5;
  background: #f9f9f9;
  margin-bottom: 30upx;
}

/* 示例 */
.example_con {
  padding: 0 30upx;
  line-height: 0;
}

.example_img {
  height: 160upx;
  width: 160upx;
  border-radius: 10upx;
  margin: 22upx 30upx 28upx 0;
}
</style>
