<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="6">
            <el-form-item label="门店">
              <el-select v-model="query.storeId" placeholder="请选择门店" clearable filterable>
                <el-option v-for="store in storeOptions" :key="store.id" :label="store.dm" :value="store.id" />
              </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.itemId"
                placeholder="请选择品项"
                clearable
                filterable
                :style='{"width":"100%"}'>
                <el-option
                  v-for="item in itemOptions"
                  :key="item.id"
                  :label="item.xmmc"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <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-if="summaryData">
        <el-row :gutter="16">
          <el-col :span="6">
            <div class="statistics-card">
              <div class="card-icon">
                <i class="el-icon-goods"></i>
              </div>
              <div class="card-content">
                <div class="card-title">品项总数</div>
                <div class="card-value">{{ summaryData.totalItems || 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(summaryData.totalBillingAmount) }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="statistics-card">
              <div class="card-icon">
                <i class="el-icon-user"></i>
              </div>
              <div class="card-content">
                <div class="card-title">购买人次</div>
                <div class="card-value">{{ summaryData.totalBuyers || 0 }}</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">¥{{ formatMoney(summaryData.totalRefundAmount) }}</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 数据表格 -->
      <div class="NCC-common-layout-main NCC-flex-main">
        <NCC-table v-loading="listLoading" :data="list" has-c>
          <el-table-column prop="ItemNumber" label="品项编号" align="left" width="120" />
          <el-table-column prop="ItemName" label="品项名称" align="left" min-width="150">
            <template slot-scope="scope">
              <span class="item-name-link" @click="handleItemNameClick(scope.row)">
                <i class="el-icon-goods" style="margin-right: 4px; color: #409EFF;"></i>
                {{ scope.row.ItemName || '无' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="BillingAmount" label="开单金额" align="right" width="120">
            <template slot-scope="scope">
              <span class="amount-value">¥{{ formatMoney(scope.row.BillingAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="BillingAmountRatio" label="开单占比" align="right" width="110">
            <template slot-scope="scope">
              {{ formatPercent(scope.row.BillingAmountRatio) }}%
            </template>
          </el-table-column>
          <el-table-column prop="TotalBuyers" label="购买人数" align="right" width="100" />
          <el-table-column prop="ItemRatio" label="人次占比" align="right" width="110">
            <template slot-scope="scope">
              {{ formatPercent(scope.row.ItemRatio) }}%
            </template>
          </el-table-column>
          <el-table-column prop="RepeatBuyers" label="复购人数" align="right" width="100" />
          <el-table-column prop="RepeatBuyRate" label="复购率" align="right" width="100">
            <template slot-scope="scope">
              {{ formatPercent(scope.row.RepeatBuyRate) }}%
            </template>
          </el-table-column>
          <el-table-column prop="ConsumeAmount" label="耗卡金额" align="right" width="120">
            <template slot-scope="scope">
              <span class="amount-paid">¥{{ formatMoney(scope.row.ConsumeAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="ConsumeAmountRatio" label="耗卡占比" align="right" width="110">
            <template slot-scope="scope">
              {{ formatPercent(scope.row.ConsumeAmountRatio) }}%
            </template>
          </el-table-column>
          <el-table-column prop="ConsumePurchaseCount" label="购买耗卡次数" align="right" width="140" />
          <el-table-column prop="ConsumeGiftCount" label="赠送耗卡次数" align="right" width="140" />
          <el-table-column prop="ConsumeExperienceCount" label="体验耗卡次数" align="right" width="140" />
          <el-table-column prop="RefundAmount" label="退款金额" align="right" width="120">
            <template slot-scope="scope">
              <span class="amount-debt">¥{{ formatMoney(scope.row.RefundAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="RefundCount" label="退款次数" align="right" width="100">
            <template slot-scope="scope">
              {{ scope.row.RefundCount || 0 }}
            </template>
          </el-table-column>
        </NCC-table>
      </div>
    </div>

    <!-- 门店统计详情弹窗 -->
    <store-statistics-dialog
      :visible="dialogVisible"
      :item-id="currentItemId"
      :start-time="query.startTime"
      :end-time="query.endTime"
      @close="dialogVisible = false"
    />
  </div>
</template>

<script>
import request from '@/utils/request'
import StoreStatisticsDialog from './components/store-statistics-dialog.vue'

export default {
  name: 'ItemStatistics',
  components: {
    StoreStatisticsDialog
  },
  data() {
    return {
      query: {
        storeId: undefined,
        startTime: undefined,
        endTime: undefined,
        itemId: undefined
      },
      storeOptions: [],
      itemOptions: [],
      summaryData: null,
      list: [],
      listLoading: false,
      dialogVisible: false,
      currentItemId: null
    }
  },
  created() {
    this.setDefaultTimeRange()
    this.initStoreOptions()
    this.initItemOptions()
    this.search()
  },
  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())
    },

    // 初始化门店选项
    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)
      })
    },

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

    // 查询数据
    search() {
      this.listLoading = true

      const params = {}

      if (this.query.storeId) {
        params.storeId = this.query.storeId
      }
      
      if (this.query.startTime) {
        params.startTime = this.query.startTime
      }
      
      if (this.query.endTime) {
        params.endTime = this.query.endTime
      }

      if (this.query.itemId) {
        params.itemId = this.query.itemId
      }

      request({
        url: '/api/Extend/lqxmzl/GetItemStatistics',
        method: 'POST',
        data: params
      }).then(res => {
        if (res.data && res.data.data) {
          this.list = res.data.data
          this.calculateSummary()
        } else {
          this.list = []
          this.summaryData = null
        }
        this.listLoading = false
      }).catch(err => {
        console.error('查询失败:', err)
        this.$message({
          type: 'error',
          message: '查询失败，请重试',
          duration: 1500
        })
        this.listLoading = false
      })
    },

    // 计算汇总数据
    calculateSummary() {
      if (!this.list || this.list.length === 0) {
        this.summaryData = null
        return
      }

      const summary = {
        totalItems: this.list.length,
        totalBillingAmount: this.list.reduce((sum, item) => sum + (item.BillingAmount || 0), 0),
        totalBuyers: this.list.reduce((sum, item) => sum + (item.TotalBuyers || 0), 0),
        totalRefundAmount: this.list.reduce((sum, item) => sum + (item.RefundAmount || 0), 0)
      }

      this.summaryData = summary
    },

    // 重置查询条件
    reset() {
      this.query = {
        storeId: undefined,
        startTime: undefined,
        endTime: undefined,
        itemId: undefined
      }
      this.setDefaultTimeRange()
      this.summaryData = null
      this.list = []
      this.search()
    },

    // 格式化金额
    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}`
    },

    // 点击品项名称
    handleItemNameClick(row) {
      if (!row.ItemId) {
        this.$message({
          type: 'warning',
          message: '品项ID不存在',
          duration: 1500
        })
        return
      }

      if (!this.query.startTime || !this.query.endTime) {
        this.$message({
          type: 'warning',
          message: '请先选择开始时间和结束时间',
          duration: 1500
        })
        return
      }

      this.currentItemId = row.ItemId
      this.dialogVisible = true
    }
  }
}
</script>

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

.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: 24px;
      font-weight: bold;
      color: #303133;
    }
  }
}

.amount-value {
  color: #409EFF;
  font-weight: 500;
}

.amount-paid {
  color: #67C23A;
  font-weight: 500;
}

.amount-debt {
  color: #F56C6C;
  font-weight: 500;
}

.item-name-link {
  color: #409EFF;
  cursor: pointer;
  transition: color 0.3s;
  
  &:hover {
    color: #66b1ff;
    text-decoration: underline;
  }
}
</style>

