<template>
  <view class="container">
    <view class="content">
      <view class="userInfoTopFixe">
        <userInfo :userInfo="currentUser" :type="withoutCard ? 'member' : 'card'" bgClass="bgLinGra"></userInfo>
      </view>
      <view class="main_box">
        <view v-if="appoint.length == 0" class="noData">
          <noData :value="noDataValue"></noData>
        </view>
        <view class="item_list" v-for="(item, index) in appoint" :key="index">
          <view class="header_time border_bottom">
            <text>{{ item.regDate }} {{ item.week }}</text>
            <text class="colorCustom border boderColorCustom" 
                  v-if="item.regFlag == '1' && (item.reservationStatus == '1' || item.reservationStatus == '2')" 
                  @click="withdrawNumber(item)">取消订单</text>
          </view>
          <view class="main_centent border_bottom">
            <view class="record_info">
              <text>预约科室</text>
              <text>{{ item.deptName }}</text>
            </view>
            <view class="record_info">
              <text>预约医生</text>
              <text>{{ item.doctorName || "--" }}</text>
            </view>
            <view class="record_info">
              <text>就诊时间</text>
              <text> {{ item.timeSliceName }} {{ item.commendTime }} {{ item.sqNo }}号</text>
            </view>
            <view class="record_info">
              <text>就诊类型</text>
              <text v-if="item.sourceType == '006'">视频问诊</text>
              <text v-else>普通问诊</text>
            </view>
            <view class="record_info">
              <text>就诊位置</text>
              <text>{{ item.workPlace || "--" }}</text>
            </view>
            <view class="record_info">
              <text>就诊人</text>
              <text>{{ item.name }}</text>
            </view>
            <view class="record_info" v-if="!withoutCard">
              <text>就诊卡号</text>
              <text v-if="item.cardNo">{{ item.cardNo }}</text>
              <text v-else>暂无</text>
            </view>
          </view>
          <view class="footer_btn">
            <text :class="item.reservationStatus == 1 ? 'backgroundCustom' : item.reservationStatus == 2 ? 'backgroundCustom_F08' : 'backgroundCustom_D9'" 
                  @click="checkIn(item)">{{ item.reservationText }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onUnmounted } from 'vue';
import { onLoad, onHide } from '@dcloudio/uni-app';
import { common } from '@/utils';
import icon from '@/utils/icon';
import { hisYyWaterList_V2, orderCancel } from '@/pagesPatient/service/record';
import { regSignForHis } from '@/pagesPatient/service/yygh';

const app = getApp();
const iconUrl = ref(icon);
const noDataValue = ref("暂无符合可签到条件的预约记录");
const appoint = ref<any[]>([]);
const serviceType = ref("");
const pageConfig = ref<any>({});
const currentUser = ref<any>({});
const withoutCard = ref(false);
const lat = ref<number | null>(null);
const lng = ref<number | null>(null);
let timer: any = null;

onLoad((options: any) => {
  let config = common.deepCopy(app.globalData.config.pageConfiguration.signInList_config);
  let user = app.globalData.currentUser;
  
  pageConfig.value = config;
  currentUser.value = user;
  serviceType.value = options.serviceType || '';
  withoutCard.value = app.globalData.withoutCard;

  // 获取用户位置信息
  getUserLocation();

  // 获取预约记录
  queryYySignListForHis();
});

onHide(() => {
  if (timer) clearInterval(timer);
});

onUnmounted(() => {
  if (timer) clearInterval(timer);
});

const getUserLocation = () => {
  uni.getLocation({
    type: 'gcj02',
    success: (res) => {
      lat.value = res.latitude;
      lng.value = res.longitude;
    },
    fail: (err) => {
      console.error('获取位置失败', err);
    }
  });
};

const refresh = () => {
  queryYySignListForHis();
};

const queryYySignListForHis = async () => {
  let user = currentUser.value;
  let reqData = {
    memberId: user.memberId || '',
    cardEncryptionStore: user.encryptionStore || '',
    memberEncryptionStore: user.baseMemberEncryptionStore || '',
    startTime: common.newDay(),
    endTime: common.afterFewDays(1),
    hosId: app.globalData.districtId || app.globalData.hosId
  };
  
  let resp = await hisYyWaterList_V2(reqData);
  if (common.isNotEmpty(resp)) {
    let list = resp.filter((item: any) => item.regFlag == 1 && item.signState == 0);
    appoint.value = list;
    interval(list);
    
    if (timer) clearInterval(timer);
    timer = setInterval(() => {
      interval(list);
    }, 1000);
  } else {
    appoint.value = [];
  }
};

const interval = (list: any[]) => {
  // 获取当前时间
  let now = Date.now();
  //就诊前多久可签到
  let differenceBefore = pageConfig.value.allowedSignBefore * 60 * 1000;
  //允许超时多久还可签到
  let differenceEnd = pageConfig.value.allowedSignAfter * 60 * 1000;
  
  list.forEach(item => {
    /**就诊时间 */ 
    // common.iosTime might not be needed if date format is standard, but keeping it safe
    let dateStr = `${item.regDate} ${item.commendTime.split('-')[0]}`;
    // Replace - with / for iOS compatibility if common.iosTime is not available or handled differently
    let registertimes = new Date(dateStr.replace(/-/g, '/')).getTime();
    
    let times = registertimes - now; 
    if (registertimes - now > differenceBefore) {
      /**未到时间  减去提前可签到时间毫秒数 */
      times = registertimes - now - differenceBefore;
    }
    
    let days = Math.floor(times / (24 * 60 * 60 * 1000));
    let hours = Math.floor(times % (24 * 60 * 60 * 1000) / (60 * 60 * 1000));
    let mins = common.formatNumber(Math.floor(times % (24 * 60 * 60 * 1000) % (60 * 60 * 1000) / (60 * 1000)));
    let secs = common.formatNumber(Math.floor(times % (24 * 60 * 60 * 1000) % (60 * 60 * 1000) % (60 * 1000) / 1000));
    
    // reservationStatus: 0：过期   1：可签到  3：时间未到  2：即将超时
    if (registertimes - now > differenceBefore) {
      /**未到时间 */
      let tips = days > 0 ? `${days}天` : hours > 0 ? `${hours}小时` : `${mins}分${secs}秒`;
      item.reservationStatus = 3;
      item.reservationText = `时间未到,${tips}后可签到`;
    } else if (registertimes - now <= differenceBefore && registertimes - now >= 0) {
      item.reservationStatus = 1;
      item.reservationText = '就诊签到';
    } else if (now - registertimes > 0 && now - registertimes <= differenceEnd) {
      /**由于超时分值是负数所以要负数转正数*/
      let tips = hours > 0 ? `${hours}小时` : `${common.formatNumber(Number(mins) * -1)}分${common.formatNumber(Number(secs)* -1)}秒`;
      item.reservationStatus = 2;
      item.reservationText = `已超过签到时间 ${tips}`;
    } else if (now - registertimes > differenceEnd) {
      item.reservationStatus = 0;
      item.reservationText = '已过期';
    }
  });
  
  list.sort(compare);
  appoint.value = [...list]; // Trigger reactivity
};

const compare = (orderInfo1: any, orderInfo2: any) => {
  var registerdate1 = orderInfo1.regDate + " " + orderInfo1.commendTime + ":00";
  var registerdateStr1 = registerdate1.replace(/-/g, "/");
  let registerdateTime1 = new Date(registerdateStr1).getTime();

  var registerdate2 = orderInfo2.regDate + " " + orderInfo2.commendTime + ":00";
  var registerdateStr2 = registerdate2.replace(/-/g, "/");
  let registerdateTime2 = new Date(registerdateStr2).getTime();
  
  if (registerdateTime1 > registerdateTime2) {
    if (orderInfo2.reservationStatus == 0 && orderInfo1.reservationStatus > 0) {
      return -1;
    }
    return 1;
  } else if (registerdateTime1 < registerdateTime2) {
    if (orderInfo1.reservationStatus == 0 && orderInfo2.reservationStatus > 0) {
      return 1;
    }
    return -1;
  }
  return 0;
};

const withdrawNumber = (item: any) => {
  let user = currentUser.value;
  common.showModal("您正在进行退号操作，为了避免误操作带来的不必要损失，系统需要您再次确认", async () => {
    let orderCancelData = {
      ...item,
      MemberStore: {
        cardEncryptionStore: user.encryptionStore || '',
        baseMemberEncryptionStore: user.baseMemberEncryptionStore
      },
      Store: {
        cardEncryptionStore: user.encryptionStore || '',
        baseMemberEncryptionStore: user.baseMemberEncryptionStore
      }
    };
    let resp = await orderCancel(orderCancelData, 0);
    if (!common.isEmpty(resp)) {
      if (timer) clearInterval(timer);
      /**取消成功 */
      common.showModal(`退号成功`, () => {
        queryYySignListForHis();
      }, {
        confirmText: '好的'
      });
    }
  }, {
    title: "温馨提示",
    cancelText: "取消"
  });
};

const checkIn = (item: any) => {
  // 判断当前时间未到
  if (item.reservationStatus !== 1 && item.reservationStatus !== 2) return;
  
  // 获取医院信息
  let hospitalInfo = app.globalData.hospitalInfo;
  if (common.isNotEmpty(hospitalInfo)) {
    let hosLat = hospitalInfo.Wd;
    let hosLng = hospitalInfo.Jd;
    if (common.isEmpty(hosLat) || common.isEmpty(hosLng)) {
      common.showToast("没有找到医院位置信息，无法线上签到。");
      return;
    }
    
    uni.getLocation({
      type: 'gcj02',
      success: async (res) => {
        // Use common.getDistance or implement it if missing. Assuming common has it based on original code.
        let distance = common.getDistance(res.latitude, res.longitude, hosLat, hosLng);
        if (distance > pageConfig.value.signDistance) {
          common.showModal(`距离医院${pageConfig.value.signDistance}公里内才可以进行在线签到，当前距离医院${distance}公里无法进行在线签到`);
          return;
        }
        
        // 判断可以无卡预约 跳转选卡页面进行校验签到
        if (withoutCard.value) {
          let queryBeanStr = encodeURIComponent(JSON.stringify(item));
          common.goToUrl(`/pagesPatient/st1/business/signIn/signInDetails/signInDetails?queryBean=${queryBeanStr}`);
        } else {
          let user = currentUser.value;
          let querData = {
            CardNo: user.cardNo,
            CardType: user.cardType,
            MemberId: user.memberId,
            OrderId: "",
            ChannelId: item.channelId,
            DeptName: item.deptName,
            DoctorCode: item.doctorCode,
            HisOrderId: item.hisOrderId,
            IdCardId: "",
            QueueNo: item.sqNo,
            RegisterDate: item.regDate,
            SourceType: "",
            UserName: item.name,
            //后端表示原因,在此用于区分是否走星网
            Reason: pageConfig.value.signReason,
            Store: {
              baseMemberEncryptionStore: user.baseMemberEncryptionStore,
              cardEncryptionStore: user.encryptionStore || ''
            }
          };
          
          let resp = await regSignForHis(querData);
          if (!common.isEmpty(resp)) {
            let queryBeanStr = JSON.stringify({
              ...resp[0]
            });
            console.log(queryBeanStr);
            common.goToUrl(`/pagesPatient/st1/business/pay/payState/payState?pageType=signIn&queryBean=${queryBeanStr}`);
          }
        }
      },
      fail: (err) => {
        common.showModal('请授权获取位置信息以进行签到');
      }
    });
  }
};
</script>

<style scoped>
.noData {
  width: 100%;
  padding-top: 0 !important;
  position: absolute;
  top: 50%;
  margin-top: -100upx;
}

.main_box {
  padding-top: 190upx;
}

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

.header_time {
  height: 100upx;
  padding: 36upx;
  box-sizing: border-box;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

.header_time text:nth-child(1) {
  line-height: 32upx;
  font-size: 32upx;
  color: #333;
}

.header_time text:nth-child(2) {
  display: inline-block;
  width: 168upx;
  line-height: 56upx;
  text-align: center;
  font-size: 28upx;
  position: relative;
}

.main_centent {
  padding: 36upx;
  box-sizing: border-box;
}

.record_info {
  margin-bottom: 36upx;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

.record_info:last-child {
  margin-bottom: 0 !important;
}

.record_info text:nth-child(1) {
  width: 26%;
  display: inline-block;
  font-size: 30upx;
  color: #666;
}

.record_info text:nth-child(2) {
  width: 74%;
  display: inline-block;
  font-size: 30upx;
  color: #333;
}

.footer_btn {
  padding: 30upx;
}

.footer_btn text {
  display: inline-block;
  width: 100%;
  line-height: 98upx;
  text-align: center;
  border-radius: 50upx;
  color: white;
  font-size: 36upx;
  position: relative;
  z-index: 0;
}
</style>