<template>
  <el-dialog
    :visible.sync="visibleProxy"
    :show-close="false"
    width="720px"
    :close-on-click-modal="false"
    custom-class="pickup-verify-dialog"
    append-to-body
    @open="handleOpen"
  >
    <div class="dialog-inner">
      <div class="dialog-header">
        <div class="dialog-title-wrap">
          <div class="dialog-title">提货核销</div>
          <div class="dialog-subtitle">输入会员商城取件码，核销后订单标记为已完成</div>
        </div>
        <span class="dialog-close" @click="visibleProxy = false"><i class="el-icon-close"></i></span>
      </div>

      <div class="dialog-body">
        <div class="search-bar">
          <div class="search-input-wrap">
            <i class="el-icon-postcard search-input-icon"></i>
            <el-input
              ref="codeInput"
              v-model="pickupCode"
              placeholder="请输入 / 扫描取件码"
              clearable
              class="search-input"
              @keyup.enter.native="handleQuery"
              @clear="clearOrder"
            />
          </div>
          <div class="search-actions">
            <el-button type="primary" icon="el-icon-search" :loading="querying" @click="handleQuery">查询订单</el-button>
            <el-button icon="el-icon-refresh-left" @click="handleReset">重置</el-button>
          </div>
        </div>

        <div v-if="order" class="order-panel">
          <div class="order-summary">
            <div class="summary-item">
              <span class="summary-label">订单号</span>
              <span class="summary-value">{{ emptyText(order.orderNo) }}</span>
            </div>
            <div class="summary-item">
              <span class="summary-label">会员</span>
              <span class="summary-value">{{ memberText }}</span>
            </div>
            <div class="summary-item">
              <span class="summary-label">下单时间</span>
              <span class="summary-value">{{ formatDateTime(order.createTime) }}</span>
            </div>
            <div class="summary-item">
              <span class="summary-label">订单金额</span>
              <span class="summary-value summary-value--amount">{{ amountText(order.amount) }}</span>
            </div>
            <div class="summary-item">
              <span class="summary-label">订单状态</span>
              <el-tag size="mini" :type="statusTagType(order.status)" effect="plain">{{ statusLabel(order.status) }}</el-tag>
            </div>
          </div>

          <div class="items-title">商品明细</div>
          <el-table
            :data="items"
            border
            size="small"
            :header-cell-style="{ background: '#f8fafc', color: '#64748b', fontWeight: 600 }"
          >
            <el-table-column type="index" label="#" width="50" align="center" />
            <el-table-column label="商品名称" min-width="180" show-overflow-tooltip>
              <template slot-scope="{ row }">{{ emptyText(row.itemName || row.name) }}</template>
            </el-table-column>
            <el-table-column label="规格" min-width="120" show-overflow-tooltip>
              <template slot-scope="{ row }">{{ emptyText(row.spec || row.specName) }}</template>
            </el-table-column>
            <el-table-column label="数量" width="80" align="center">
              <template slot-scope="{ row }">{{ emptyText(row.quantity != null ? row.quantity : row.qty) }}</template>
            </el-table-column>
            <el-table-column label="单价" width="110" align="right">
              <template slot-scope="{ row }">{{ amountText(row.price) }}</template>
            </el-table-column>
            <el-table-column label="小计" width="110" align="right">
              <template slot-scope="{ row }">{{ amountText(row.amount != null ? row.amount : row.subtotal) }}</template>
            </el-table-column>
          </el-table>
          <div v-if="!items.length" class="empty-items">暂无商品明细</div>
        </div>

        <div v-else class="order-empty">
          <i class="el-icon-box"></i>
          <span>请输入取件码查询待自提订单</span>
        </div>
      </div>

      <div class="dialog-footer">
        <el-button
          type="primary"
          icon="el-icon-circle-check"
          :loading="verifying"
          :disabled="!canVerify"
          @click="handleVerify"
        >确认核销</el-button>
        <el-button @click="visibleProxy = false">关闭</el-button>
        <span v-if="order && !canVerify" class="footer-tip">当前订单非「待自提」状态，无法核销</span>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { queryByPickupCode, verify } from '@/api/mall'

// 订单状态枚举：1待付款/2待自提/3已完成/4已取消
const STATUS_MAP = {
  1: '待付款',
  2: '待自提',
  3: '已完成',
  4: '已取消'
}

export default {
  name: 'PickupVerifyDialog',
  props: {
    visible: { type: Boolean, default: false },
    storeId: { type: String, default: '' }
  },
  data() {
    return {
      pickupCode: '',
      order: null,
      items: [],
      querying: false,
      verifying: false
    }
  },
  computed: {
    visibleProxy: {
      get() { return this.visible },
      set(v) { this.$emit('update:visible', v) }
    },
    memberText() {
      if (!this.order) return '无'
      const name = this.order.memberName || this.order.khmc || ''
      const phone = this.order.memberPhone || this.order.phone || ''
      if (name && phone) return `${name}（${this.$maskMobile(phone)}）`
      return this.emptyText(name || phone)
    },
    canVerify() {
      return !!this.order && Number(this.order.status) === 2
    }
  },
  methods: {
    handleOpen() {
      this.pickupCode = ''
      this.clearOrder()
      this.$nextTick(() => {
        if (this.$refs.codeInput) this.$refs.codeInput.focus()
      })
    },
    emptyText(val) {
      if (val === undefined || val === null || String(val).trim() === '') return '无'
      return val
    },
    amountText(val) {
      if (val === undefined || val === null || val === '') return '无'
      const num = Number(val)
      if (isNaN(num)) return '无'
      return `¥${num.toFixed(2)}`
    },
    formatDateTime(val) {
      if (!val) return '无'
      const d = new Date(val)
      if (isNaN(d.getTime())) return String(val)
      const y = d.getFullYear()
      const m = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      const hh = String(d.getHours()).padStart(2, '0')
      const mm = String(d.getMinutes()).padStart(2, '0')
      return `${y}-${m}-${day} ${hh}:${mm}`
    },
    statusLabel(status) {
      return STATUS_MAP[Number(status)] || '无'
    },
    statusTagType(status) {
      const map = { 1: 'warning', 2: 'primary', 3: 'success', 4: 'info' }
      return map[Number(status)] || 'info'
    },
    clearOrder() {
      this.order = null
      this.items = []
    },
    resolveStoreId() {
      return this.storeId || localStorage.getItem('store_current_store_id') || ''
    },
    async handleQuery() {
      const code = (this.pickupCode || '').trim()
      if (!code) {
        this.$message.warning('请输入取件码')
        return
      }
      const storeId = this.resolveStoreId()
      if (!storeId) {
        this.$message.warning('未获取到当前门店信息')
        return
      }
      this.querying = true
      try {
        const res = await queryByPickupCode({ pickupCode: code, storeId })
        const data = res.data || {}
        this.order = data
        this.items = data.items || []
        if (Number(data.status) !== 2) {
          this.$message.warning(`该订单当前为「${this.statusLabel(data.status)}」，仅「待自提」订单可核销`)
        }
      } catch (e) {
        // 取件码不存在 / 不属于本门店 / 非待自提等错误由 request 拦截器统一提示
        this.clearOrder()
      } finally {
        this.querying = false
      }
    },
    async handleVerify() {
      if (!this.canVerify) return
      const code = (this.pickupCode || '').trim()
      const storeId = this.resolveStoreId()
      if (!storeId) {
        this.$message.warning('未获取到当前门店信息')
        return
      }
      this.verifying = true
      try {
        const res = await verify({ PickupCode: code, StoreId: storeId })
        const data = res.data || {}
        const orderNo = data.orderNo || this.order.orderNo || ''
        this.$message.success(orderNo ? `核销成功：${orderNo}` : '核销成功')
        this.$emit('verified', data)
        this.pickupCode = ''
        this.clearOrder()
        this.$nextTick(() => {
          if (this.$refs.codeInput) this.$refs.codeInput.focus()
        })
      } catch (e) {
        // 错误信息由 request 拦截器统一提示
      } finally {
        this.verifying = false
      }
    },
    handleReset() {
      this.pickupCode = ''
      this.clearOrder()
      this.$nextTick(() => {
        if (this.$refs.codeInput) this.$refs.codeInput.focus()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .pickup-verify-dialog {
  border-radius: 20px;
  padding: 0;
  background: radial-gradient(circle at 0 0, rgba(255, 255, 255, 0.96) 0, rgba(248, 250, 252, 0.98) 40%, rgba(241, 245, 249, 0.98) 100%);
  box-shadow: 0 24px 48px rgba(15, 23, 42, 0.18), 0 0 0 1px rgba(255, 255, 255, 0.9);
  .el-dialog__header { display: none; }
  .el-dialog__body { padding: 0; }
}
.dialog-inner { display: flex; flex-direction: column; max-height: 88vh; }
.dialog-header {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 18px 22px 0;
  padding: 10px 14px;
  border-radius: 14px;
  background: rgba(219, 234, 254, 0.96);
}
.dialog-title-wrap { display: flex; flex-direction: column; gap: 2px; }
.dialog-title { font-size: 17px; font-weight: 600; color: #0f172a; }
.dialog-subtitle { font-size: 12px; color: #64748b; }
.dialog-close {
  cursor: pointer;
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 999px;
  color: #64748b;
  &:hover { background: rgba(0, 0, 0, 0.06); color: #0f172a; }
}
.dialog-body { flex: 1; min-height: 0; overflow: auto; padding: 16px 22px 4px; }
.search-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 10px 12px;
  border-radius: 14px;
  background: rgba(255, 255, 255, 0.85);
  border: 1px solid rgba(226, 232, 240, 0.9);
  box-shadow: inset 0 1px 2px rgba(15, 23, 42, 0.03);
}
.search-input-wrap {
  position: relative;
  flex: 1;
  .search-input-icon {
    position: absolute;
    left: 12px;
    top: 50%;
    transform: translateY(-50%);
    z-index: 1;
    color: #94a3b8;
    font-size: 15px;
    pointer-events: none;
  }
}
::v-deep .search-input .el-input__inner {
  height: 38px;
  line-height: 38px;
  padding-left: 34px;
  border-radius: 10px;
  border-color: #e2e8f0;
  background: #fff;
  transition: all 0.15s;
  &:focus { border-color: #409EFF; box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.12); }
}
.search-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  .el-button { border-radius: 10px; padding: 10px 18px; }
}
.order-panel { margin-top: 16px; }
.order-summary {
  display: flex;
  flex-wrap: wrap;
  gap: 12px 28px;
  padding: 14px 16px;
  border-radius: 14px;
  background: rgba(248, 250, 252, 0.9);
  border: 1px solid rgba(226, 232, 240, 0.9);
  margin-bottom: 14px;
}
.summary-item { display: flex; align-items: center; gap: 8px; }
.summary-label { font-size: 12px; color: #94a3b8; }
.summary-value { font-size: 14px; color: #0f172a; font-weight: 500; }
.summary-value--amount { color: #409EFF; font-weight: 600; }
.items-title { font-size: 14px; font-weight: 600; color: #334155; margin-bottom: 8px; }
.empty-items { text-align: center; color: #94a3b8; font-size: 13px; padding: 16px 0; }
.order-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 10px;
  color: #94a3b8;
  padding: 48px 0 40px;
  i { font-size: 42px; }
  span { font-size: 13px; }
}
.dialog-footer {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 10px;
  padding: 12px 22px 18px;
  border-top: 1px solid rgba(229, 231, 235, 0.6);
}
.footer-tip { font-size: 12px; color: #f59e0b; }
::v-deep .pickup-verify-dialog .el-button--primary {
  border-radius: 999px;
  background: #409EFF;
  border-color: #409EFF;
}
</style>
