<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { showDialog, showToast } from 'vant'

import MobilePaymentCashierPopup from '@/features/orders/components/MobilePaymentCashierPopup.vue'
import MobilePayWaySelectPopup from '@/features/orders/components/MobilePayWaySelectPopup.vue'
import { useOrderActions, CONFIRMABLE_ACTIONS } from '@/features/orders/composables/useOrderActions'
import { useMobilePaymentCashier } from '@/features/orders/composables/useMobilePaymentCashier'
import { useMobilePayWaySelect } from '@/features/orders/composables/useMobilePayWaySelect'
import {
  amountYuan,
  money,
  readAssetSummary as readOrderAssetSummary,
  readSnapshot as readOrderSnapshot,
} from '@/features/orders/composables/useOrderSnapshot'
import {
  OrderCheckoutSummary,
  OrderHandoffTimeline,
  OrderResourceUsageEditor,
} from '@/features/orders'
import { handoffStatusLabel, orderStatusLabel } from '@/shared/utils/statusLabels'
import { formatDateTime } from '@/shared/utils/time'

// 移动端支付收银台（基于通用 useOrderPaymentCashier 的薄封装：注入 vant toast + App 浏览器跳转）。
const cashier = useMobilePaymentCashier()
const router = useRouter()

// 支付方式选择底部弹层（与 PC 端一致的渠道卡片体验）。
const payWaySelect = useMobilePayWaySelect()
const selectPayWay = payWaySelect.select
const {
  paymentPopupVisible,
  activePayment,
  payURL,
  paymentQRCodeURL,
  qrGenerating,
  checkingPayment,
  refreshPaymentStatus,
} = cashier

const {
  loading,
  cancelling,
  startingPayment: paying,
  handoffing,
  confirming,
  returning,
  completing,
  countering,
  acceptingCheckout,
  rejectingCheckout,
  disputing,
  cancellingDispute,
  openingChat,
  order,
  handoffRecords,
  handoffContent,
  checkoutForm,
  resourceUsage,
  counterForm,
  rejectReason,
  disputeType,
  disputeDescription,
  disputeEvidenceText,
  checkoutResources,
  resourceChargeAmount,
  snapshotHafCoinM,
  remainingHafCoinM,
  resourceLineAmount,
  isOwner,
  isRenter,
  listingCode,
  orderAmountLabel,
  orderRentDisplayAmount,
  ownerIncomeDisplayAmount,
  ownerIncomeLabel,
  canOpenDispute,
  canCancelDispute,
  isCheckoutDisputeStage,
  handleCancel,
  handlePay,
  handleSubmitHandoff,
  handleConfirmReceive,
  handleSubmitCheckout,
  handleConfirmCheckout,
  handleCounterCheckout,
  handleAcceptCheckout,
  handleRejectCheckout,
  handleCreateDispute,
  handleCancelDispute,
  handleEvidenceUpload,
  handleCounterEvidenceUpload,
  openOrderChat,
  orderEstimatedEndAt,
  orderRentedAt,
} = useOrderActions({
  notifySuccess: message => showToast({ message, icon: 'passed' }),
  notifyError: message => showToast({ message, icon: 'cross' }),
  notifyWarning: message => showToast({ message, icon: 'warning-o' }),
  confirm: async ({ title, message }) => {
    try {
      await showDialog({ title, message, showCancelButton: true })
      return true
    } catch {
      return false
    }
  },
  actionsNeedingConfirm: CONFIRMABLE_ACTIONS,
  selectPayWay,
  ordersPath: '/m/orders',
  chatPathPrefix: '/m/chats/',
  startCashier: (payment, onPaid) => cashier.openMobilePaymentCashier(payment, onPaid),
  onCounterCheckoutSuccess: () => (showCounterPopup.value = false),
  onRejectCheckoutSuccess: () => (showRejectPopup.value = false),
  onCreateDisputeSuccess: () => (showDisputePopup.value = false),
})

// Mobile 独有 UI 状态：折叠面板、各类 popup 显隐。
const activeNames = ref<string[]>([])
const showDisputePopup = ref(false)
const showCounterPopup = ref(false)
const showRejectPopup = ref(false)

// 账号快照展示（PC 不用，保留在本视图）。
function readSnapshot() {
  return readOrderSnapshot(order.value) as Record<string, any> | null
}
function readAssetSummary() {
  return readOrderAssetSummary(order.value) as Record<string, any> | null
}

// 状态颜色映射（vant 标签主题）。
function getStatusTagType(status: string) {
  if (['completed', 'received'].includes(status)) return 'success'
  if (['pending_payment', 'pending_confirm'].includes(status)) return 'warning'
  if (['renting'].includes(status)) return 'primary'
  if (['cancelled', 'closed'].includes(status)) return 'danger'
  return 'danger'
}

async function copyListingCode() {
  if (!order.value) return
  try {
    await navigator.clipboard.writeText(listingCode.value)
    showToast({ message: '商品编号已复制', icon: 'passed' })
  } catch {
    showToast({ message: '复制失败', icon: 'cross' })
  }
}
</script>

<template>
  <main class="mobile-order-detail-view">
    <header class="page-header">
      <button class="back-btn" @click="router.back()">
        <van-icon name="arrow-left" :size="20" />
      </button>
      <h1>订单详情</h1>
      <button
        v-if="order"
        class="chat-btn"
        type="button"
        :disabled="openingChat"
        @click="openOrderChat"
      >
        <van-icon name="chat-o" :size="19" />
      </button>
      <span v-else class="header-spacer"></span>
    </header>

    <van-loading v-if="loading" class="center-loading" size="24px" vertical>
      加载中...
    </van-loading>

    <template v-else-if="order">
      <!-- 状态及核心信息卡片 -->
      <section class="card-section info-card">
        <div class="card-header-row">
          <span class="order-no">{{ order.order_no }}</span>
          <van-tag :type="getStatusTagType(order.status)" size="medium">
            {{ orderStatusLabel(order.status) }}
          </van-tag>
        </div>
        <button class="listing-code-chip" type="button" @click="copyListingCode">
          商品编号 {{ listingCode }}
        </button>
        <h2 class="order-title">{{ order.title }}</h2>
        <div class="order-meta-grid">
          <div class="meta-item">
            <span class="meta-label">{{ orderAmountLabel }}</span>
            <strong class="meta-value accent">¥{{ money(orderRentDisplayAmount) }}</strong>
          </div>
          <div v-if="isOwner && ownerIncomeDisplayAmount !== null" class="meta-item">
            <span class="meta-label">{{ ownerIncomeLabel }}</span>
            <strong class="meta-value income">¥{{ money(ownerIncomeDisplayAmount) }}</strong>
          </div>
          <div class="meta-item">
            <span class="meta-label">押金</span>
            <strong class="meta-value">¥{{ money(amountYuan(order.deposit_amount_cent)) }}</strong>
            <span v-if="amountYuan(order.deposit_waived_amount_cent) > 0" class="meta-note"
              >已免押 ¥{{ money(amountYuan(order.deposit_waived_amount_cent)) }}</span
            >
          </div>
          <div class="meta-item">
            <span class="meta-label">交接状态</span>
            <strong class="meta-value">{{ handoffStatusLabel(order.handoff_status) }}</strong>
          </div>
        </div>
      </section>

      <!-- 时间节点卡片 -->
      <section class="card-section">
        <van-cell-group inset :border="false">
          <van-cell title="开始时间" :value="formatDateTime(orderRentedAt(), '未开始')" />
          <van-cell title="预计截止" :value="formatDateTime(orderEstimatedEndAt(), '未设置')" />
        </van-cell-group>
      </section>

      <!-- Renter Action: Pay / Cancel -->
      <section v-if="order.status === 'pending_payment'" class="card-section action-card">
        <p class="action-hint">订单已创建，请确认并在有效期内完成支付。过期订单将自动关闭。</p>
        <div class="action-buttons">
          <van-button
            v-if="isRenter"
            type="primary"
            block
            round
            :loading="paying"
            loading-text="支付中..."
            @click="handlePay"
          >
            支付订单
          </van-button>
          <van-button
            type="danger"
            block
            plain
            round
            :loading="cancelling"
            loading-text="取消中..."
            @click="handleCancel"
          >
            取消订单并释放账号
          </van-button>
        </div>
      </section>

      <!-- Handoff Panel: Owner Handoff Info Submission -->
      <section
        v-if="
          isOwner && order.status === 'pending_handoff' && order.handoff_status === 'pending_owner'
        "
        class="card-section action-card"
      >
        <h3 class="section-title">提交交接说明</h3>
        <p class="action-hint">提交登录所需的账号密码、密保注意事项或扫码交接联系方式。</p>
        <van-field
          v-model="handoffContent"
          rows="3"
          autosize
          label="交接说明"
          type="textarea"
          placeholder="请在这里填写登录方式、注意事项或扫码联系渠道"
          class="action-field"
        />
        <van-button
          type="primary"
          block
          round
          :loading="handoffing"
          loading-text="正在提交..."
          @click="handleSubmitHandoff"
        >
          提交交接说明
        </van-button>
      </section>

      <!-- Handoff Panel: Renter Confirm Handoff Received -->
      <section
        v-if="
          isRenter &&
          order.status === 'pending_handoff' &&
          order.handoff_status === 'pending_renter_confirm'
        "
        class="card-section action-card"
      >
        <h3 class="section-title">确认收到账号</h3>
        <p class="action-hint">
          请按照号主提交的交接说明进行登录测试，确认无误后点击下方按钮确认收号，租期将正式开始计算。
        </p>
        <div class="action-buttons">
          <van-button
            type="primary"
            block
            round
            :loading="confirming"
            loading-text="确认中..."
            @click="handleConfirmReceive"
          >
            确认收到账号
          </van-button>
          <van-button
            type="danger"
            block
            plain
            round
            :loading="cancelling"
            loading-text="取消中..."
            @click="handleCancel"
          >
            未收到/无法登录，取消订单
          </van-button>
        </div>
      </section>

      <!-- Handoff Records list -->
      <OrderHandoffTimeline
        variant="mobile"
        :records="handoffRecords"
        :listing-code="listingCode"
      />

      <!-- Renter Action: Return Account & Initiate Checkout -->
      <OrderResourceUsageEditor
        v-if="isRenter && ['renting', 'overdue'].includes(order.status)"
        v-model:checkout-form="checkoutForm"
        v-model:resource-usage="resourceUsage"
        variant="mobile"
        :resources="checkoutResources"
        :resource-charge-amount="resourceChargeAmount"
        :snapshot-haf-coin-m="snapshotHafCoinM"
        :remaining-haf-coin-m="remainingHafCoinM"
        :returning="returning"
        :resource-line-amount="resourceLineAmount"
        @submit="handleSubmitCheckout"
      />

      <!-- Checkout Details Display -->
      <OrderCheckoutSummary
        v-if="
          order.checkout &&
          ['pending_checkout_confirm', 'pending_checkout_accept'].includes(order.status)
        "
        variant="mobile"
        :order="order"
        :is-owner="isOwner"
        :is-renter="isRenter"
      />

      <!-- Owner Action: Confirm Checkout / Make Counter Adjustment Proposal -->
      <section
        v-if="isOwner && order.status === 'pending_checkout_confirm'"
        class="card-section action-card"
      >
        <h3 class="section-title">结账处理</h3>
        <p class="action-hint">
          租客已发起结账并归还账号。确认无误后点击“确认结账”；若扣款不足，可以提出“修改结账”反向提案。
        </p>
        <div class="action-buttons">
          <van-button
            type="primary"
            block
            round
            :loading="completing"
            loading-text="处理中..."
            @click="handleConfirmCheckout"
          >
            同意并确认结账
          </van-button>
          <van-button type="warning" block plain round @click="showCounterPopup = true">
            修改扣款金额
          </van-button>
        </div>
      </section>

      <!-- Renter Action: Accept Counter Checkout Proposal / Refuse and Dispute -->
      <section
        v-if="isRenter && order.status === 'pending_checkout_accept'"
        class="card-section action-card"
      >
        <h3 class="section-title">号主结账修正审批</h3>
        <p class="action-hint">
          号主修改了您的结账申请并对押金进行了扣除。请审查，同意将完成结算，不同意将进入仲裁申诉。
        </p>
        <div class="action-buttons">
          <van-button
            type="primary"
            block
            round
            :loading="acceptingCheckout"
            loading-text="同意中..."
            @click="handleAcceptCheckout"
          >
            同意修正并结账
          </van-button>
          <van-button type="danger" block plain round @click="showRejectPopup = true">
            拒绝修正并提起申诉
          </van-button>
        </div>
      </section>

      <!-- Universal Action: File a Dispute -->
      <section v-if="canOpenDispute" class="card-section action-card">
        <van-button type="warning" block plain round @click="showDisputePopup = true">
          {{ isCheckoutDisputeStage ? '对结账发起申诉争议' : '发起订单申诉争议' }}
        </van-button>
      </section>

      <section v-if="canCancelDispute" class="card-section action-card">
        <van-button
          type="warning"
          block
          plain
          round
          :loading="cancellingDispute"
          loading-text="取消中..."
          @click="handleCancelDispute"
        >
          {{ order.status === 'checkout_disputing' ? '取消结账争议' : '取消申诉' }}
        </van-button>
      </section>

      <!-- Snapshot Account Details Accordion -->
      <section class="card-section">
        <van-collapse v-model="activeNames">
          <van-collapse-item title="查看订单账号快照信息" name="snapshot">
            <template v-if="readSnapshot()">
              <van-cell-group :border="false">
                <van-cell title="区服" :value="order.server_region" />
                <van-cell title="登录平台" :value="order.login_platform" />
                <van-cell title="烽火等级" :value="readAssetSummary()?.fire_level || '--'" />
                <van-cell title="绝密KD" :value="readAssetSummary()?.secret_kd || '--'" />
                <van-cell
                  title="常用登录地区"
                  :value="readAssetSummary()?.common_regions?.join('、') || '--'"
                />
                <van-cell title="封禁记录" :value="readAssetSummary()?.ban_record || '无'" />
                <van-cell title="体力等级" :value="readAssetSummary()?.stamina_level || '--'" />
                <van-cell title="负重等级" :value="readAssetSummary()?.load_level || '--'" />
                <van-cell title="账号备注" :label="readSnapshot()?.description || '无'" />
              </van-cell-group>
            </template>
            <template v-else>
              <div class="no-snapshot-hint">暂无快照数据</div>
            </template>
          </van-collapse-item>
        </van-collapse>
      </section>
    </template>

    <div v-else class="empty-wrap">
      <van-empty image="search" description="订单不存在或已被删除" />
    </div>

    <MobilePayWaySelectPopup
      v-model:show="payWaySelect.visible.value"
      @choose="payWaySelect.choose"
      @closed="payWaySelect.handleClosed"
    />

    <MobilePaymentCashierPopup
      v-model:show="paymentPopupVisible"
      :payment="activePayment"
      :pay-url="payURL"
      :qr-code-url="paymentQRCodeURL"
      :qr-generating="qrGenerating"
      :checking="checkingPayment"
      @refresh="refreshPaymentStatus(false)"
    />

    <!-- POPUP: Owner Counter Checkout Adjustments -->
    <van-popup v-model:show="showCounterPopup" position="bottom" round class="mobile-popup-form">
      <header class="popup-header">
        <h3>修改结账扣款金额</h3>
        <button class="popup-close" @click="showCounterPopup = false">✕</button>
      </header>
      <div class="popup-body">
        <p class="form-hint-info">
          在此调整实际使用的租金项目和押金赔付金额，提案将交由租客二次确认。
        </p>
        <van-cell-group :border="false">
          <van-field label="额外消耗品已用">
            <template #input>
              <input
                v-model.number="counterForm.consumableAmountYuan"
                type="number"
                class="custom-inline-input"
              />
            </template>
          </van-field>
          <van-field label="消耗哈夫币 M">
            <template #input>
              <input
                v-model.number="counterForm.coin_consumed_m"
                type="number"
                class="custom-inline-input"
              />
            </template>
          </van-field>
          <van-field label="其他押金扣款">
            <template #input>
              <input
                v-model.number="counterForm.otherAmountYuan"
                type="number"
                class="custom-inline-input"
              />
            </template>
          </van-field>
          <van-field label="押金赔付扣除" required>
            <template #input>
              <input
                v-model.number="counterForm.depositDeductAmountYuan"
                type="number"
                class="custom-inline-input"
              />
            </template>
          </van-field>
        </van-cell-group>
        <van-field
          v-model="counterForm.reason"
          rows="2"
          autosize
          label="修改原因"
          type="textarea"
          placeholder="请说明调整扣款的原因，说服租客确认"
          class="popup-field"
        />
        <van-field
          v-model="counterForm.evidenceText"
          rows="2"
          autosize
          label="扣款证据"
          type="textarea"
          placeholder="证据链接（每行一个）"
          class="popup-field"
        />
        <div class="evidence-upload-row">
          <span>上传新证据截图：</span>
          <input type="file" accept="image/*" @change="handleCounterEvidenceUpload" />
        </div>
        <van-button
          type="warning"
          block
          round
          :loading="countering"
          loading-text="提交中..."
          @click="handleCounterCheckout"
          class="popup-submit"
        >
          提交提案给租客确认
        </van-button>
      </div>
    </van-popup>

    <!-- POPUP: Renter Reject Counter Proposal Reason -->
    <van-popup v-model:show="showRejectPopup" position="bottom" round class="mobile-popup-form">
      <header class="popup-header">
        <h3>拒绝修正扣款说明</h3>
        <button class="popup-close" @click="showRejectPopup = false">✕</button>
      </header>
      <div class="popup-body">
        <p class="form-hint-info">
          拒绝号主的修正提案后，订单将立即自动发起争议，由客服介入根据证据判定。
        </p>
        <van-field
          v-model="rejectReason"
          rows="3"
          autosize
          label="拒绝原因"
          type="textarea"
          placeholder="请详细叙述拒绝号主扣款的理由，这些信息将被客服作为判定依据"
          class="popup-field"
        />
        <van-button
          type="danger"
          block
          round
          :loading="rejectingCheckout"
          loading-text="发起争议中..."
          @click="handleRejectCheckout"
          class="popup-submit"
        >
          提交原因并提起争议
        </van-button>
      </div>
    </van-popup>

    <!-- POPUP: Create Generic Order Dispute -->
    <van-popup v-model:show="showDisputePopup" position="bottom" round class="mobile-popup-form">
      <header class="popup-header">
        <h3>发起申诉争议</h3>
        <button class="popup-close" @click="showDisputePopup = false">✕</button>
      </header>
      <div class="popup-body">
        <van-field v-if="!isCheckoutDisputeStage" label="申诉类型" class="popup-field">
          <template #input>
            <select v-model="disputeType" class="custom-select">
              <option value="cannot_login">无法登录</option>
              <option value="false_description">虚假描述</option>
              <option value="account_banned">账号被封</option>
              <option value="asset_loss">资产损失</option>
              <option value="haf_coin_dispute">哈夫币争议</option>
              <option value="handoff_timeout">超时未交接</option>
              <option value="return_timeout">超时未归还</option>
            </select>
          </template>
        </van-field>
        <van-field
          v-model="disputeDescription"
          rows="3"
          autosize
          label="经过说明"
          type="textarea"
          placeholder="请在此描述您的诉求、事件经过、时间点等详细情况"
          class="popup-field"
        />
        <van-field
          v-model="disputeEvidenceText"
          rows="2"
          autosize
          label="证据列表"
          type="textarea"
          placeholder="证据链接（每行一个）"
          class="popup-field"
        />
        <div class="evidence-upload-row">
          <span>上传证据截图：</span>
          <input type="file" accept="image/*" @change="handleEvidenceUpload" />
        </div>
        <van-button
          type="warning"
          block
          round
          :loading="disputing"
          loading-text="正在发起申诉..."
          @click="handleCreateDispute"
          class="popup-submit"
        >
          提交申诉客服仲裁
        </van-button>
      </div>
    </van-popup>
  </main>
</template>

<style scoped>
.mobile-order-detail-view {
  min-height: 100dvh;
  background: #f5f7fa;
  padding-bottom: 40px;
}

/* ========== Header ========== */
.page-header {
  position: sticky;
  top: 0;
  z-index: 10;
  display: flex;
  align-items: center;
  height: 48px;
  padding: 0 12px;
  background: #fff;
  border-bottom: 1px solid #eee;
}

.page-header h1 {
  flex: 1;
  margin: 0;
  font-size: 17px;
  font-weight: 700;
  text-align: center;
}

.back-btn,
.chat-btn {
  display: grid;
  width: 36px;
  height: 36px;
  place-items: center;
  border: none;
  background: none;
  color: #333;
  cursor: pointer;
}

.chat-btn:disabled {
  color: #a1a1aa;
}

.header-spacer {
  width: 36px;
}

.center-loading {
  display: flex;
  justify-content: center;
  padding: 60px 0;
}

/* ========== Card layout ========== */
.card-section {
  margin: 12px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  overflow: hidden;
  padding: 14px;
}

.info-card {
  padding: 16px;
}

.card-header-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.order-no {
  font-size: 12px;
  color: #999;
  font-family: monospace;
}

.listing-code-chip {
  margin-bottom: 10px;
  padding: 4px 9px;
  border: 1px solid #dbeafe;
  border-radius: 999px;
  background: #eff6ff;
  color: #2563eb;
  font-size: 12px;
  font-weight: 800;
}

.order-title {
  font-size: 18px;
  font-weight: 700;
  color: #1a1a1a;
  margin: 0 0 14px 0;
}

.order-meta-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
  background: #f8f9fa;
  border-radius: 8px;
  padding: 10px;
}

.meta-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.meta-label {
  font-size: 11px;
  color: #8c96a0;
  margin-bottom: 4px;
}

.meta-value {
  font-size: 13px;
  color: #2c3e50;
  font-weight: 600;
}

.meta-value.accent {
  color: #ff5f00;
  font-weight: 700;
}

.meta-value.income {
  color: #16a34a;
  font-weight: 700;
}

.meta-note {
  margin-top: 2px;
  font-size: 10px;
  color: #2563eb;
}

.action-card {
  padding: 16px;
}

.section-title {
  font-size: 15px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0 0 8px 0;
}

.action-hint {
  font-size: 12px;
  color: #7f8c8d;
  line-height: 1.5;
  margin: 0 0 14px 0;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.action-field {
  background: #f8fafc;
  border-radius: 8px;
  margin-bottom: 12px;
  overflow: hidden;
}

.custom-inline-input {
  border: none;
  background: transparent;
  outline: none;
  font-size: 14px;
  flex: 1;
}

.no-snapshot-hint {
  text-align: center;
  padding: 10px;
  color: #cbd5e0;
  font-size: 13px;
}

/* ========== Popups ========== */
.mobile-popup-form {
  max-height: 85%;
  padding-bottom: env(safe-area-inset-bottom);
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #edf2f7;
}

.popup-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 700;
}

.popup-close {
  border: none;
  background: transparent;
  font-size: 16px;
  color: #a0aec0;
  cursor: pointer;
}

.popup-body {
  padding: 16px;
  overflow-y: auto;
}

.form-hint-info {
  font-size: 12px;
  color: #718096;
  line-height: 1.5;
  margin: 0 0 12px 0;
}

.popup-field {
  background: #f7fafc;
  border-radius: 8px;
  margin-bottom: 12px;
}

.evidence-upload-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 13px;
  color: #4a5568;
  margin-bottom: 16px;
}

.popup-submit {
  margin-top: 10px;
}

.custom-select {
  border: none;
  background: transparent;
  width: 100%;
  font-size: 14px;
  color: #2d3748;
  outline: none;
}

.empty-wrap {
  padding: 60px 0;
}
</style>
