<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 icon-blue">
                <i class="el-icon-trophy"></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 icon-green">
                <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 icon-orange">
                <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 icon-red">
                <i class="el-icon-wallet"></i>
              </div>
              <div class="card-content">
                <div class="card-title">欠款金额</div>
                <div class="card-value">¥{{ formatMoney(statisticsData.DebtAmount) }}</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 开单列表 -->
      <div class="billing-table-section" v-loading="listLoading">
        <el-table
          :data="billingList"
          border
          style="width: 100%;max-height: 40vh;overflow-y: scroll;"
          stripe>
          <!-- <el-table-column
            prop="BillingId"
            label="账单ID"
            >
            <template slot-scope="scope">
              <i class="el-icon-document"></i> {{ scope.row.BillingId || '无' }}
            </template>
          </el-table-column> -->
          <el-table-column
            prop="BillingDate"
            label="开单日期"
            >
            <template slot-scope="scope">
              {{ formatDate(scope.row.BillingDate) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="CustomerName"
            label="客户姓名"
           >
            <template slot-scope="scope">
              <i class="el-icon-user"></i> {{ scope.row.CustomerName || '无' }}
            </template>
          </el-table-column>
          <el-table-column
            prop="CustomerPhone"
            label="客户电话"
            >
            <template slot-scope="scope">
              <i class="el-icon-phone"></i> {{ scope.row.CustomerPhone || '无' }}
            </template>
          </el-table-column>
          <el-table-column
            prop="StoreName"
            label="门店"
            >
            <template slot-scope="scope">
              <i class="el-icon-s-home"></i> {{ scope.row.StoreName || '无' }}
            </template>
          </el-table-column>
          <el-table-column
            prop="Amount"
            label="开单金额"
           >
            <template slot-scope="scope">
              <i class="el-icon-money"></i> ¥{{ formatMoney(scope.row.Amount) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="DebtAmount"
            label="欠款金额"
           >
            <template slot-scope="scope">
              <i class="el-icon-wallet"></i> ¥{{ formatMoney(scope.row.DebtAmount) }}
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination
          v-if="billingList.length > 0"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
          :current-page="pager.pageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pager.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pager.total"
          style="margin-top: 16px; text-align: right;">
        </el-pagination>
      </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,
      billingList: [],
      pager: {
        pageIndex: 1,
        pageSize: 20,
        total: 0
      }
    }
  },
  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 || [],
        pageIndex: this.pager.pageIndex,
        pageSize: this.pager.pageSize
      }

      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
          this.billingList = res.data.BillingList || []
          this.pager.total = res.data.total || this.billingList.length
        } else {
          this.statisticsData = null
          this.billingList = []
          this.pager.total = 0
        }
        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
      this.billingList = []
      this.pager = {
        pageIndex: 1,
        pageSize: 20,
        total: 0
      }
    },

    // 分页改变
    handlePageChange(page) {
      this.pager.pageIndex = page
      this.search()
    },

    // 每页条数改变
    handleSizeChange(size) {
      this.pager.pageSize = size
      this.pager.pageIndex = 1
      this.search()
    },

    // 格式化日期
    formatDate(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}`
    },

    // 格式化金额
    formatMoney(amount) {
      if (!amount && amount !== 0) return '0.00'
      return Number(amount).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: 100px;
}

.statistics-card {
  height: 100px;
  padding: 12px;
  border-radius: 12px;
  background: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  display: flex;
  align-items: center;
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  }
  
  .card-icon {
    width: 60px;
    height: 60px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;
    flex-shrink: 0;
    
    &.icon-blue {
      background: linear-gradient(135deg, #409EFF, #66B1FF);
    }
    
    &.icon-green {
      background: linear-gradient(135deg, #67C23A, #85CE61);
    }
    
    &.icon-orange {
      background: linear-gradient(135deg, #E6A23C, #EEBE77);
    }
    
    &.icon-red {
      background: linear-gradient(135deg, #F56C6C, #F89898);
    }
    
    i {
      font-size: 24px;
      color: #fff;
    }
  }
  
  .card-content {
    flex: 1;
    min-width: 0;
    
    .card-title {
      font-size: 14px;
      color: #909399;
      margin-bottom: 8px;
      line-height: 1.2;
    }
    
    .card-value {
      font-size: 20px;
      font-weight: bold;
      color: #303133;
      word-break: break-all;
      line-height: 1.2;
    }
  }
}

.billing-table-section {
  margin-top: 20px;
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  
  ::v-deep .el-table {
    .el-table__header th {
      background-color: #f5f7fa;
      color: #303133;
      font-weight: 600;
      padding: 12px 0;
    }
    
    .el-table__body td {
      padding: 12px 0;
      
      .cell {
        display: flex;
        align-items: center;
        
        i {
          margin-right: 6px;
          color: #409EFF;
          font-size: 16px;
        }
      }
    }
    
    .el-table__row:hover {
      background-color: #f5f7fa;
    }
  }
  
  ::v-deep .el-pagination {
    margin-top: 20px;
  }
}
</style>

