<template>
  <cwg-page-wrapper>
    <view class="order-detail-page">
      <view class="content">
        <view class="status-card section-card">
          <view class="success-icon-wrapper">
            <image v-if="orderDetail.orderStatus === 'success'" src="/static/images/vector.png" alt=""
              mode="widthFix" />
            <image v-else-if="orderDetail.orderStatus === 'failed'" src="/static/images/vector2.png" alt=""
              mode="widthFix" />
            <image v-else src="/static/images/vector3.png" alt="" mode="widthFix" />
          </view>
          <text class="status-title">{{ getOrderStatusText(orderDetail.orderStatus) }}</text>
          <text v-if="approveDesc" class="success-text">{{ approveDesc }}</text>
        </view>

        <!-- Approval Progress -->
        <!-- <view class="section-card">
          <view class="section-header">
            <uni-icons type="bars" size="18" color="#2563eb" />
            <text class="section-title">{{ t('card.Status.t15') }}</text>
          </view>

          <view class="approval-timeline">
            <view v-for="(step, index) in orderDetail.approvalSteps" :key="index" class="timeline-item">
              <view class="timeline-left">
                <view
                  :class="['timeline-dot', step.status === 'completed' ? 'timeline-dot-active' : step.status === 'current' ? 'timeline-dot-current' : '']">
                  <uni-icons v-if="step.status === 'completed'" type="checkmarkempty" size="14" color="#ffffff" />
                </view>
                <view v-if="index < orderDetail.approvalSteps.length - 1" class="timeline-line"></view>
              </view>

              <view class="timeline-right">
                <view class="timeline-header">
                  <text class="timeline-title">{{ step.title }}</text>
                  <view v-if="step.status === 'completed'" class="timeline-status completed">
                    <uni-icons type="checkmarkempty" size="12" color="#22c55e" />
                    <text class="timeline-status-text">{{ t('State.Completed') }}</text>
                  </view>
                  <view v-else-if="step.status === 'current'" class="timeline-status current">
                    <uni-icons type="info" size="12" color="#eab308" />
                    <text class="timeline-status-text">{{ t('State.Ongoing') }}</text>
                  </view>
                  <view v-else class="timeline-status pending">
                    <text class="timeline-status-text">{{ t('State.ToBeProcessed') }}</text>
                  </view>
                </view>
                <text v-if="step.operator" class="timeline-operator">操作人: {{ step.operator }}</text>
                <text v-if="step.time" class="timeline-time">{{ step.time }}</text>
                <text v-if="step.remark" class="timeline-remark">{{ step.remark }}</text>
              </view>
            </view>
          </view>
        </view> -->

        <!-- Amount Info -->
        <view class="section-card">
          <view class="section-header">
            <uni-icons type="wallet" size="18" color="#2563eb" />
            <text class="section-title">{{ t('card.Form.f55') }}</text>
          </view>

          <view class="info-list">
            <view class="info-row">
              <text class="info-label">{{ t('card.Form.f37') }}</text>
              <text class="info-value amount-highlight">
                {{ orderDetail.amount.toFixed(2) }} <text class="currency">{{ orderDetail.currency || 'USD' }}</text>
              </text>
            </view>

            <view class="info-row">
              <text class="info-label">{{ t('card.Form.f30') }}</text>
              <text class="info-value">
                {{ orderDetail.fee.toFixed(2) }} <text class="currency">{{ orderDetail.currency || 'USD' }}</text>
              </text>
            </view>

            <!-- <view class="divider"></view>

            <view class="info-row">
              <text class="info-label total-label">{{ t('card.Form.f55') }}</text>
              <text class="info-value total-value">
                {{ orderDetail.actualAmount.toFixed(2) }} <text class="currency">{{ orderDetail.currency || 'USD'
                  }}</text>
              </text>
            </view> -->
          </view>
        </view>

        <!-- Order Info -->
        <view class="section-card">
          <view class="section-header">
            <uni-icons type="list" size="18" color="#2563eb" />
            <text class="section-title">{{ t('global.title3') }}</text>
          </view>

          <view class="info-list">
            <view class="info-row" v-if="orderDetail.orderNo">
              <text class="info-label">{{ t('card.Form.f35') }}</text>
              <view class="info-value-wrapper">
                <text class="info-value">{{ formatOrderNo(orderDetail.orderNo) }}</text>
                <cwg-icon name="copy" :size="14" color="#9ca3af" @click.stop="copyOrderNo" />
              </view>
            </view>

            <view class="info-row">
              <text class="info-label">{{ t('card.Form.f42') }}</text>
              <text class="info-value">{{ orderDetail.type || '-' }}</text>
            </view>

            <view class="info-row">
              <text class="info-label">{{ t('card.Form.f33') }}</text>
              <text class="info-value">{{ orderDetail.createTime }}</text>
            </view>

            <view class="info-row" v-if="orderDetail.completeTime">
              <text class="info-label">{{ t('State.Complete') }}</text>
              <text class="info-value">{{ orderDetail.completeTime || '-' }}</text>
            </view>

            <view v-if="orderDetail.merchant" class="info-row">
              <text class="info-label">{{ t('card.Form.f41') }}</text>
              <text class="info-value">{{ orderDetail.merchant }}</text>
            </view>

            <view v-if="orderDetail.bankCard" class="info-row">
              <text class="info-label">{{ t('card.Form.f24') }}</text>
              <text class="info-value">{{ orderDetail.bankCard }}</text>
            </view>

            <view v-if="orderDetail.remark" class="info-row vertical">
              <text class="info-label">{{ t('card.Form.f27') }}</text>
              <text class="info-value remark-text">{{ orderDetail.remark }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </cwg-page-wrapper>
</template>

<script setup lang="ts">
import { reactive, computed, ref } from 'vue';
import { onLoad, onUnload } from '@dcloudio/uni-app';
import { useI18n } from 'vue-i18n';
import useCardStore from '@/stores/use-card-store';
import useUserStore from '@/stores/use-user-store';
import { ucardApi } from '@/api/ucard';
type OrderStatus = 'success' | 'processing' | 'failed' | 'cancelled';
type ApprovalStatus = 'completed' | 'current' | 'pending';

interface ApprovalStep {
  title: string;
  status: ApprovalStatus;
  operator?: string;
  time?: string;
  remark?: string;
}

interface OrderDetail {
  category?: 'recharge' | 'transaction' | 'deduction';
  orderNo: string;
  type: string;
  amount: number;
  fee: number;
  actualAmount: number;
  currency?: string;
  orderStatus: OrderStatus;
  statusMessage: string;
  createTime: string;
  completeTime?: string;
  merchant?: string;
  bankCard?: string;
  remark?: string;
  approvalSteps: ApprovalStep[];
}

// 订单详情数据（默认占位，进入页面后会用缓存覆盖）
const orderDetail = reactive<OrderDetail>({
  category: 'recharge',
  orderNo: '',
  type: '',
  amount: 0,
  fee: 0,
  actualAmount: 0,
  currency: 'USD',
  orderStatus: 'processing',
  statusMessage: '',
  createTime: '',
  completeTime: '',
  merchant: '',
  bankCard: '',
  remark: '',
  approvalSteps: []
});

const { t, locale } = useI18n();
const cardStore = useCardStore();
const userStore = useUserStore();
const approveDesc = ref('');
const getApproveDesc = () => {
  const d = orderDetail.approveDesc
  if (!d) return
  const c = userStore.reasonsOptions
  const a = c[d || '']
  const b = locale.value == 'cn' || locale.value == 'zhHant' ? a.content : a.enContent
  if (!b) {
    reasonsRefusalList()
  }
  approveDesc.value = b;
}
async function reasonsRefusalList() {
  try {
    const res = await ucardApi.reasonsRefusalList();
    if (res.code === 200) {
      pickFields(res.data);
      getApproveDesc()
    } else {
      uni.$u.toast(res.msg || t("login.msg0"));
    }
  } catch (error) {
    console.log(error, 111);
  }
}
function pickFields(source, fields = ['content', 'enContent']) {
  const result = {}
  Object.entries(source).forEach(([key, value]) => {
    result[key] = fields.reduce((acc, f) => {
      acc[f] = value[f] ?? null
      return acc
    }, {})
  })
  userStore.saveReasonsOptions(result);
}
const formatOrderNo = (orderNo?: string) => {
  if (!orderNo) return '--';
  if (orderNo.length <= 20) return orderNo;
  return orderNo.slice(0, 6) + '...' + orderNo.slice(-4);
}
// 获取订单状态颜色
const getOrderStatusColor = (status: OrderStatus): string => {
  switch (status) {
    case 'success':
      return '#22c55e';
    case 'processing':
      return '#eab308';
    case 'failed':
      return '#ef4444';
    case 'cancelled':
      return '#9ca3af';
    default:
      return '#9ca3af';
  }
};

// 获取订单状态文本
const getOrderStatusText = (status: OrderStatus): string => {
  switch (status) {
    case 'success':
      return t('card.Status.t1'); // 成功
    case 'processing':
      return t('card.Status.t3'); // 处理中
    case 'failed':
      return t('card.Status.t2'); // 失败
    case 'cancelled':
      return t('card.Status.t5'); // 待处理 / 已取消，复用状态文案
    default:
      return t('card.Status.t5');
  }
};

// 复制订单号
const copyOrderNo = () => {
  uni.setClipboardData({
    data: orderDetail.orderNo,
    success: () => {
      uni.showToast({
        title: t('card.Msg.m8') || '复制成功',
        icon: 'success'
      });
    }
  });
};

// 联系客服
const contactService = () => {
  uni.showToast({
    title: '联系客服',
    icon: 'none'
  });
};

// 取消订单
const cancelOrder = () => {
  uni.showModal({
    title: '确认取消',
    content: '确定要取消此订单吗？',
    success: (res) => {
      if (res.confirm) {
        uni.showToast({
          title: '订单已取消',
          icon: 'success'
        });
      }
    }
  });
};

// 申诉订单
const appealOrder = () => {
  uni.showToast({
    title: '提交申诉',
    icon: 'none'
  });
};

// 删除订单
const deleteOrder = () => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除此订单吗？删除后无法恢复',
    success: (res) => {
      if (res.confirm) {
        uni.showToast({
          title: '订单已删除',
          icon: 'success'
        });
      }
    }
  });
};

// 页面加载时，从 store 中读取订单详情
onLoad(() => {
  const cache = cardStore.orderDetail;
  if (cache && typeof cache === 'object') {
    Object.assign(orderDetail, cache);
  } else {
    uni.showToast({
      title: '暂无订单数据',
      icon: 'none'
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 800);
  }
});

// 离开页面时清空订单详情
onUnload(() => {
  cardStore.clearOrderDetail();
});
</script>

<style scoped lang="scss">
@import "@/uni.scss";

.page-wrapper {
  padding: 0;
}

.order-detail-page {
  background-color: #f9fafb;
  padding-bottom: px2rpx(80);
}

/* Header */
.header {
  background: linear-gradient(135deg, #2563eb 0%, #60a5fa 100%);
  padding: px2rpx(12) px2rpx(16);
  padding-top: calc(px2rpx(12) + env(safe-area-inset-top));
}

.header-nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.back-btn {
  width: px2rpx(40);
  height: px2rpx(40);
  display: flex;
  align-items: center;
  justify-content: center;
}

.header-title {
  color: #ffffff;
  font-size: px2rpx(18);
}

.header-action {
  width: px2rpx(40);
}

/* Content */
.content {
  padding: px2rpx(16);
}

/* Status Card */
.status-card {
  background-color: #ffffff;
  border-radius: px2rpx(16);
  padding: px2rpx(32) px2rpx(24);
  margin-bottom: px2rpx(16);
  display: flex;
  flex-direction: column;
  align-items: center;
}

.status-icon-wrapper {
  margin-bottom: px2rpx(16);
}

.status-icon {
  width: px2rpx(80);
  height: px2rpx(80);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.status-icon-success {
  background-color: #f0fdf4;
}

.status-icon-processing {
  background-color: #fefce8;
}

.status-icon-failed {
  background-color: #fef2f2;
}

.status-icon-cancelled {
  background-color: #f9fafb;
}

.status-title {
  font-size: px2rpx(22);
  color: #111827;
  margin-bottom: px2rpx(8);
}

.status-subtitle {
  font-size: px2rpx(14);
  color: #6b7280;
  text-align: center;
}

/* Section Card */
.section-card {
  background-color: #ffffff;
  border-radius: px2rpx(12);
  padding: px2rpx(16);
  margin-bottom: px2rpx(16);
}

.section-header {
  display: flex;
  align-items: center;
  gap: px2rpx(8);
  margin-bottom: px2rpx(16);
}

.section-title {
  font-size: px2rpx(16);
  color: #111827;
}

/* Approval Timeline */
.approval-timeline {
  display: flex;
  flex-direction: column;
}

.timeline-item {
  display: flex;
  gap: px2rpx(12);
}

.timeline-left {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex-shrink: 0;
}

.timeline-dot {
  width: px2rpx(24);
  height: px2rpx(24);
  border-radius: 50%;
  background-color: #f3f4f6;
  border: 2px solid #e5e7eb;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.timeline-dot-active {
  background-color: #22c55e;
  border-color: #22c55e;
}

.timeline-dot-current {
  background-color: #eab308;
  border-color: #eab308;
  animation: pulse 2s infinite;
}

@keyframes pulse {

  0%,
  100% {
    opacity: 1;
  }

  50% {
    opacity: 0.7;
  }
}

.timeline-line {
  width: px2rpx(2);
  flex: 1;
  background-color: #e5e7eb;
  margin: px2rpx(4) 0;
}

.timeline-right {
  flex: 1;
  padding-bottom: px2rpx(24);
}

.timeline-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: px2rpx(6);
}

.timeline-title {
  font-size: px2rpx(15);
  color: #111827;
}

.timeline-status {
  display: flex;
  align-items: center;
  gap: px2rpx(4);
  padding: px2rpx(2) px2rpx(8);
  border-radius: px2rpx(12);
}

.timeline-status.completed {
  background-color: #f0fdf4;
}

.timeline-status.current {
  background-color: #fefce8;
}

.timeline-status.pending {
  background-color: #f9fafb;
}

.timeline-status-text {
  font-size: px2rpx(12);
}

.timeline-status.completed .timeline-status-text {
  color: #22c55e;
}

.timeline-status.current .timeline-status-text {
  color: #eab308;
}

.timeline-status.pending .timeline-status-text {
  color: #9ca3af;
}

.timeline-operator {
  font-size: px2rpx(13);
  color: #6b7280;
  display: block;
  margin-bottom: px2rpx(4);
}

.timeline-time {
  font-size: px2rpx(12);
  color: #9ca3af;
  display: block;
  margin-bottom: px2rpx(4);
}

.timeline-remark {
  font-size: px2rpx(13);
  color: #6b7280;
  display: block;
  margin-top: px2rpx(6);
  padding: px2rpx(8);
  background-color: #f9fafb;
  border-radius: px2rpx(6);
}

/* Info List */
.info-list {
  display: flex;
  flex-direction: column;
  gap: px2rpx(12);
}

.info-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: px2rpx(12);
}

.info-row.vertical {
  flex-direction: column;
  align-items: flex-start;
}

.info-label {
  font-size: px2rpx(14);
  color: #6b7280;
  flex-shrink: 0;
}

.info-value {
  font-size: px2rpx(14);
  color: #111827;
  text-align: right;
  word-break: break-all;
}

.info-value-wrapper {
  display: flex;
  align-items: center;
  gap: px2rpx(8);
  flex: 1;
  justify-content: flex-end;
}

.amount-highlight {
  font-size: px2rpx(20);
  color: #2563eb;
}

.total-label {
  font-size: px2rpx(15);
  color: #111827;
}

.total-value {
  font-size: px2rpx(18);
  color: #ef4444;
}

.remark-text {
  text-align: left;
  color: #6b7280;
  line-height: 1.6;
}

.divider {
  height: px2rpx(1);
  background-color: #f3f4f6;
  margin: px2rpx(4) 0;
}

/* Service Card */
.service-card {
  background-color: #ffffff;
  border-radius: px2rpx(12);
  padding: px2rpx(16);
  display: flex;
  align-items: center;
  gap: px2rpx(12);
  margin-bottom: px2rpx(16);
}

.service-text {
  flex: 1;
  font-size: px2rpx(15);
  color: #111827;
}

/* Bottom Actions */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #ffffff;
  border-top: 1px solid #e5e7eb;
  padding: px2rpx(12) px2rpx(16);
  padding-bottom: calc(px2rpx(12) + env(safe-area-inset-bottom));
  display: flex;
  gap: px2rpx(12);
}

.action-btn {
  flex: 1;
  height: px2rpx(44);
  border-radius: px2rpx(8);
  display: flex;
  align-items: center;
  justify-content: center;
}

.cancel-btn {
  background-color: #f3f4f6;
}

.cancel-btn .btn-text {
  color: #6b7280;
}

.appeal-btn {
  background-color: #2563eb;
}

.appeal-btn .btn-text {
  color: #ffffff;
}

.delete-btn {
  background-color: #f3f4f6;
}

.delete-btn .btn-text {
  color: #ef4444;
}

.btn-text {
  font-size: px2rpx(15);
}

.currency {
  font-size: px2rpx(12);
}
</style>
