<template>
  <div class="app-container">
    <!-- 查询区 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="团购编号" prop="groupNo">
        <el-input v-model="queryParams.groupNo" placeholder="请输入团购编号" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商品名称" prop="productName">
        <el-input v-model="queryParams.productName" placeholder="请输入商品名称" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商品ID" prop="productId">
        <el-input v-model="queryParams.productId" placeholder="请输入商品ID" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable size="small" style="width: 140px">
          <el-option label="进行中" :value="0" />
          <el-option label="拼团成功" :value="1" />
          <el-option label="拼团失败" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间" prop="beginTime">
        <el-date-picker v-model="queryParams.beginTime" type="datetime" placeholder="开始时间" value-format="yyyy-MM-dd HH:mm:ss" size="small" style="width: 200px" />
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker v-model="queryParams.endTime" type="datetime" placeholder="结束时间" value-format="yyyy-MM-dd HH:mm:ss" size="small" style="width: 200px" />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list" border>
      <el-table-column label="团购编号" align="center" prop="groupNo" width="160" />
      <el-table-column label="商品信息" align="center" min-width="260">
        <template slot-scope="scope">
          <div style="display:flex;align-items:center;">
            <el-image
              v-if="scope.row.productImage"
              style="width:50px;height:50px;margin-right:10px;border-radius:4px;"
              :src="scope.row.productImage"
              fit="cover"
              :preview-src-list="[scope.row.productImage]"
            />
            <div style="text-align:left;">
              <div>{{ scope.row.productName || '-' }}</div>
              <div style="color:#909399;font-size:12px;">ID: {{ scope.row.productId }}</div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="原价" align="center" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.originalPrice != null">¥{{ Number(scope.row.originalPrice).toFixed(2) }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="团购价" align="center" width="110">
        <template slot-scope="scope">
          <span style="color:#f56c6c;font-weight:bold;">¥{{ scope.row.groupPrice ? Number(scope.row.groupPrice).toFixed(2) : '0.00' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="成团人数" align="center" prop="groupNum" width="90" />
      <el-table-column label="进度(已付/参团/满团)" align="center" width="170">
        <template slot-scope="scope">
          <el-tag size="mini" type="success">已付 {{ scope.row.paidNum || 0 }}</el-tag>
          <el-tag size="mini" type="warning" style="margin-left:4px;">参团 {{ scope.row.joinNum || 0 }}</el-tag>
          <el-tag size="mini" style="margin-left:4px;">满 {{ scope.row.groupNum || 0 }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="160" />
      <el-table-column label="结束时间" align="center" prop="endTime" width="160" />
      <el-table-column label="状态" align="center" width="90">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 0" type="warning">进行中</el-tag>
          <el-tag v-else-if="scope.row.status === 1" type="success">拼团成功</el-tag>
          <el-tag v-else-if="scope.row.status === 2" type="danger">拼团失败</el-tag>
          <el-tag v-else type="info">未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)" v-hasPermi="['store:productGroupBuy:query']">查看详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-s-order" @click="handleHistory(scope.row)" v-hasPermi="['store:productGroupBuy:list']">历史拼团</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 详情抽屉：团购信息 + 商品信息 + 团员表格（含订单状态） -->
    <el-drawer title="团购详情" :visible.sync="detailOpen" size="75%" destroy-on-close>
      <div v-loading="detailLoading" style="padding: 0 20px;">
        <template v-if="detail">
          <el-descriptions title="团购信息" :column="3" border size="small">
            <el-descriptions-item label="团购编号">{{ detail.groupNo }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag v-if="detail.status === 0" type="warning">进行中</el-tag>
              <el-tag v-else-if="detail.status === 1" type="success">拼团成功</el-tag>
              <el-tag v-else-if="detail.status === 2" type="danger">拼团失败</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="成团人数">{{ detail.groupNum }}</el-descriptions-item>
            <el-descriptions-item label="已参团">{{ detail.joinNum }}</el-descriptions-item>
            <el-descriptions-item label="已付款">{{ detail.paidNum }}</el-descriptions-item>
            <el-descriptions-item label="团购价">
              <span style="color:#f56c6c;font-weight:bold;">¥{{ detail.groupPrice ? Number(detail.groupPrice).toFixed(2) : '0.00' }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="原价">¥{{ detail.originalPrice ? Number(detail.originalPrice).toFixed(2) : '-' }}</el-descriptions-item>
            <el-descriptions-item label="开始时间">{{ detail.startTime }}</el-descriptions-item>
            <el-descriptions-item label="结束时间">{{ detail.endTime }}</el-descriptions-item>
          </el-descriptions>

          <el-descriptions title="商品信息" :column="2" border size="small" style="margin-top:16px;">
            <el-descriptions-item label="商品">
              <div style="display:flex;align-items:center;">
                <el-image
                  v-if="detail.productImage"
                  style="width:50px;height:50px;margin-right:10px;border-radius:4px;"
                  :src="detail.productImage"
                  fit="cover"
                  :preview-src-list="[detail.productImage]"
                />
                <span>{{ detail.productName || '-' }}</span>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="商品ID">{{ detail.productId }}</el-descriptions-item>
          </el-descriptions>

          <div style="margin-top: 16px; display:flex; justify-content: space-between; align-items:center;">
            <h3 style="margin:0;">参团用户（订单状态）</h3>
            <span style="color:#909399;font-size:12px;">共 {{ detail.members ? detail.members.length : 0 }} 人</span>
          </div>
          <el-table :data="detail.members || []" border size="small" style="margin-top:8px;">
            <el-table-column label="用户" align="center" min-width="180">
              <template slot-scope="scope">
                <div style="display:flex;align-items:center;">
                  <el-avatar v-if="scope.row.avatar" :src="scope.row.avatar" size="small" style="margin-right:8px;" />
                  <div style="text-align:left;">
                    <div>{{ scope.row.nickName || '-' }}</div>
                    <div style="color:#909399;font-size:12px;">ID: {{ scope.row.userId }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="规格" align="center" prop="specName" min-width="140">
              <template slot-scope="scope">
                <span>{{ scope.row.specName || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="参团时间" align="center" prop="joinTime" width="160" />
            <el-table-column label="订单号" align="center" prop="orderCode" min-width="180">
              <template slot-scope="scope">
                <el-link v-if="scope.row.orderCode" type="primary" @click="copyOrderCode(scope.row.orderCode)">{{ scope.row.orderCode }}</el-link>
                <span v-else style="color:#c0c4cc;">-</span>
              </template>
            </el-table-column>
            <el-table-column label="付款状态" align="center" width="90">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.payStatus === 1" type="success" size="mini">已付</el-tag>
                <el-tag v-else type="info" size="mini">未付</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="订单状态" align="center" width="110">
              <template slot-scope="scope">
                <span>{{ formatOrderStatus(scope.row.orderStatus) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="退款状态" align="center" width="100">
              <template slot-scope="scope">
                <span>{{ formatRefundStatus(scope.row.refundStatus) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="支付金额" align="center" width="100">
              <template slot-scope="scope">
                <span v-if="scope.row.payMoney != null">¥{{ Number(scope.row.payMoney).toFixed(2) }}</span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="退款金额" align="center" width="100">
              <template slot-scope="scope">
                <span v-if="scope.row.refundPrice != null && Number(scope.row.refundPrice) > 0" style="color:#f56c6c;">¥{{ Number(scope.row.refundPrice).toFixed(2) }}</span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="付款时间" align="center" prop="payTime" width="160" />
            <el-table-column label="操作" align="center" width="110">
              <template slot-scope="scope">
                <el-button size="mini" type="text" :disabled="!scope.row.orderCode" @click="goOrderDetail(scope.row)">查看订单</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </div>
    </el-drawer>

    <!-- 历史拼团抽屉：按商品ID查所有团购记录 -->
    <el-drawer :title="`历史拼团 - ${historyProductName || ''}`" :visible.sync="historyOpen" size="70%" destroy-on-close>
      <div v-loading="historyLoading" style="padding: 0 20px;">
        <el-table :data="historyList" border size="small">
          <el-table-column label="团购编号" align="center" prop="groupNo" width="160" />
          <el-table-column label="团购价" align="center" width="100">
            <template slot-scope="scope">
              <span style="color:#f56c6c;">¥{{ scope.row.groupPrice ? Number(scope.row.groupPrice).toFixed(2) : '0.00' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="成团人数" align="center" prop="groupNum" width="90" />
          <el-table-column label="已付/参团" align="center" width="130">
            <template slot-scope="scope">
              <span>{{ scope.row.paidNum || 0 }} / {{ scope.row.joinNum || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="开始时间" align="center" prop="startTime" width="160" />
          <el-table-column label="结束时间" align="center" prop="endTime" width="160" />
          <el-table-column label="状态" align="center" width="100">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status === 0" type="warning" size="mini">进行中</el-tag>
              <el-tag v-else-if="scope.row.status === 1" type="success" size="mini">拼团成功</el-tag>
              <el-tag v-else-if="scope.row.status === 2" type="danger" size="mini">拼团失败</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="100">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="handleDetail(scope.row)">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  listProductGroupBuy,
  getProductGroupBuy,
  listGroupBuyByProduct
} from '@/api/hisStore/productGroupBuy'

export default {
  name: 'ProductGroupBuy',
  data() {
    return {
      loading: false,
      showSearch: true,
      list: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        groupNo: null,
        productId: null,
        productName: null,
        status: null,
        beginTime: null,
        endTime: null
      },
      // 详情抽屉
      detailOpen: false,
      detailLoading: false,
      detail: null,
      // 历史拼团抽屉
      historyOpen: false,
      historyLoading: false,
      historyList: [],
      historyProductName: ''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      listProductGroupBuy(this.queryParams).then(response => {
        this.list = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleDetail(row) {
      this.detailOpen = true
      this.detailLoading = true
      this.detail = null
      getProductGroupBuy(row.id).then(response => {
        this.detail = response.data || null
        this.detailLoading = false
      }).catch(() => {
        this.detailLoading = false
      })
    },
    handleHistory(row) {
      this.historyOpen = true
      this.historyLoading = true
      this.historyProductName = row.productName || ''
      this.historyList = []
      listGroupBuyByProduct(row.productId).then(response => {
        this.historyList = response.rows || []
        this.historyLoading = false
      }).catch(() => {
        this.historyLoading = false
      })
    },
    copyOrderCode(code) {
      const input = document.createElement('input')
      input.value = code
      document.body.appendChild(input)
      input.select()
      try {
        document.execCommand('copy')
        this.msgSuccess('订单号已复制：' + code)
      } catch (e) {
        this.$message.warning('复制失败，请手动复制')
      }
      document.body.removeChild(input)
    },
    goOrderDetail(row) {
      if (!row.orderCode) return
      // 跳转到订单列表并自动按订单号筛选
      const routeData = this.$router.resolve({
        path: '/his/storeOrder',
        query: { orderCode: row.orderCode }
      })
      window.open(routeData.href, '_blank')
    },
    formatOrderStatus(status) {
      // fs_store_order_scrm.status（OrderInfoEnum）：
      // -1 申请退款 / -2 退款成功 / -3 已取消 / 0 待支付 / 1 待发货 / 2 待收货 / 3 已完成 / 4 待评价
      const map = {
        0: '待支付',
        1: '待发货',
        2: '待收货',
        3: '已完成',
        4: '待评价',
        '-1': '申请退款',
        '-2': '退款成功',
        '-3': '已取消'
      }
      if (status === null || status === undefined) return '-'
      return map[status] !== undefined ? map[status] : ('状态' + status)
    },
    formatRefundStatus(status) {
      // 0 未退款 1 申请中 2 已退款
      const map = { 0: '未退款', 1: '退款中', 2: '已退款' }
      if (status === null || status === undefined) return '-'
      return map[status] !== undefined ? map[status] : ('状态' + status)
    }
  }
}
</script>
