<template>
  <view class="container">
    <view class="main_box">
      <view class="make_msg_box" :class="{ 'topBorderRadius': pageType == 'yygh' }">
        <image class="success_icon" :src="icon.icon_circleActive"></image>
        <text class="title" v-if="pageType == 'yygh'">预约成功</text>
        <text class="title mb30" v-if="pageType == 'czjf'">付款成功</text>
        <text class="title mb30" v-if="pageType == 'signIn'">恭喜您，签到成功</text>
        <text class="title mb30" v-if="pageType == 'orderPayment'">恭喜您，结算成功</text>
        <text class="title mb30" v-if="pageType == 'refund'">退款成功</text>
        <text class="title mb30" v-if="pageType == 'yjyy'">{{ isSuccess ? '预约成功' : '预约失败' }}</text>
      </view>
      <image v-if="pageType == 'yygh'" class="division_icon" :src="icon.icon_division"></image>
      <view class="time_box bottomBorderRadius" v-if="pageType == 'yygh'">
        <view class="time_box_list displayFlexRow">
          <text class="time_leftText">预约科室</text>
          <text class="time_rightText">{{ orderInfo.OrderMemo.DeptName }}</text>
        </view>
        <view class="time_box_list displayFlexRow">
          <text class="time_leftText">医生姓名</text>
          <text class="time_rightText">{{ orderInfo.OrderMemo.DoctorName }}</text>
        </view>
        <view class="time_box_list displayFlexRow">
          <text class="time_leftText">就诊时间</text>
          <text class="time_rightText">{{ orderInfo.OrderMemo.RegDate }} {{ orderInfo.OrderMemo.CommendTime }}</text>
        </view>
        <view class="time_box_list displayFlexRow">
          <text class="time_leftText">就诊人</text>
          <text class="time_rightText">{{ orderInfo.MemberName }}</text>
        </view>
        <view class="time_box_list displayFlexRow">
          <text class="time_leftText">挂号费</text>
          <text class="time_rightText colorCustom_F08">{{ orderInfo.TotalMoney / 100 }}元</text>
        </view>

        <view class="footerBtn displayFlexRow">
          <text v-if="orderInfo.allowCancel" class="colorCustom border" @click="cancelAppointment">取消预约</text>
          <text class="colorCustom border" @click="toAppointmentRecord">查看预约记录</text>
        </view>
      </view>
      <!-- 不等于在线签到成功页面时展示提示信息 -->
      <view class="tips_box" v-if="pageType != 'signIn'">
        <view v-if="pageType == 'yygh'">
          <view class="tips_title_box displayFlexRow">
            <image :src="icon.spot_left"></image>
            <text>注意事项</text>
            <image :src="icon.spot_right"></image>
          </view>
          <!-- 判断是否有配置信息有就取配置信息的 -->
          <block v-if="pageConfig.tip && pageConfig.tip.length > 0">
            <view class="tips_item_box" v-for="(item, index) in pageConfig.tip" :key="index">
              <block v-if="item.length > 1">
                <text class="font_weight">{{ item[0] }}</text>
                <text>{{ item[1] }}</text>
              </block>
              <block v-else>
                <text class="font_weight">{{ item }}</text>
              </block>
            </view>
          </block>
          <!-- 没有就走固定的 -->
          <block v-else>
            <view class="tips_item_box">
              <text class="font_weight">1、签到取号：</text>
              <text>请于就诊当日到院签到，支持微信签到、自助机、服务台签到取号，可提前90分钟或延迟30分钟（超过30分钟则预约无效，需要重新排号）；</text>
            </view>
            <view class="tips_item_box">
              <text class="font_weight">2、退号：</text>
              <text>如您无法按时就诊，请至少提前1天取消，以免因为爽约影响下次预约；</text>
            </view>
            <view class="tips_item_box">
              <text class="font_weight">3、首次就诊患者：</text>
              <text>需要带身份证原件办理开卡；</text>
              <text class="font_weight">未实名制的复诊患者：</text>
              <text>在就诊前需要持本人有效身份证证件进行实名认证，否则无法就诊；有效证件类型包括：身份证、社保卡、户口簿（仅限未成年）、护照、驾驶证、港澳台通行证、老人证、军官证、出生证（仅限新生儿）。</text>
            </view>
          </block>
        </view>
        <text v-if="pageType == 'czjf' && orderInfo.ServiceId == '006'">尊敬的患者，系统正在为您的就诊卡账户充值，充值过程大约需要3~5分钟，祝您早日康复！</text>
        <text v-if="pageType == 'czjf' && orderInfo.ServiceId == '007'">尊敬的患者，系统正在为住院预交金账户<text class="colorRed">{{ orderInfo.CardNo }}</text>充值，充值过程大约需要3~5分钟，祝您早日康复！</text>
        <text v-if="pageType == 'orderPayment'">尊敬的患者，系统正在为您进行结算，结算过程大约需要3-5分钟，祝您早日康复！</text>
        <text v-if="pageType == 'refund'">尊敬的患者，系统退款金额将在5个工作日内原路退还到您的充值账户内！</text>
      </view>
      <!-- 等于在线签到且有候诊查询时展示候诊 -->
      <view class="tips_box" v-if="pageType == 'signIn' && pageConfig.signInQueue">
        <queueItem :orderInfo="queryBean" :currentUser="currentUser" :ifGetQueueInfo="true"></queueItem>
      </view>
      <!-- 医技预约状态 -->
      <block v-if="pageType == 'yjyy'">
        <view class="con">
          <view class="tips" v-if="isSuccess">
            请与就诊当日提前20分钟到该医技科室，若您无法 按时就诊，请至少提前一天进行取消，祝您早日康复~
            <view class="yjyy_tipInfo">
              <view>注意事项：</view>
              <view>1、CT、MRI检查当天需到自助机打印预约单；</view>
              <view>2、窗口签到；</view>
              <view>
                3、<view class="btn" @click="gotoAppointmentRecord">预约回执单</view>
              </view>
            </view>
          </view>
          <view class="tips" v-else>
            非常抱歉，预约失败，请稍后重试。
            <view class="btn" @click="gotoAppointmentRecord">查看记录</view>
          </view>
        </view>
      </block>
      <view class="btn_box">
        <view class="btn" @click="btnClick">回到首页</view>
        <view class="btn" v-if="pageType == 'yjyy'" @click="clickAi">智能导诊</view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import common from '@/utils/common';
import icon from '@/utils/icon';
import { orderDetailLocal, orderCancel } from '@/pagesPatient/service/record/index';
import { getAppointReceiptInfo } from '@/pagesPatient/service/otherService/index';
import queueItem from '@/pagesPatient/st1/components/queueItem/queueItem.vue';

const app = getApp();
const isSuccess = ref(true);
const pageType = ref('card');
const showCon = ref(false);
const orderInfo = ref<any>({});
const orderId = ref('');
const toUrl = ref('');
const pageConfig = ref<any>({});
const queryBean = ref<any>('');
const currentUser = ref<any>({});
const info = ref<any>({});

onLoad((options: any) => {
  pageConfig.value = common.deepCopy(app.globalData.config?.pageConfiguration?.payState_config || {});
  toUrl.value = options.toUrl || '';
  orderId.value = options.orderId || '';
  pageType.value = options.pageType || 'card';
  isSuccess.value = options.isSuccess === 'false' ? false : true;
  queryBean.value = options.queryBean ? JSON.parse(options.queryBean) : '';
  currentUser.value = app.globalData.currentUser || {};
  
  main();
});

const main = async () => {
  let tempOrderId = orderId.value;
  let tempPageType = pageType.value;
  let tempOrderInfo: any = {};
  let tempInfo: any = {};
  
  // 判断orderId不为空的时候查询订单详情
  if (!common.isEmpty(tempOrderId)) {
    try {
      let orderResp = await orderDetailLocal({ OrderId: tempOrderId });
      if (!common.isEmpty(orderResp) && orderResp.length > 0) {
        tempOrderInfo = orderResp[0];
        let serviceId = tempOrderInfo.ServiceId;
        tempPageType = serviceId == '006' || serviceId == '007' ? 'czjf' : 
                       serviceId == '0' || serviceId == '009' ? 'yygh' : 
                       serviceId == '011' || serviceId == '008' ? 'orderPayment' : pageType.value;
        
        // 判断订单返回是否存在扩展字段,存在转json格式
        if (tempOrderInfo.OrderMemo) {
          tempOrderInfo.OrderMemo = JSON.parse(tempOrderInfo.OrderMemo);
          // 判断是否允许取消预约
          chkAllowCancel(tempOrderInfo);
        }
      }
    } catch (e) {
      console.error(e);
    }
  }
  
  if (tempPageType == 'yjyy') {
    try {
      const resp = await getAppointReceiptInfo(queryBean.value.hisKey);
      if (common.isNotEmpty(resp)) {
        tempInfo = resp;
      }
    } catch (e) {
      console.error(e);
    }
  }
  
  info.value = tempInfo;
  pageType.value = tempPageType;
  orderInfo.value = tempOrderInfo;
  showCon.value = true;
};

const btnClick = () => {
  common.goToUrl('/pages/st1/business/tabbar/homePage/homePage', { skipWay: "reLaunch" });
};

const gotoAppointmentRecord = () => {
  common.goToUrl(`/pages/st1/green/business/record/outpatientMedical/outpatientMedical`);
};

const clickAi = () => {
  uni.navigateToMiniProgram({
    appId: 'wx1ccb00ea4ab483fe',
    path: `/pages/prediagnosis?partnerId=100000038&hospitalId=800000366&registerId=${orderId.value}`,
    success(res) {
      // 打开成功
    }
  });
};

const chkAllowCancel = (info: any) => {
  const timeLimit = 1; // 提前取消最小时间间隔（单位：天）
  if (pageType.value !== 'yygh') {
    return;
  }
  let { RegDate } = info.OrderMemo;
  if (RegDate) {
    RegDate = RegDate.replace(/-/g, '/');
    const targetDate = new Date(`${RegDate}`);
    const today = new Date(new Date().toLocaleDateString());
    // @ts-ignore
    info.allowCancel = (targetDate - today) >= timeLimit * 24 * 60 * 60 * 1000;
  }
};

const cancelAppointment = () => {
  common.showModal(`确认退号吗？`, async () => {
    try {
      const orderCancelData = {
        ...orderInfo.value,
        OrderId: orderInfo.value.OrderId,
        OperatorId: orderInfo.value.OperatorId,
        OperatorName: orderInfo.value.OperatorName
      };
      // Note: Original code calls record.orderCancel(orderCancelData) but orderCancel signature is (data, serviceId) or (data). 
      // Checking service definition: export const orderCancel = async (queryData: any, serviceId: any = '') => { ... }
      // So passing just orderCancelData is fine if serviceId logic is handled or empty. 
      // However, usually we pass serviceId. The original code in `payState.js` was:
      // await record.orderCancel(orderCancelData)
      // I'll stick to that.
      
      await orderCancel(orderCancelData, orderInfo.value.ServiceId); // Better to pass ServiceId if available
      
      common.showModal('取消成功', () => {
        // Refresh
        main();
      });
    } catch (e) {
      console.error(e);
    }
  });
};

const toAppointmentRecord = () => {
  common.goToUrl(`/pagesPatient/st1/business/record/appointmentRecord/appointmentRecord`);
};
</script>

<style scoped lang="scss">
.container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.main_box {
  width: 100%;
  height: 100%;
  padding: 30upx;
  box-sizing: border-box;
  padding-bottom: 210upx;
  overflow: auto;
}

.make_msg_box {
  width: 100%;
  padding: 64upx 0upx 30upx 0upx;
  box-sizing: border-box;
  background: white;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border-radius: 24upx;
}

.mb30 {
  margin-bottom: 34upx;
}

.topBorderRadius {
  border-radius: 24upx 24upx 0 0 !important;
}

.bottomBorderRadius {
  border-radius: 0 0 30upx 30upx !important;
}

.make_msg_box .success_icon {
  width: 120upx;
  height: 120upx;
  margin-bottom: 30upx;
}

.make_msg_box .title {
  font-size: 36upx;
  font-family: PingFang SC;
  font-weight: bold;
  color: #333;
  text-align: left;
}

.division_icon {
  width: 100%;
  height: 48upx;
}

.time_box {
  width: 100%;
  background: white;
  padding: 10upx 30upx 16upx;
  box-sizing: border-box;
  border-radius: 24upx;
}

.time_box_list {
  width: 100%;
  padding-bottom: 32upx;
  align-items: flex-start;
  position: relative;
  display: flex;
  flex-direction: row;
}

.time_box_list:last-child {
  margin-bottom: 0;
}

.time_box_list .time_leftText {
  width: 28%;
  font-size: 30upx;
  font-family: PingFang SC;
  color: #8A8A99;
  text-align: left;
}

.time_box_list .time_rightText {
  width: 72%;
  font-size: 30upx;
  font-family: PingFang SC;
  color: #222326;
}

.sign_main_box {
  width: 100%;
}

.tips_box {
  margin-top: 30upx;
  background: white;
  padding: 30upx;
  box-sizing: border-box;
  border-radius: 24upx;
}

.tips_box text {
  line-height: 48upx;
  font-size: 30upx;
}

.tips_title_box {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 30upx;
}

.tips_title_box image {
  width: 20upx;
  height: 20upx;
}

.tips_title_box text {
  font-size: 32upx;
  font-weight: bold;
  color: #333;
  margin: 0 20upx;
}

.tips_item_box {
  margin-bottom: 20upx;
  display: flex;
  flex-direction: column;
}

.font_weight {
  font-weight: bold;
  color: #333;
}

.colorRed {
  color: #ff5e5e;
}

.colorCustom {
  color: #29cf8c;
}

.colorCustom_F08 {
  color: #F08300;
}

.footerBtn {
  display: flex;
  justify-content: flex-end;
  padding-top: 20upx;
  border-top: 1upx solid #eee;
}

.footerBtn text {
  padding: 10upx 30upx;
  border-radius: 30upx;
  font-size: 28upx;
  margin-left: 20upx;
}

.border {
  border: 1upx solid #29cf8c;
}

.btn_box {
  width: 100%;
  margin-top: 60upx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.btn {
  width: 690upx;
  height: 88upx;
  background: #29cf8c;
  border-radius: 44upx;
  text-align: center;
  line-height: 88upx;
  color: white;
  font-size: 32upx;
  margin-bottom: 30upx;
}

.yjyy_tipInfo {
  margin-top: 20upx;
  font-size: 28upx;
  color: #666;
}

.con {
  background: #fff;
  border-radius: 20upx;
  padding: 30upx;
  margin-top: 20upx;
}
</style>
