<template>
  <div class="app-container">
    <el-card>
      <div slot="header"><span>权益包兑换记录</span></div>

      <!-- 搜索 -->
      <el-form :inline="true" :model="queryParams" class="mb-20">
        <el-form-item label="用户ID">
          <el-input v-model="queryParams.userId" clearable style="width:150px" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="全部" clearable style="width:120px">
            <el-option label="待处理" :value="0" />
            <el-option label="已发货" :value="1" />
            <el-option label="已完成" :value="2" />
            <el-option label="已取消" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table v-loading="loading" :data="list" border>
        <el-table-column prop="id" label="ID" width="70" />
        <el-table-column prop="userId" label="用户ID" width="90" />
        <el-table-column label="用户信息" width="130">
          <template slot-scope="scope">
            <div>{{ scope.row.userRealname }}</div>
            <div style="color:#999;font-size:12px">{{ scope.row.userPhone }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="packageName" label="权益包" min-width="150" />
        <el-table-column label="消耗" width="130">
          <template slot-scope="scope">
            <span v-if="scope.row.pointsCost > 0">{{ scope.row.pointsCost }}积分</span>
            <span v-if="scope.row.balanceCost > 0" style="margin-left:4px">¥{{ scope.row.balanceCost }}</span>
          </template>
        </el-table-column>
        <el-table-column label="收货地址" min-width="200">
          <template slot-scope="scope">
            <template v-if="scope.row.addressSnapshot">
              {{ formatAddress(scope.row.addressSnapshot) }}
            </template>
            <span v-else style="color:#ccc">无需配送</span>
          </template>
        </el-table-column>
        <el-table-column label="物流" width="200">
          <template slot-scope="scope">
            <template v-if="scope.row.expressNo">
              <div>{{ scope.row.expressCompany }}</div>
              <div style="color:#1890ff">{{ scope.row.expressNo }}</div>
            </template>
            <span v-else style="color:#ccc">-</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="90">
          <template slot-scope="scope">
            <el-tag :type="statusType(scope.row.status)" size="mini">
              {{ statusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="兑换时间" width="160" />
        <el-table-column label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.status === 0"
              type="text"
              @click="handleShip(scope.row)"
            >发货</el-button>
            <el-button
              v-if="scope.row.status === 1"
              type="text"
              @click="handleComplete(scope.row)"
            >标记完成</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.limit"
        @pagination="getList"
      />
    </el-card>

    <!-- 发货对话框 -->
    <el-dialog :visible.sync="shipDialogVisible" title="填写发货信息" width="440px">
      <el-form :model="shipForm" label-width="90px">
        <el-form-item label="快递公司">
          <el-input v-model="shipForm.expressCompany" placeholder="如：顺丰速运" />
        </el-form-item>
        <el-form-item label="快递单号">
          <el-input v-model="shipForm.expressNo" placeholder="请输入快递单号" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="shipDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitShip">确认发货</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getBenefitExchangePage,
  shipBenefitExchange,
  completeBenefitExchange,
} from '@/api/shop/shopMemberBenefit';

export default {
  name: 'ShopMemberBenefitExchange',
  data() {
    return {
      loading: false,
      list: [],
      total: 0,
      queryParams: { page: 1, limit: 20, userId: '', status: '' },
      shipDialogVisible: false,
      shipForm: { id: null, expressCompany: '', expressNo: '' },
    };
  },
  created() { this.getList(); },
  methods: {
    async getList() {
      this.loading = true;
      try {
        const res = await getBenefitExchangePage(this.queryParams);
        this.list = res.data.list || [];
        this.total = res.data.total || 0;
      } finally { this.loading = false; }
    },
    handleQuery() { this.queryParams.page = 1; this.getList(); },
    resetQuery() { this.queryParams = { page: 1, limit: 20, userId: '', status: '' }; this.getList(); },

    handleShip(row) {
      this.shipForm = { id: row.id, expressCompany: '', expressNo: '' };
      this.shipDialogVisible = true;
    },
    async submitShip() {
      if (!this.shipForm.expressNo) {
        this.$message.warning('请输入快递单号');
        return;
      }
      await shipBenefitExchange(this.shipForm.id, {
        expressCompany: this.shipForm.expressCompany,
        expressNo: this.shipForm.expressNo,
      });
      this.$message.success('发货成功');
      this.shipDialogVisible = false;
      this.getList();
    },

    async handleComplete(row) {
      await this.$confirm('确认标记为已完成？', '提示', { type: 'warning' });
      await completeBenefitExchange(row.id);
      this.$message.success('已完成');
      this.getList();
    },

    formatAddress(snapshot) {
      try {
        const addr = JSON.parse(snapshot);
        return `${addr.name} ${addr.phone}  ${addr.province || ''}${addr.city || ''}${addr.district || ''}${addr.detail || ''}`;
      } catch {
        return snapshot;
      }
    },
    statusText(s) {
      return ['待处理', '已发货', '已完成', '已取消'][s] || '-';
    },
    statusType(s) {
      return ['warning', 'primary', 'success', 'info'][s] || 'info';
    },
  },
};
</script>

<style scoped>
.mb-20 { margin-bottom: 20px; }
</style>
