<template>
  <div class="NCC-common-layout">
    <div class="NCC-common-layout-center">
      <!-- 筛选条件 -->
      <el-row class="NCC-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <el-col :span="8">
            <el-form-item label="活动">
              <el-select
                v-model="query.activityId"
                placeholder="请选择活动"
                clearable
                filterable
                :style='{"width":"100%"}'>
                <el-option
                  v-for="item in activityOptions"
                  :key="item.id"
                  :label="item.activityName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="开始时间">
              <el-date-picker 
                v-model="query.startTime" 
                type="datetime" 
                value-format="yyyy-MM-dd HH:mm:ss" 
                format="yyyy-MM-dd HH:mm:ss" 
                placeholder="开始时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结束时间">
              <el-date-picker 
                v-model="query.endTime" 
                type="datetime" 
                value-format="yyyy-MM-dd HH:mm:ss" 
                format="yyyy-MM-dd HH:mm:ss" 
                placeholder="结束时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="门店（多选）">
              <el-select
                v-model="query.storeIds"
                multiple
                collapse-tags
                placeholder="请选择门店"
                filterable
                :style='{"width":"100%"}'>
                <el-option
                  v-for="store in storeOptions"
                  :key="store.id"
                  :label="store.dm"
                  :value="store.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
              <el-button icon="el-icon-refresh-right" @click="reset()">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>

      <!-- 统计卡片 -->
      <div class="statistics-cards" v-loading="listLoading">
        <el-row :gutter="16" v-if="statisticsData">
          <el-col :span="6">
            <div class="statistics-card">
              <div class="card-icon">
                <i class="el-icon-document"></i>
              </div>
              <div class="card-content">
                <div class="card-title">活动名称</div>
                <div class="card-value">{{ statisticsData.ActivityName || '无' }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="statistics-card">
              <div class="card-icon">
                <i class="el-icon-shopping-bag-1"></i>
              </div>
              <div class="card-content">
                <div class="card-title">开单数量</div>
                <div class="card-value">{{ statisticsData.BillingCount || 0 }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="statistics-card">
              <div class="card-icon">
                <i class="el-icon-money"></i>
              </div>
              <div class="card-content">
                <div class="card-title">开单金额</div>
                <div class="card-value">¥{{ formatMoney(statisticsData.BillingAmount) }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="statistics-card">
              <div class="card-icon">
                <i class="el-icon-delete"></i>
              </div>
              <div class="card-content">
                <div class="card-title">退款数量</div>
                <div class="card-value">{{ statisticsData.RefundCount || 0 }}</div>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="16" style="margin-top: 16px;" v-if="statisticsData">
          <el-col :span="6">
            <div class="statistics-card">
              <div class="card-icon">
                <i class="el-icon-delete-solid"></i>
              </div>
              <div class="card-content">
                <div class="card-title">退款金额</div>
                <div class="card-value">¥{{ formatMoney(statisticsData.RefundAmount) }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="statistics-card">
              <div class="card-icon">
                <i class="el-icon-connection"></i>
              </div>
              <div class="card-content">
                <div class="card-title">净开单数量</div>
                <div class="card-value">{{ statisticsData.NetBillingCount || 0 }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="statistics-card">
              <div class="card-icon">
                <i class="el-icon-success"></i>
              </div>
              <div class="card-content">
                <div class="card-title">净开单金额</div>
                <div class="card-value">¥{{ formatMoney(statisticsData.NetBillingAmount) }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="statistics-card">
              <div class="card-icon">
                <i class="el-icon-warning"></i>
              </div>
              <div class="card-content">
                <div class="card-title">退款率</div>
                <div class="card-value">{{ formatPercent(statisticsData.RefundRate) }}%</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'ActivityStatistics',
  data() {
    return {
      query: {
        activityId: '',
        startTime: undefined,
        endTime: undefined,
        storeIds: []
      },
      activityOptions: [],
      storeOptions: [],
      statisticsData: null,
      listLoading: false
    }
  },
  created() {
    this.setDefaultTimeRange()
    this.initActivityOptions()
    this.initStoreOptions()
  },
  methods: {
    // 设置默认时间范围（本月1号到现在）
    setDefaultTimeRange() {
      const now = new Date()
      const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1)
      
      this.query.startTime = this.formatDateTime(firstDayOfMonth.getTime())
      this.query.endTime = this.formatDateTime(now.getTime())
    },

    // 初始化活动选项
    initActivityOptions() {
      request({
        url: '/api/Extend/lqpackageinfo/GetPackageInfoListAsync',
        method: 'GET',
        data: {
          currentPage: 1,
          pageSize: 1000
        }
      }).then(res => {
        this.activityOptions = res.data.list || []
        if(this.activityOptions.length > 0) {
          this.query.activityId = this.activityOptions[0].id
          this.search()
        }
      }).catch(err => {
        console.error('获取活动列表失败:', err)
      })
    },

    // 初始化门店选项
    initStoreOptions() {
      request({
        url: '/api/Extend/LqMdxx',
        method: 'GET',
        data: {
          currentPage: 1,
          pageSize: 1000
        }
      }).then(res => {
        this.storeOptions = res.data.list || []
      }).catch(err => {
        console.error('获取门店列表失败:', err)
      })
    },

    // 查询数据
    search() {
      if (!this.query.activityId) {
        this.$message({
          type: 'warning',
          message: '请选择活动',
          duration: 1500
        })
        return
      }

      this.listLoading = true

      const params = {
        activityId: this.query.activityId,
        startTime: this.query.startTime,
        endTime: this.query.endTime,
        storeIds: this.query.storeIds || []
      }

      request({
        url: '/api/Extend/lqpackageinfo/get-activity-statistics',
        method: 'POST',
        data: params
      }).then(res => {
        console.error(res)
        if (res.data && res.data) {
          this.statisticsData = res.data
        } else {
          this.statisticsData = null
        }
        this.listLoading = false
      }).catch(err => {
        console.error('查询失败:', err)
        this.$message({
          type: 'error',
          message: '查询失败，请重试',
          duration: 1500
        })
        this.listLoading = false
      })
    },

    // 重置查询条件
    reset() {
      this.query = {
        activityId: '',
        startTime: undefined,
        endTime: undefined,
        storeIds: []
      }
      this.setDefaultTimeRange()
      this.statisticsData = null
    },

    // 格式化金额
    formatMoney(amount) {
      if (!amount && amount !== 0) return '0.00'
      return Number(amount).toFixed(2)
    },

    // 格式化百分比
    formatPercent(ratio) {
      if (!ratio && ratio !== 0) return '0.00'
      return (Number(ratio) * 100).toFixed(2)
    },

    // 格式化日期时间（用于API传参）
    formatDateTime(timestamp) {
      if (!timestamp) return ''
      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    }
  }
}
</script>

<style lang="scss" scoped>
.statistics-cards {
  margin-bottom: 20px;
  min-height: 300px;
}

.statistics-card {
  height: 100px;
  padding: 12px;
  border-radius: 12px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  
  .card-icon {
    width: 60px;
    height: 60px;
    border-radius: 8px;
    background: linear-gradient(135deg, #409EFF, #67C23A);
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;
    
    i {
      font-size: 24px;
      color: #fff;
    }
  }
  
  .card-content {
    flex: 1;
    
    .card-title {
      font-size: 14px;
      color: #909399;
      margin-bottom: 8px;
    }
    
    .card-value {
      font-size: 20px;
      font-weight: bold;
      color: #303133;
      word-break: break-all;
    }
  }
}
</style>

