<template>
  <view class="container">
    <view class="content_x">
      <view class="doc_info">
        <image class="doc_img" :src="doctorItem.PhotoUrl || iconUrl.icon_doctor"></image>
        <view class="doc_con">
          <view class="doc_name">{{ doctorItem.DoctorName }}</view>
          <view class="doc_tip">{{ doctorItem.DeptName }} | {{ doctorItem.Title }}</view>
        </view>
      </view>


      <view class="info_list">
        <view class="info_item border_bottom">
          <view class="info_item_tit">就诊人</view>
          <view class="info_item_val">{{ currentUser.memberName }}({{ currentUser.sex == '1' ? '男' : currentUser.sex == '2' ? '女' : '未知' }}/{{ currentUser.ageStr }})</view>
        </view>
        <view class="info_item border_bottom" v-if="currentUser.isChildren == 0">
          <view class="info_item_tit">身份证号</view>
          <view class="info_item_val">{{ currentUser.certNum }}</view>
        </view>
        <view class="info_item border_bottom" v-if="currentUser.isChildren == 1">
          <view class="info_item_tit">监护人身份证号</view>
          <view class="info_item_val">{{ currentUser.guardianCertNum }}</view>
        </view>
        <view class="info_item border_bottom">
          <view class="info_item_tit">候补排班</view>
          <view class="info_item_val">{{ dateInfoSelected.RegDate }} {{ dateInfoSelected.WeekName }}{{ dateInfoSelected.TimeSliceStr }}</view>
        </view>
        <view class="info_item" v-if="false">
          <view class="info_item_tit">候补截止</view>
          <view class="info_item_val">
            <picker mode="date" class="picker" :value="waitDate" :start="today" :end="endDate" @change="bindDateChange">
              {{ waitDate }}
            </picker>
            {{ waitDateName }}{{ waitTimeName }}
            <picker mode="time" class="picker" :value="waitTime" :end="endTime" @change="bindTimeChange">
              {{ waitTime }}
            </picker>
            <image class="right" :src="iconUrl.icon_right"></image>
          </view>
        </view>
        <view class="info_item_tip">
          截至{{ waitDate }} {{ waitTime }}之前，系统将一直为您尝试预约挂号候补
        </view>
      </view>
      <view class="public_btn_con">
        <view class="public_btn backgroundCustom" @click="jumpAppointmentSuccess">确认登记</view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { common } from '@/utils';
import icon from '@/utils/icon';
import { waitListApiAdd } from '@/pagesPatient/service/yygh';

const app = getApp();
const iconUrl = ref(icon);
const waitDate = ref(''); //候补日期 
const waitDateName = ref(''); //星期
const waitTime = ref('16:00'); //候补时间
const waitTimeName = ref(''); //上下午
const endTime = ref("23:59"); //截止时间
const endDate = ref(''); //截止日期
const showMore = ref(false); //是否展示过敏史等
const currentUser = ref<any>({});
const doctorItem = ref<any>({});
const dateInfoSelected = ref<any>({});
const today = ref('');

onLoad((options: any) => {
  let user = app.globalData.currentUser;
  let querBen = options.querBen ? JSON.parse(decodeURIComponent(options.querBen)) : {};
  let doctor = querBen.doctorItem; //医生信息
  let dateInfo = querBen.dateInfoSelected; //排班信息
  let wDate = dateInfo.RegDate;

  currentUser.value = user;
  doctorItem.value = doctor;
  dateInfoSelected.value = dateInfo;
  waitDate.value = wDate;
  today.value = common.afterFewDays(1);
  endDate.value = wDate;
  waitDateName.value = common.getWeekName(new Date(wDate).getDay(), 1);
  waitTimeName.value = getWaitTimeName(waitTime.value);
});

const getWaitTimeName = (str: string) => {
  let val = Number(str.replace(':', ''));
  if (val >= 0 && val <= 1200) {
    return '上午';
  } else if (val > 1200 && val <= 2359) {
    return '下午';
  }
  return '';
};

// 选择截止日期
const bindDateChange = (e: any) => {
  let val = e.detail.value;
  waitDate.value = val;
  waitDateName.value = common.getWeekName(new Date(e.detail.value).getDay(), 1);
};

const bindTimeChange = (e: any) => {
  waitTime.value = e.detail.value;
  waitTimeName.value = getWaitTimeName(e.detail.value);
};

// 跳转候补成功
const jumpAppointmentSuccess = async () => {
  let user = currentUser.value;
  let doctor = doctorItem.value;
  let dateInfo = dateInfoSelected.value;
  
  let queryData = {
    HosId: app.globalData.districtId || app.globalData.hosId,
    OpenId: uni.getStorageSync("openid"),
    MemberId: user.memberId,
    MemberName: user.memberName,
    CertType: user.isChildren == '1' ? user.guardianCertType : user.certType,
    CertNum: user.isChildren == '1' ? user.guardianCertNum : user.certNum,
    ScheduleId: dateInfo.ScheduleId,
    DeptCode: doctor.DeptCode,
    DeptName: doctor.DeptName,
    DoctorCode: doctor.DoctorCode,
    DoctorName: doctor.DoctorName,
    RegDate: dateInfo.RegDate,
    WeekId: dateInfo.WeekId,
    TimeId: dateInfo.TimeSlice,
    RegFee: dateInfo.RegFee,
    InvalidDate: `${waitDate.value} ${waitTime.value}:00`,
    ServiceId: '0',
    MemberStore: {
      cardEncryptionStore: user.encryptionStore || '',
      baseMemberEncryptionStore: user.baseMemberEncryptionStore
    }
  };
  
  // Note: Original code destructures {resp, resData}, but handle.promistHandleNew usually returns [err, res] or just res depending on implementation.
  // Assuming standard usage: let resp = await api(...)
  // Based on waitListApiAdd implementation in index.ts: 
  // let resp = handle.promistHandleNew(...)
  // return handle.catchPromiseNew(resp, () => resp);
  // So resp will be the result array/object.
  // However, looking at original code: let {resp,resData} = await yygh.waitListApiAdd(queryData)
  // It seems it expects an object with resp and resData. 
  // But waitListApiAdd in index.ts returns `handle.catchPromiseNew(resp, () => resp)`.
  // If promistHandleNew returns [err, res], then catchPromiseNew usually returns res if no error.
  // Let's look at `handle.promistHandleNew` usage pattern in other files if possible, or assume standard uni-app-base pattern.
  // In `record/index.ts`, `waitListApiAdd` was not present, I added it to `yygh/index.ts`.
  // Standard `handle.catchPromiseNew(resp, () => resp)` usually returns the data directly.
  // The original code `let {resp,resData} = await ...` suggests the return value is an object containing these keys.
  // But my implementation of `waitListApiAdd` returns `resp` directly (or whatever `catchPromiseNew` returns).
  // If `catchPromiseNew` returns the response body, we should check `RespCode` on it.
  
  let resp = await waitListApiAdd(queryData);
  
  // Assuming resp is the data object or array. 
  // If resp is array (common in some frameworks), check resp[0].
  // If resp is object, check resp.RespCode.
  // Let's assume resp is the response object.
  // If the original code destructured it, maybe the library returns {resp, resData}.
  // But I'm using the standard `handle` from `pagesPatient/service/yygh/index.ts`.
  // Let's check `regSignForHis` usage in `signInList.vue` I just wrote:
  // let resp = await regSignForHis(querData)
  // if (!common.isEmpty(resp)) { ... resp[0] ... }
  // This suggests `resp` is an array of results.
  
  // Wait, the original code used `yygh.waitListApiAdd`.
  // I should check if I should return `resp` or `resp[0]`.
  // Usually `handle.catchPromiseNew` returns the business data.
  // If the API returns a list, it's a list. If it returns an object, it's an object.
  // `waitListApiAdd` likely returns a status object.
  
  if (resp && resp.RespCode == '10000') {
      common.goToUrl(`/pagesPatient/st1/business/yygh/waitSuccess/waitSuccess`);
  } else if (Array.isArray(resp) && resp[0] && resp[0].RespCode == '10000') {
      common.goToUrl(`/pagesPatient/st1/business/yygh/waitSuccess/waitSuccess`);
  } else {
     // If response structure is different, we might need to adjust.
     // For now, let's assume if it returns success it might be in resp.RespCode or we just check if it's not empty.
     // But explicit check for 10000 is better.
     // Let's try to be robust.
     if ((resp && resp.RespCode == '10000') || (Array.isArray(resp) && resp[0] && resp[0].RespCode == '10000')) {
        common.goToUrl(`/pagesPatient/st1/business/yygh/waitSuccess/waitSuccess`);
     }
  }
};
</script>

<style scoped>
.content_x {
  width: 100%;
  display: inline-block;
  padding-bottom: 170upx;
}

.doc_info {
  position: relative;
  padding: 30upx;
  display: flex;
  align-items: center;
  background-color: #fff;
  margin-bottom: 20upx;
}

.right {
  position: absolute;
  right: 30upx;
  top: 0;
  bottom: 0;
  margin: auto 0;
  width: 12upx;
  height: 24upx;
}

.info_item .right {
  position: inherit;
  margin-left: 12upx;
}

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

.doc_con {
  width: 100%;
}

.doc_name {
  font-size: 32upx;
  font-family: PingFang SC;
  font-weight: bold;
  color: #333;
  line-height: 18upx;
  margin-bottom: 15upx;
}

.doc_tip {
  font-size: 26upx;
  font-family: PingFang SC;
  color: #999;
}

.info_list {
  background-color: #fff;
  display: inline-block;
  width: 100%;
  margin-bottom: 20upx;
  padding: 0 30upx;
}

.info_item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 32upx;
  font-family: PingFang SC;
  color: #333;
}

.info_item_val {
  padding: 38upx 0;
  display: flex;
  align-items: center;
  font-size: 32upx;
  font-family: PingFang SC;
  color: #666666;
  line-height: 38upx;
}

.info_item_tip {
  font-size: 28upx;
  font-family: PingFang SC;
  color: #999;
  line-height: 42upx;
  padding: 25upx 30upx;
  background: #f7f7f7;
  border-radius: 10upx;
  position: relative;
  margin-bottom: 30upx;
}

.info_item_tip::after {
  display: block;
  content: "";
  width: 20upx;
  height: 20upx;
  background-color: #f7f7f7;
  transform-origin: 50%;
  transform: rotateZ(45deg);
  position: absolute;
  left: 30upx;
  top: -10upx;
}

.picker {
  margin: 0 20upx;
}
</style>