<template>
  <full-page mainStyle="background:#f0f0f0" :class="{ 'elder-mode': elderMode }">
    <template v-if="order">
      <view v-if="order.text" class="info" :class="{ 'info--elder': elderMode }">
        <view class="name" :class="{ 'name--elder': elderMode }" :style="{ color: order.color }">{{ order.text }}</view>
        <view v-if="order.subText" style="margin-top: 10rpx;" :class="{ 'sub-text--elder': elderMode }">{{ order.subText
        }}</view>
      </view>
      <view class="info" :class="{ 'info--elder': elderMode }">
        <view class="info-row" :class="{ 'info-row--elder': elderMode }">
          <text class="name" :class="{ 'name--elder': elderMode }">{{ order.doctorName }}</text>
          <text :class="{ 'title-text--elder': elderMode }">{{ order.doctorTitle }}</text>
        </view>
        <view class="info-row" :class="{ 'info-row--elder': elderMode }">
          <text :class="{ 'hospital-text--elder': elderMode }">震元堂中医院</text>
          <text v-if="order.deptName" :class="{ 'dept-text--elder': elderMode }"> | {{ order.deptName }}</text>
        </view>
      </view>
      <disease-summary :order="order" :elderMode="elderMode" />
      <view v-if="diagnosis" class="order-form" :class="{ 'order-form--elder': elderMode }">
        <view class="order-form-row" :class="{ 'order-form-row--elder': elderMode }" @click="viewSumarry()">
          <text class="order-form-label" :class="{ 'order-form-label--elder': elderMode }">病历概要：</text>
          <text style="color:$theme-brown-primary" :class="{ 'link-text--elder': elderMode }">点击查看</text>
        </view>
      </view>
      <view class="order-form" :class="{ 'order-form--elder': elderMode }">
        <view class="order-form-row" :class="{ 'order-form-row--elder': elderMode }">
          <text class="order-form-label" :class="{ 'order-form-label--elder': elderMode }">订单编号：</text>
          <text :class="{ 'form-text--elder': elderMode }">{{ order.orderId }}</text>
        </view>
        <view class="order-form-row" :class="{ 'order-form-row--elder': elderMode }">
          <text class="order-form-label" :class="{ 'order-form-label--elder': elderMode }">下单时间：</text>
          <text :class="{ 'form-text--elder': elderMode }">{{
            order.createTime
              ? dayjs(order.createTime).format("YYYY-MM-DD HH:mm")
              : ""
          }}</text>
        </view>
        <view v-if="order.settlement && order.settlement.total_fee" class="order-form-row"
          :class="{ 'order-form-row--elder': elderMode }">
          <text class="order-form-label" :class="{ 'order-form-label--elder': elderMode }">互联网诊查费：</text>
          <text :class="{ 'form-text--elder': elderMode }">￥{{ order.settlement.total_fee }}</text>
        </view>
        <view v-if="order.settlement" class="order-form-row" :class="{ 'order-form-row--elder': elderMode }">
          <text class="order-form-label" :class="{ 'order-form-label--elder': elderMode }">支付方式：</text>
          <text :class="{ 'form-text--elder': elderMode }">支付宝医保支付</text>
        </view>
        <view v-if="order.settlement && order.settlement.chage_date" class="order-form-row"
          :class="{ 'order-form-row--elder': elderMode }">
          <text class="order-form-label" :class="{ 'order-form-label--elder': elderMode }">支付时间：</text>
          <text :class="{ 'form-text--elder': elderMode }">
            {{
              order.settlement && order.settlement.chage_date
                ? dayjs(order.settlement.chage_date).format(
                  "YYYY-MM-DDHH: mm: ss"
                )
                : ""
            }}
          </text>
        </view>
        <view v-if="order.drugStoreName" class="order-form-row" :class="{ 'order-form-row--elder': elderMode }">
          <text class="order-form-label" :class="{ 'order-form-label--elder': elderMode }">来源：</text>
          <text :class="{ 'form-text--elder': elderMode }"> {{ order.drugStoreName }} </text>
        </view>
        <view class="order-form-row" :class="{ 'order-form-row--elder': elderMode }">
          <text class="order-form-label" :class="{ 'order-form-label--elder': elderMode }">终端：</text>
          <text :class="{ 'form-text--elder': elderMode }"> 支付宝小程序 </text>
        </view>
      </view>
    </template>
    <empty-data v-else :text="msg" />
    <template #footer>
      <view v-if="order && order.showFooter" class="footer" :class="{ 'footer--elder': elderMode }">
        <view v-if="order.canPay" class="footer__btn primary" :class="{ 'footer__btn--elder': elderMode }"
          @click="toPay()">支付</view>
        <view v-if="order.canCancel" class="footer__btn inactive" :class="{ 'footer__btn--elder': elderMode }"
          @click="cancelOrder()">取消</view>
        <view v-if="order.enterRoom" class="footer__btn primary" :class="{ 'footer__btn--elder': elderMode }"
          @click="enterRoom()">{{ order.enterRoomText }}</view>
      </view>
    </template>
  </full-page>
</template>
<script setup>
import { ref, onMounted } from "vue";
import { onLoad, onUnload } from "@dcloudio/uni-app";
import dayjs from "dayjs";
import useYbPay from "@/hooks/useYbPay";
import {
  getPatientOrder,
  getOrderDiagnosis,
  cancelConsultOrder,
} from "@/utils/api";
import { useIMStore } from "@/store/tim";
import { toast, confirm, loading, hideLoading } from "@/utils/widget";
import { getOrderStatus } from "@/utils";

import diseaseSummary from "@/pages/consult/components/disease-summary.vue";
import emptyData from "@/components/empty.vue";
import fullPage from "@/components/full-page.vue";

const order = ref(null);
const msg = ref("");
const pay = useYbPay(null, reload);
const diagnosis = ref(null)
const timer = ref(null)

// 适老化模式状态
const elderMode = ref(false);

onMounted(() => {
  // 从本地存储读取适老化模式状态
  const savedElderMode = uni.getStorageSync('elderMode')||false;

  if (savedElderMode !== null && savedElderMode !== undefined) {
    elderMode.value = !!savedElderMode
  }
});

onLoad((e) => {
  if (e.orderId) {
    getOrderDetail(e.orderId);
  }
});
onUnload(() => {
  timer.value && clearInterval(timer.value)
})

function reload() {
  if (order.value && order.value.orderId) {
    getOrderDetail(order.value.orderId)
  }
}

async function getOrderDetail(orderId) {
  const { success, data, message } = await getPatientOrder({ orderId });
  if (success) {
    order.value = {
      ...data,
      ...getOrderStatus(data),
    };
    if (order.value.hasPassDiagnostic) {
      getDiagnosis()
    }
  } else {
    order.value = null;
    toast(message);
    msg.value = message || "获取订单失败";
  }
  console.log("order", order.value);
}

function toPay() {
  pay(order.value);
}

async function cancelOrder() {
  const item = order.value;
  await confirm("确定取消订单吗？");
  const { success, message } = await cancelConsultOrder({
    orderId: item.orderId,
  });
  if (success) {
    toast("取消成功");
    getOrderDetail(item.orderId);
  } else {
    toast(message || "取消失败");
  }
}

async function enterRoom() {
  const { doctorCode, orderId } = order.value;
  if (!doctorCode) {
    toast("进入视频间错误,医生视频账号不存在 ");
    return;
  }
  if (!orderId) {
    toast("进入视频间错误,用户视频账号不存在 ");
    return;
  }
  loading("正在进入视频间, 请稍后等待");
  const imStore = useIMStore();
  try {
    const res = await imStore.login(orderId);
    if (!res) {
      hideLoading()
      toast("IM 登录失败");
      return;
    }
    await new Promise((resolve) => {
      if (imStore.isSDKReady) {
        resolve();
      } else {
        timer.value = setInterval(() => {
          if (imStore.isSDKReady) {
            clearInterval(timer.value);
            timer.value = null
            resolve();
          }
        }, 500);
      }
    });
    const conversationID = `C2C${doctorCode}`;
    uni.navigateTo({
      url: `/pages/chat/index?conversationID=${conversationID}&orderId=${orderId}`,
    });
  } catch (e) {
    hideLoading()
    toast(`进入会话失败: ${e.message || "未知错误"}`);
  }

}

async function getDiagnosis() {
  const { data } = await getOrderDiagnosis({ orderId: order.value.orderId, status: 'PASS' });
  diagnosis.value = data || null;
}

function viewSumarry() {
  if (diagnosis.value) {
    uni.setStorageSync('order-diagnosis', JSON.stringify(diagnosis.value));
    uni.navigateTo({
      url: '/pages/record/order-diagnosis'
    })
  }
}

</script>
<style lang="scss" scoped>
.order-form {
  margin-top: 20rpx;
  background: #fff;

  // 适老化模式：表单区域整体变大
  @at-root &--elder {
    margin: 30rpx 20rpx 20rpx 20rpx;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  }
}

.order-form-row {
  display: flex;
  padding: 24rpx 30rpx;
  font-size: 28rpx;
  color: #333;

  @at-root &+& {
    border-top: 1px solid #e5e5e5;
  }

  // 适老化模式：行内边距增加，字体放大，元素各占一行
  @at-root &--elder {
    flex-direction: column;
    align-items: flex-start;
    gap: 12rpx;
    padding: 36rpx 40rpx;
    font-size: 39rpx; // 28 * 1.4
    font-weight: 500;
  }
}

.order-form-label {
  color: #666;

  // 适老化模式：标签字体放大，加粗
  @at-root &--elder {
    font-size: 39rpx; // 28 * 1.4
    font-weight: bold;
  }
}

.info {
  padding: 24rpx 30rpx;
  margin-bottom: 20rpx;
  background-color: #fff;
  line-height: 40rpx;
  color: #666;
  font-size: 28rpx;

  // 适老化模式：信息区域内边距增加，字体和行高放大
  @at-root &--elder {
    padding: 36rpx 40rpx;
    margin: 30rpx 20rpx 20rpx 20rpx;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
    font-size: 39rpx; // 28 * 1.4
    line-height: 56rpx; // 40 * 1.4
    font-weight: 500;
  }
}

.info-row {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;

  // 适老化模式：元素各占一行，允许换行
  @at-root &--elder {
    white-space: normal;
    overflow: visible;
    text-overflow: unset;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 12rpx;
    margin-bottom: 16rpx;
  }
}

text {
  white-space: nowrap;
}

.name {
  margin-right: 12rpx;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;

  // 适老化模式：名称字体放大
  @at-root &--elder {
    margin-right: 20rpx;
    font-size: 45rpx; // 32 * 1.4
    font-weight: bold;
  }
}

.footer {
  display: flex;
  justify-content: flex-end;
  padding: 24rpx 30rpx;
  background: white;

  // 适老化模式：底部区域内边距增加，按钮各占一行
  @at-root &--elder {
    flex-direction: column;
    align-items: stretch;
    gap: 16rpx;
    padding: 36rpx 40rpx;
  }
}

.footer__btn {
  padding: 8rpx 20rpx;
  font-size: 28rpx;
  border-radius: 20rpx;
  border: 1px solid;
  color: #333;

  @at-root &+& {
    margin-left: 20rpx;
  }

  &.primary {
    color: $theme-brown-primary;
  }

  &.inactive {
    color: #666;
  }

  // 适老化模式：按钮变大，字体放大
  @at-root &--elder {
    padding: 16rpx 32rpx;
    font-size: 39rpx; // 28 * 1.4
    border-radius: 28rpx;
    font-weight: bold;
    text-align: center;

    @at-root &+& {
      margin-left: 0;
    }
  }
}

// 适老化模式额外样式类
.sub-text--elder {
  font-size: 39rpx !important; // 28 * 1.4
  font-weight: 500;
  margin-top: 14rpx !important; // 10 * 1.4
}

.title-text--elder {
  font-size: 39rpx !important; // 28 * 1.4
  font-weight: 500;
}

.hospital-text--elder {
  font-size: 39rpx !important; // 28 * 1.4
  font-weight: 500;
}

.dept-text--elder {
  font-size: 39rpx !important; // 28 * 1.4
  font-weight: 500;
}

.link-text--elder {
  font-size: 39rpx !important; // 28 * 1.4
  font-weight: bold;
}

.form-text--elder {
  font-size: 39rpx !important; // 28 * 1.4
  font-weight: 500;
}
</style>
