<template>
  <full-page mainStyle="background:#f0f0f0" @reachBottom="loadMore()">
    <view class="p-15" :style="elderVarStyle">
      <view v-for="(item, idx) in list" :key="item._id" class="bg-white shadow-lg rounded"
        :class="idx > 0 ? 'mt-12' : ''" @click="viewPaper(item)">
        <view class="flex jusitfy-between py-12 px-15 border-b">
          <view class="mr-10 w-0 flex-grow">
            <text class="mr-5 text-base text-gray">{{ item.time }}</text>
            <text class="text-base text-gray">({{ item.typeText }})</text>
          </view>
          <view v-if="item.hisUploadStatus === 'uploaded'" class="flex-shrink-0 text-base text-success">已上传</view>
          <view v-else-if="item.hisUploadStatus === 'error'" class="flex-shrink-0 text-base text-danger">上传错误</view>
        </view>
        <view class="py-12 px-15 leading-normal"
          :class="item.prescriptionType === 'onlineMedicinePurchase' ? 'border-b' : ''">
          <view class="flex pb-5">
            <view class="flex-shrink-0 text-base text-gray mr-10"> 患者:</view>
            <view class="text-base text-dark">
              {{ item.name }} {{ item.sex }} {{ item.age ? item.age + '岁' : '' }}
            </view>
          </view>
          <view class="flex pb-5">
            <view class="flex-shrink-0 text-base text-gray mr-10"> 医生:</view>
            <view class="text-base text-dark"> {{ item.doctorName }} {{ item.deptName }} </view>
          </view>
          <view class="flex pb-5">
            <view class="flex-shrink-0 text-base text-gray mr-10"> 诊断:</view>
            <view class="text-base text-dark"> {{ item.diagnosisStr }} </view>
          </view>
          <view class="flex">
            <view class="flex-shrink-0 text-base text-gray mr-10"> 药品:</view>
            <view class="text-base text-dark"> {{ item.drugNames }} </view>
          </view>
        </view>
        <view v-if="item.prescriptionType === 'onlineMedicinePurchase'"
          class="flex items-center justify-between px-15 py-12">
          <view class="mr-10 w-0 flex-grow">
            <template v-if="expireTimeStr[item._id]">
              <text class="text-base text-danger">{{ expireTimeStr[item._id] }}</text>
              <text class="text-base text-dark">后失效</text>
            </template>
          </view>
          <view v-if="item.canPay" class="px-10 py-5 rounded-full border-primary text-primary text-base"
            @click.stop="handleInsurancePayment(item)">医保结算</view>
          <view v-else-if="item.canViewOrder" class="px-10 py-5 rounded-full border-primary text-primary text-base"
            @click.stop="viewOrder(item)">查看订单</view>
          <view v-else-if="item.isExpired" class="px-10 py-5 rounded-full border text-gray text-base">
            已失效
          </view>
        </view>
      </view>

    </view>
    <empty-data v-if="list.length === 0" />
  </full-page>
  <refresh-icon v-if="!loading" @refresh="refresh()" />

</template>
<script setup>
import { ref, computed } from 'vue';
import { onLoad } from "@dcloudio/uni-app";
import dayjs from 'dayjs';
import useElder from '@/hooks/useElder';
import useUser from '@/hooks/useUser';
import usePageList from '@/hooks/usePageList';
import { getAccountRxList, getRxMedicinePurchaseOrderId } from "@/utils/api";
import { toast, loading as showLoading, hideLoading } from "@/utils/widget";

import fullPage from '@/components/full-page.vue';
import refreshIcon from '@/components/refresh-icon.vue';
import emptyData from "@/components/empty.vue";

const { elderVarStyle } = useElder();
const PrescriptionType = {
  onlineMedicinePurchase: '在线配药', // 线上购药 (在线咨询 物流配送药品)
  storeMedicinePurchase: '在线复诊'
}

const { userInfo } = useUser();
const { page, pageSize, list, pages, changePage, loading, hasMore } = usePageList(getList, { pageSize: 10 });
const serviceTime = ref(0);

const expireTimeStr = computed(() => list.value.reduce((acc, item) => {
  if (item.prescriptionType === 'onlineMedicinePurchase' && !item.isExpired && (!item.purchaseOrder || 'unpay' === item.purchaseOrder.status)) {
    const diff = item.expireTime - serviceTime.value;
    if (diff > 0) {
      const hours = Math.floor(diff / 3600 / 1000);
      const minutes = Math.floor((diff % (3600 * 1000)) / (60 * 1000));
      if (hours > 0) {
        acc[item._id] = `${hours}小时${minutes}分`;
      } else {
        acc[item._id] = `${Math.max(1, minutes)}分`;
      }
    }
  }
  return acc
}, {}))

async function getList() {
  if (loading.value) return;
  loading.value = true;
  showLoading();
  const res = await getAccountRxList({
    page: page.value,
    pageSize: pageSize.value,
    accountId: userInfo.value.userId
  });
  const { success, orderList, list: data, message, pages: totalPages, now } = res || {};
  hideLoading();
  const medicineOrderList = Array.isArray(orderList) ? orderList : [];
  serviceTime.value = typeof now === 'number' ? now : 0;
  const arr = Array.isArray(data) ? data.map(i => {
    const order = medicineOrderList.find(o => o.rpNo === i._id);
    // 购药处方是否过期 
    const isExpired = i.prescriptionType === 'onlineMedicinePurchase' && i.expireTime < now && (!order || order.status === 'expired');
    // 购药处方是否可以支付
    const canPay = !isExpired && i.prescriptionType === 'onlineMedicinePurchase' && (!order || 'unpay' === order.status);
    // 查看购药订单
    const canViewOrder = order && ['shipped', 'ybPaid'].includes(order.status);
    return {
      ...i,
      time: dayjs(i.createTime).format('YYYY-MM-DD HH:mm'),
      typeText: PrescriptionType[i.prescriptionType] || PrescriptionType.ONLINE_CONSULT,
      name: i.name,
      sex: i.sex,
      age: i.age,
      doctorName: i.doctorName,
      deptName: i.deptName,
      diagnosisStr: Array.isArray(i.diagnosisList) ? i.diagnosisList.map(i => i.name).filter(Boolean).join('、') : '',
      drugNames: Array.isArray(i.drugs) ? i.drugs.map(i => i.drugName).filter(Boolean).join('、') : '',
      isExpired,
      canPay,
      canViewOrder,
      purchaseOrder: order
    }
  }) : []
  loading.value = false;
  list.value = page.value === 1 ? arr : [...list.value, ...arr];
  console.log('list.value', list.value)
  pages.value = Number.isInteger(totalPages) ? totalPages : 0;
  if (!success) {
    toast(message || '查询失败');
  }
}

function loadMore() {
  if (hasMore.value && !loading.value) {
    changePage(page.value + 1)
  }
}

function refresh() {
  if (loading.value) return;
  changePage(1)
}

function viewPaper(item) {
  uni.navigateTo({
    url: `/pages/record/rx-paper?id=${item._id}`
  })
}

async function handleInsurancePayment(item) {
  showLoading();
  const res = await getRxMedicinePurchaseOrderId({
    accountId: userInfo.value.userId,
    rpNo: item._id
  });
  hideLoading()
  if (res && res.success) {
    if (res.status === 'unpay') {
      uni.navigateTo({
        url: `/pages/consult/drug-purchase-order/drug-purchase-order?id=${res.id}`
      })
    }
    else if (res.status === 'expired') {
      toast('订单已过期');
    }
    else {
      uni.navigateTo({
        url: `/pages/consult/drug-purchase-list/detail?id=${res.id}`
      })
    }
  } else {
    toast(res.message || '获取在线配药订单失败');
  }
}

function viewOrder(item) {
  uni.navigateTo({
    url: `/pages/consult/drug-purchase-list/detail?id=${item.purchaseOrder._id}`
  })
}


onLoad(() => {
  changePage(1)
})
</script>

<style lang="scss" scoped>
.container {
  padding: 30rpx;

  // 适老化模式：容器内边距增加
  @at-root &--elder {
    padding: 40rpx 20rpx;
  }
}

.prescription-list {
  .card {
    background: #fff;
    border-radius: 16rpx;
    margin-bottom: 24rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
    padding: 32rpx;

    // 适老化模式：卡片整体变大
    @at-root &--elder {
      margin: 30rpx 20rpx 24rpx 20rpx;
      border-radius: 20rpx;
      box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.12);
      padding: 45rpx; // 32 * 1.4
    }

    &-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-bottom: 24rpx;
      border-bottom: 1rpx solid #eee;

      // 适老化模式：头部区域内边距增加
      @at-root &--elder {
        padding-bottom: 34rpx; // 24 * 1.4
        border-bottom: 2rpx solid #eee;
      }

      .time {
        color: #666;
        font-size: 26rpx;

        // 适老化模式：时间字体放大
        @at-root &--elder {
          font-size: 36rpx; // 26 * 1.4
          font-weight: 500;
        }
      }

      .status {
        font-size: 28rpx;
        font-weight: 500;

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

    &-body {
      padding: 24rpx 0 0;

      // 适老化模式：主体区域内边距增加
      @at-root &--elder {
        padding: 34rpx 0 0; // 24 * 1.4
      }

      .info-row {
        display: flex;
        margin-bottom: 20rpx;

        // 适老化模式：信息行间距增加
        @at-root &--elder {
          gap: 12rpx;
          margin-bottom: 28rpx; // 20 * 1.4
        }

        .label {
          width: 140rpx;
          color: #999;
          font-size: 28rpx;

          // 适老化模式：标签字体放大，保持固定宽度对齐
          @at-root &--elder {
            width: 196rpx; // 140 * 1.4 保持对齐
            font-size: 39rpx; // 28 * 1.4
            font-weight: bold;
          }
        }

        .value {
          flex: 1;
          color: #333;
          font-size: 28rpx;
          font-weight: 500;

          // 适老化模式：值字体放大
          @at-root &--elder {
            font-size: 39rpx; // 28 * 1.4
            font-weight: 500;
          }
        }
      }

      .medication {
        display: flex;
        margin-bottom: 20rpx;

        // 适老化模式：药品区域间距增加
        @at-root &--elder {
          gap: 12rpx;
          margin-bottom: 28rpx; // 20 * 1.4
        }

        .label {
          width: 140rpx;
          color: #999;
          font-size: 28rpx;

          // 适老化模式：药品标签字体放大，保持固定宽度对齐
          @at-root &--elder {
            width: 196rpx; // 140 * 1.4 保持与其他label对齐
            font-size: 39rpx; // 28 * 1.4
            font-weight: bold;
          }
        }

        .drug-list {
          flex: 1;

          .drug {
            display: block;
            color: #333;
            font-size: 28rpx;
            font-weight: 500;
            line-height: 1.6;

            // 适老化模式：药品字体放大，行高增加
            @at-root &--elder {
              font-size: 39rpx; // 28 * 1.4
              font-weight: 500;
              line-height: 1.8;
            }
          }
        }
      }

      .medical-record {
        display: flex;
        align-items: center;
        margin-top: 8rpx;

        .label {
          width: 140rpx;
          color: #999;
          font-size: 28rpx;
        }

        .link {
          font-size: 28rpx;
          font-weight: 500;
        }
      }
    }

    &-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-top: 24rpx;
      border-top: 1rpx solid #eee;

      // 适老化模式：底部区域增加间距
      @at-root &--elder {
        gap: 20rpx;
        padding-top: 34rpx; // 24 * 1.4
        border-top: 2rpx solid #eee;
      }

      .tips {
        color: #999;
        font-size: 26rpx;

        // 适老化模式：提示文字字体放大
        @at-root &--elder {
          font-size: 36rpx; // 26 * 1.4
          font-weight: 500;
        }
      }

      .detail-btn {
        height: 48rpx;
        line-height: 46rpx;
        border-radius: 24rpx;
        font-size: 28rpx;
        padding: 0 40rpx;
        margin: 0;
        border: 1px solid;
        color: $theme-brown-primary;

        &::after {
          border: none;
        }

        // 适老化模式：按钮变大
        @at-root &--elder {
          height: 67rpx; // 48 * 1.4
          line-height: 65rpx; // 46 * 1.4
          border-radius: 34rpx; // 24 * 1.4
          font-size: 39rpx; // 28 * 1.4
          padding: 0 56rpx; // 40 * 1.4
          font-weight: bold;
          border: 2px solid;
        }
      }
    }
  }
}
</style>