<template>
  <view class="page-seller-order-detail">
    <view v-if="order.id" class="detail-content">
      <!-- 状态栏 -->
      <view :class="['status-bar', `status-${order.status}`]">
        <text class="status-text">{{ statusLabels[order.status] }}</text>
      </view>

      <!-- 房源信息 -->
      <view class="section">
        <view class="room-card flex-row">
          <image class="room-thumb" :src="order.room?.coverImage || '/static/default-room.png'" mode="aspectFill" />
          <view class="room-info">
            <text class="room-name text-ellipsis">{{ order.room?.name }}</text>
            <text class="merchant-name">{{ order.merchant?.shopName }}</text>
          </view>
        </view>
      </view>

      <!-- 入住人信息 -->
      <view class="section">
        <view class="section-title">入住人信息</view>
        <view class="info-row flex-between">
          <text class="info-label">联系人</text>
          <text class="info-value">{{ order.contactName }}</text>
        </view>
        <view class="info-row flex-between">
          <text class="info-label">联系电话</text>
          <text class="info-value">{{ order.contactPhone }}</text>
        </view>
        <view class="info-row flex-between" v-if="order.contactIdCard">
          <text class="info-label">身份证号</text>
          <text class="info-value">{{ order.contactIdCard }}</text>
        </view>
        <view class="info-row flex-between">
          <text class="info-label">入住人数</text>
          <text class="info-value">{{ order.guestCount || 1 }}人</text>
        </view>
      </view>

      <!-- 入住信息 -->
      <view class="section">
        <view class="section-title">入住信息</view>
        <view class="info-row flex-between">
          <text class="info-label">入住日期</text>
          <text class="info-value">{{ order.checkInDate }}</text>
        </view>
        <view class="info-row flex-between">
          <text class="info-label">离店日期</text>
          <text class="info-value">{{ order.checkOutDate }}</text>
        </view>
        <view class="info-row flex-between">
          <text class="info-label">入住晚数</text>
          <text class="info-value">{{ order.nights }}晚</text>
        </view>
        <view class="info-row flex-between">
          <text class="info-label">房间套数</text>
          <text class="info-value">{{ order.roomCount || 1 }}套</text>
        </view>
      </view>

      <!-- 费用明细 -->
      <view class="section">
        <view class="section-title">费用明细</view>
        <view class="info-row flex-between">
          <text class="info-label">房费</text>
          <text class="info-value">¥{{ order.roomAmount }}</text>
        </view>
        <view v-if="order.couponDiscount > 0" class="info-row flex-between">
          <text class="info-label">优惠券</text>
          <text class="info-value discount">-¥{{ order.couponDiscount }}</text>
        </view>
        <view class="info-row flex-between">
          <text class="info-label">软件服务费</text>
          <text class="info-value service-fee">-¥{{ order.serviceFee || 0 }}</text>
        </view>
        <view class="info-row flex-between">
          <text class="info-label">预计收入</text>
          <text class="info-value merchant-income">¥{{ order.merchantIncome || order.payAmount }}</text>
        </view>
        <view class="info-row flex-between total-row">
          <text class="info-label">实付金额</text>
          <text class="total-price">¥{{ order.payAmount }}</text>
        </view>
      </view>

      <!-- 订单信息 -->
      <view class="section">
        <view class="section-title">订单信息</view>
        <view class="info-row flex-between">
          <text class="info-label">订单号</text>
          <text class="info-value">{{ order.orderNo }}</text>
        </view>
        <view class="info-row flex-between">
          <text class="info-label">下单时间</text>
          <text class="info-value">{{ order.createdAt }}</text>
        </view>
        <view class="info-row flex-between" v-if="order.paymentMethod">
          <text class="info-label">支付方式</text>
          <text class="info-value">{{ paymentMethodLabels[order.paymentMethod] }}</text>
        </view>
        <view class="info-row flex-between" v-if="order.paidAt">
          <text class="info-label">支付时间</text>
          <text class="info-value">{{ order.paidAt }}</text>
        </view>
        <view class="info-row flex-between" v-if="order.confirmedAt">
          <text class="info-label">确认时间</text>
          <text class="info-value">{{ order.confirmedAt }}</text>
        </view>
        <view class="info-row flex-between" v-if="order.checkinAt">
          <text class="info-label">入住时间</text>
          <text class="info-value">{{ order.checkinAt }}</text>
        </view>
        <view class="info-row flex-between" v-if="order.cancelReason">
          <text class="info-label">取消原因</text>
          <text class="info-value">{{ order.cancelReason }}</text>
        </view>
        <view class="info-row flex-between" v-if="order.remark">
          <text class="info-label">备注</text>
          <text class="info-value">{{ order.remark }}</text>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="actions" v-if="order.status === 'pending_confirm'">
        <button class="btn-reject" @tap="handleReject">拒绝订单</button>
        <button class="btn-confirm" @tap="handleConfirm">确认接单</button>
      </view>
      <view class="actions" v-if="order.status === 'pending_checkin'">
        <button class="btn-checkin" @tap="handleCheckin">办理入住</button>
      </view>
      <view class="actions" v-if="order.status === 'checked_in' && canCheckout">
        <button class="btn-checkout" @tap="handleCheckout">确认离店</button>
      </view>
    </view>

    <view v-else class="loading">加载中...</view>

    <!-- 拒绝原因弹窗 -->
    <view v-if="showRejectModal" class="modal-mask" @tap="closeRejectModal">
      <view class="modal-panel" @tap.stop>
        <view class="modal-header">
          <text class="modal-title">拒绝订单</text>
          <text class="modal-close" @tap="closeRejectModal">×</text>
        </view>
        <view class="modal-body">
          <textarea class="reject-input" v-model="rejectReason" placeholder="请输入拒绝原因" />
        </view>
        <view class="modal-footer">
          <button class="modal-btn cancel" @tap="closeRejectModal">取消</button>
          <button class="modal-btn confirm" @tap="submitReject">确认拒绝</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { getSellerOrderDetail, confirmOrder, rejectOrder, checkinOrder, checkoutOrder } from '@/api/seller/order';

const statusLabels: Record<string, string> = {
  pending_pay: '待支付',
  pending_confirm: '待确认',
  pending_checkin: '待入住',
  checked_in: '已入住',
  completed: '已完成',
  cancelled: '已取消',
  refunding: '退款中',
  refunded: '已退款',
};

const paymentMethodLabels: Record<string, string> = {
  wechat: '微信支付',
  alipay: '支付宝',
  balance: '余额支付',
};

const order = ref<any>({});
const orderNo = ref('');
const showRejectModal = ref(false);
const rejectReason = ref('');

// 判断是否可以确认离店（已到离店日期）
const canCheckout = computed(() => {
  if (!order.value?.checkOutDate) return false;
  const today = new Date().toISOString().split('T')[0];
  return order.value.checkOutDate <= today;
});

onMounted(() => {
  const pages = getCurrentPages();
  const page = pages[pages.length - 1] as any;
  orderNo.value = page.options?.orderNo || page.$page?.options?.orderNo;
  if (orderNo.value) fetchDetail();
});

async function fetchDetail() {
  try {
    const res = await getSellerOrderDetail(orderNo.value);
    order.value = res.data;
  } catch (e) {
    console.error(e);
  }
}

async function handleConfirm() {
  uni.showModal({
    title: '提示',
    content: '确认接单？',
    success: async (res) => {
      if (res.confirm) {
        uni.showLoading({ title: '处理中...' });
        try {
          await confirmOrder(orderNo.value);
          uni.hideLoading();
          uni.showToast({ title: '已确认', icon: 'success' });
          fetchDetail();
        } catch (e: any) {
          uni.hideLoading();
          uni.showToast({ title: e.message || '操作失败', icon: 'none' });
        }
      }
    },
  });
}

function handleReject() {
  rejectReason.value = '';
  showRejectModal.value = true;
}

function closeRejectModal() {
  showRejectModal.value = false;
}

async function handleCheckin() {
  uni.showModal({
    title: '提示',
    content: '确认办理入住？',
    success: async (res) => {
      if (res.confirm) {
        uni.showLoading({ title: '处理中...' });
        try {
          await checkinOrder(orderNo.value);
          uni.hideLoading();
          uni.showToast({ title: '已入住', icon: 'success' });
          fetchDetail();
        } catch (e: any) {
          uni.hideLoading();
          uni.showToast({ title: e.message || '操作失败', icon: 'none' });
        }
      }
    },
  });
}

async function submitReject() {
  if (!rejectReason.value.trim()) {
    uni.showToast({ title: '请输入拒绝原因', icon: 'none' });
    return;
  }
  uni.showLoading({ title: '处理中...' });
  try {
    await rejectOrder(orderNo.value, rejectReason.value);
    uni.hideLoading();
    uni.showToast({ title: '已拒绝', icon: 'success' });
    showRejectModal.value = false;
    fetchDetail();
  } catch (e: any) {
    uni.hideLoading();
    uni.showToast({ title: e.message || '操作失败', icon: 'none' });
  }
}

async function handleCheckout() {
  uni.showModal({
    title: '提示',
    content: '确认客人已离店？订单将标记为已完成',
    success: async (res) => {
      if (res.confirm) {
        uni.showLoading({ title: '处理中...' });
        try {
          await checkoutOrder(orderNo.value);
          uni.hideLoading();
          uni.showToast({ title: '已确认离店', icon: 'success' });
          fetchDetail();
        } catch (e: any) {
          uni.hideLoading();
          uni.showToast({ title: e.message || '操作失败', icon: 'none' });
        }
      }
    },
  });
}
</script>

<style lang="scss" scoped>
@import '@/static/styles/common.scss';

.page-seller-order-detail {
  min-height: 100vh;
  background: $bg-page;
  padding-bottom: 140rpx;
}

.status-bar {
  padding: $spacing-2xl $spacing-xl;
  color: #fff;
  font-size: $font-2xl;
  font-weight: $font-bold;
  border-radius: $radius-lg;
  margin: $spacing-xl;
}

.status-pending_pay { background: $warning-color; }
.status-pending_confirm { background: $info-color; }
.status-pending_checkin { background: $success-color; }
.status-checked_in { background: $primary-color; }
.status-completed { background: $success-color; }
.status-cancelled { background: $text-tertiary; }
.status-refunding { background: $error-color; }
.status-refunded { background: #722ed1; }

.section {
  background: $bg-card;
  margin: $spacing-xl;
  border-radius: $radius-lg;
  padding: $spacing-xl;
  border: 1rpx solid $border-light;
}

.section-title {
  font-size: $font-md;
  font-weight: $font-semibold;
  color: $text-primary;
  margin-bottom: $spacing-lg;
}

.room-card {
  padding: $spacing-xs 0;
}

.room-thumb {
  width: 160rpx;
  height: 120rpx;
  border-radius: $radius-base;
  flex-shrink: 0;
  border: 1rpx solid $border-light;
}

.room-info {
  flex: 1;
  margin-left: $spacing-lg;
}

.room-name {
  font-size: $font-md;
  font-weight: $font-semibold;
  color: $text-primary;
}

.merchant-name {
  font-size: $font-xs;
  color: $text-secondary;
  margin-top: $spacing-xs;
}

.info-row {
  padding: $spacing-md 0;
  border-bottom: 1rpx solid $border-light;

  &:last-child { border-bottom: none; }
}

.info-label {
  font-size: $font-base;
  color: $text-secondary;
}

.info-value {
  font-size: $font-base;
  color: $text-primary;
}

.discount { color: $success-color; }

.service-fee { color: $warning-color; }

.merchant-income { color: $info-color; font-weight: $font-semibold; }

.total-row {
  padding-top: $spacing-lg;
  border-top: 2rpx solid $border-base;
}

.total-price {
  font-size: $font-2xl;
  font-weight: $font-bold;
  color: $primary-color;
}

.loading {
  text-align: center;
  padding: 200rpx 0;
  color: $text-secondary;
}

.actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  gap: $spacing-xl;
  padding: $spacing-xl;
  background: $bg-card;
  border-top: 1rpx solid $border-light;
}

.btn-reject {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  border-radius: $radius-base;
  font-size: $font-md;
  background: $bg-card;
  color: $error-color;
  border: 2rpx solid $error-color;
}

.btn-confirm {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  border-radius: $radius-base;
  font-size: $font-md;
  background: $primary-color;
  color: #fff;
  border: none;

  &:active {
    background: $primary-dark;
  }
}

.btn-checkin {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  border-radius: $radius-base;
  font-size: $font-md;
  background: $success-color;
  color: #fff;
  border: none;

  &:active {
    background: $success-dark;
  }
}

.btn-checkout {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  border-radius: $radius-base;
  font-size: $font-md;
  background: $info-color;
  color: #fff;
  border: none;

  &:active {
    background: $info-dark;
  }
}

.btn-approve-refund {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  border-radius: $radius-base;
  font-size: $font-md;
  background: $success-color;
  color: #fff;
  border: none;

  &:active {
    background: $success-dark;
  }
}

.btn-reject-refund {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  border-radius: $radius-base;
  font-size: $font-md;
  background: $bg-card;
  color: $error-color;
  border: 2rpx solid $error-color;
}

/* 拒绝弹窗 */
.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-panel {
  width: 80%;
  background: $bg-card;
  border-radius: $radius-lg;
  padding: $spacing-2xl;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: $spacing-xl;
}

.modal-title {
  font-size: $font-lg;
  font-weight: $font-semibold;
  color: $text-primary;
}

.modal-close {
  font-size: $font-2xl;
  color: $text-secondary;
}

.modal-body {
  margin-bottom: $spacing-xl;
}

.reject-input {
  width: 100%;
  height: 160rpx;
  background: $bg-page;
  border-radius: $radius-base;
  padding: $spacing-md;
  font-size: $font-base;
  border: 2rpx solid $border-light;

  &:focus {
    border-color: $primary-color;
  }
}

.modal-footer {
  display: flex;
  gap: $spacing-xl;
}

.modal-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  font-size: $font-md;
  border-radius: $radius-base;
  border: none;

  &.cancel {
    background: $bg-page;
    color: $text-secondary;
  }

  &.confirm {
    background: $error-color;
    color: #fff;

    &:active {
      background: $error-dark;
    }
  }
}
</style>