<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" v-if="activityInfo">
        <el-row :gutter="16">
          <el-col :span="24">
            <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">{{ activityInfo.ActivityName || '无' }}</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div> -->

      <!-- Tab切换 -->
      <el-tabs v-model="activeTab" @tab-click="handleTabClick" class="statistics-tabs">
        <!-- 门店Tab -->
        <el-tab-pane label="门店" name="store">
          <div class="table-section" v-loading="listLoading">
            <el-table
              :data="storeList"
              border
              style="width: 100%"
              stripe
              show-summary
              :summary-method="getStoreSummary">
              <el-table-column
                prop="StoreName"
                label="门店名称">
                <template slot-scope="scope">
                  <i class="el-icon-office-building"></i> {{ scope.row.StoreName || '无' }}
                </template>
              </el-table-column>
              <el-table-column
                prop="BillingCount"
                label="开单数量"
                >
                <template slot-scope="scope">
                  <i class="el-icon-shopping-bag-1"></i> {{ scope.row.BillingCount || 0 }}
                </template>
              </el-table-column>
              <el-table-column
                prop="BillingAmount"
                label="开单金额"
                >
                <template slot-scope="scope">
                  <i class="el-icon-money"></i> ¥{{ formatMoney(scope.row.BillingAmount) }}
                </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-column
                prop="CustomerCount"
                label="人头数"
                >
                <template slot-scope="scope">
                  <i class="el-icon-user"></i> {{ scope.row.CustomerCount || 0 }}
                </template>
              </el-table-column>
              <el-table-column
                prop="ItemCount"
                label="项目数"
                >
                <template slot-scope="scope">
                  <i class="el-icon-menu"></i> {{ scope.row.ItemCount || 0 }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 品项Tab -->
        <el-tab-pane label="品项" name="item">
          <div class="table-section" v-loading="listLoading">
            <el-table
              :data="itemList"
              border
              style="width: 100%"
              stripe
              show-summary
              :summary-method="getItemSummary">
              <el-table-column
                prop="ItemName"
                label="品项名称">
                <template slot-scope="scope">
                  <i class="el-icon-goods"></i> {{ scope.row.ItemName || '无' }}
                </template>
              </el-table-column>
              <el-table-column
                prop="SalesQuantity"
                label="销售数量"
                >
                <template slot-scope="scope">
                  <i class="el-icon-shopping-cart-2"></i> {{ scope.row.SalesQuantity || 0 }}
                </template>
              </el-table-column>
              <el-table-column
                prop="SalesAmount"
                label="销售金额"
                >
                <template slot-scope="scope">
                  <i class="el-icon-money"></i> ¥{{ formatMoney(scope.row.SalesAmount) }}
                </template>
              </el-table-column>
              <el-table-column
                prop="BillingCount"
                label="开单数量"
                >
                <template slot-scope="scope">
                  <i class="el-icon-shopping-bag-1"></i> {{ scope.row.BillingCount || 0 }}
                </template>
              </el-table-column>
              <el-table-column
                prop="SalesCount"
                label="销售次数"
                >
                <template slot-scope="scope">
                  <i class="el-icon-refresh"></i> {{ scope.row.SalesCount || 0 }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 门店品项Tab -->
        <el-tab-pane label="门店品项" name="storeItem">
          <div class="table-section" v-loading="listLoading">
            <el-table
              :data="storeItemList"
              border
              style="width: 100%"
              stripe
              row-key="id"
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
              default-expand-all
              show-summary
              :summary-method="getStoreItemSummary">
              <el-table-column
                prop="name"
                label="门店/品项名称"
                width="250">
                <template slot-scope="scope">
                  <div v-if="scope.row.isStore" class="store-name">
                    <i class="el-icon-office-building"></i> {{ scope.row.StoreName || '无' }}
                  </div>
                  <div v-else class="item-name">
                    <i class="el-icon-goods item-icon"></i>
                    <span>{{ scope.row.ItemName || '无' }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="SalesQuantity"
                label="销售数量"
                width="120">
                <template slot-scope="scope">
                  <span v-if="!scope.row.isStore">{{ scope.row.SalesQuantity || 0 }}</span>
                  <span v-else class="summary-text">{{ scope.row.SalesQuantity || 0 }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="SalesAmount"
                label="销售金额"
                width="120">
                <template slot-scope="scope">
                  <span v-if="!scope.row.isStore" class="amount-value">¥{{ formatMoney(scope.row.SalesAmount) }}</span>
                  <span v-else class="summary-text amount-value">¥{{ formatMoney(scope.row.SalesAmount) }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="BillingCount"
                label="开单数量"
                width="120">
                <template slot-scope="scope">
                  <span v-if="!scope.row.isStore">{{ scope.row.BillingCount || 0 }}</span>
                  <span v-else class="summary-text">{{ scope.row.BillingCount || 0 }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="SalesCount"
                label="销售次数"
                width="120">
                <template slot-scope="scope">
                  <span v-if="!scope.row.isStore">{{ scope.row.SalesCount || 0 }}</span>
                  <span v-else class="summary-text">{{ scope.row.SalesCount || 0 }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

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

export default {
  name: 'ActivityStatisticsDetail',
  data() {
    return {
      query: {
        activityId: '',
        startTime: undefined,
        endTime: undefined,
        storeIds: []
      },
      activityOptions: [],
      storeOptions: [],
      activityInfo: null,
      listLoading: false,
      activeTab: 'store',
      // 门店数据
      storeList: [],
      // 品项数据
      itemList: [],
      // 门店品项原始数据
      storeItemRawData: [],
      // 门店品项扁平化数据（用于表格显示）
      storeItemList: []
    }
  },
  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)
      })
    },

    // Tab切换
    handleTabClick(tab) {
      if (this.query.activityId) {
        this.search()
      }
    },

    // 查询数据
    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 || []
      }

      // 根据当前tab调用不同的接口
      if (this.activeTab === 'store') {
        this.loadStoreData(params)
      } else if (this.activeTab === 'item') {
        this.loadItemData(params)
      } else if (this.activeTab === 'storeItem') {
        this.loadStoreItemData(params)
      }
    },

    // 加载门店数据
    loadStoreData(params) {
      request({
        url: '/api/Extend/lqpackageinfo/get-activity-statistics-by-store',
        method: 'POST',
        data: params
      }).then(res => {
        if (res.data) {
          this.activityInfo = {
            ActivityId: res.data.ActivityId,
            ActivityName: res.data.ActivityName
          }
          this.storeList = res.data.StoreList || []
        } else {
          this.activityInfo = null
          this.storeList = []
        }
        this.listLoading = false
      }).catch(err => {
        console.error('查询门店数据失败:', err)
        this.$message({
          type: 'error',
          message: '查询失败，请重试',
          duration: 1500
        })
        this.listLoading = false
      })
    },

    // 加载品项数据
    loadItemData(params) {
      request({
        url: '/api/Extend/lqpackageinfo/get-activity-statistics-by-item',
        method: 'POST',
        data: params
      }).then(res => {
        if (res.data) {
          this.activityInfo = {
            ActivityId: res.data.ActivityId,
            ActivityName: res.data.ActivityName
          }
          this.itemList = res.data.ItemList || []
        } else {
          this.activityInfo = null
          this.itemList = []
        }
        this.listLoading = false
      }).catch(err => {
        console.error('查询品项数据失败:', err)
        this.$message({
          type: 'error',
          message: '查询失败，请重试',
          duration: 1500
        })
        this.listLoading = false
      })
    },

    // 加载门店品项数据
    loadStoreItemData(params) {
      request({
        url: '/api/Extend/lqpackageinfo/get-activity-statistics-by-store-item',
        method: 'POST',
        data: params
      }).then(res => {
        if (res.data) {
          this.activityInfo = {
            ActivityId: res.data.ActivityId,
            ActivityName: res.data.ActivityName
          }
          this.storeItemRawData = res.data.StoreList || []
          // 转换为树形结构
          this.convertToTreeData()
        } else {
          this.activityInfo = null
          this.storeItemRawData = []
          this.storeItemList = []
        }
        this.listLoading = false
      }).catch(err => {
        console.error('查询门店品项数据失败:', err)
        this.$message({
          type: 'error',
          message: '查询失败，请重试',
          duration: 1500
        })
        this.listLoading = false
      })
    },

    // 将门店品项数据转换为树形结构
    convertToTreeData() {
      this.storeItemList = []
      let idCounter = 1
      
      this.storeItemRawData.forEach(store => {
        // 创建门店节点（父节点）
        const storeNode = {
          id: `store_${idCounter++}`,
          isStore: true,
          StoreId: store.StoreId,
          StoreName: store.StoreName,
          children: [],
          // 门店合计字段（初始化为0）
          SalesQuantity: 0,
          SalesAmount: 0,
          BillingCount: 0,
          SalesCount: 0
        }
        
        // 如果有品项列表，创建品项子节点并计算合计
        if (store.ItemList && store.ItemList.length > 0) {
          store.ItemList.forEach(item => {
            const itemNode = {
              id: `item_${idCounter++}`,
              isStore: false,
              ItemId: item.ItemId,
              ItemName: item.ItemName,
              SalesQuantity: item.SalesQuantity || 0,
              SalesAmount: item.SalesAmount || 0,
              BillingCount: item.BillingCount || 0,
              SalesCount: item.SalesCount || 0
            }
            storeNode.children.push(itemNode)
            
            // 累加门店合计值
            storeNode.SalesQuantity += Number(itemNode.SalesQuantity) || 0
            storeNode.SalesAmount += Number(itemNode.SalesAmount) || 0
            storeNode.BillingCount += Number(itemNode.BillingCount) || 0
            storeNode.SalesCount += Number(itemNode.SalesCount) || 0
          })
        }
        
        // 如果门店有子节点或者即使没有子节点也显示门店
        if (storeNode.children.length > 0 || !store.ItemList || store.ItemList.length === 0) {
          this.storeItemList.push(storeNode)
        }
      })
    },

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

    // 门店表格合计方法
    getStoreSummary({ columns, data }) {
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          // 如果是金额字段，格式化显示
          if (column.property === 'BillingAmount' || column.property === 'DebtAmount') {
            sums[index] = '¥' + this.formatMoney(sums[index])
          }
        } else {
          sums[index] = '-'
        }
      })
      return sums
    },

    // 品项表格合计方法
    getItemSummary({ columns, data }) {
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          // 如果是金额字段，格式化显示
          if (column.property === 'SalesAmount') {
            sums[index] = '¥' + this.formatMoney(sums[index])
          }
        } else {
          sums[index] = '-'
        }
      })
      return sums
    },

    // 门店品项表格合计方法（树形表格，只合计品项数据，不包括门店行）
    getStoreItemSummary({ columns, data }) {
      const sums = []
      
      // 递归获取所有品项数据（不包括门店行）
      const getAllItems = (list) => {
        let items = []
        list.forEach(row => {
          if (!row.isStore && row.ItemName) {
            // 是品项行
            items.push(row)
          }
          if (row.children && row.children.length > 0) {
            // 递归处理子节点
            items = items.concat(getAllItems(row.children))
          }
        })
        return items
      }
      
      const allItems = getAllItems(data)
      
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        
        // 只对品项数据进行合计
        const values = allItems.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value)) && values.length > 0) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          // 如果是金额字段，格式化显示
          if (column.property === 'SalesAmount') {
            sums[index] = '¥' + this.formatMoney(sums[index])
          }
        } else {
          sums[index] = '-'
        }
      })
      return sums
    },

    // 格式化金额
    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);
    }
    
    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;
    }
  }
}

.statistics-tabs {
  margin-top: 20px;
  
  ::v-deep .el-tabs__header {
    background: #fff;
    padding: 0 20px;
    border-radius: 8px 8px 0 0;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    margin-bottom: 0;
  }
  
  ::v-deep .el-tabs__content {
    background: #fff;
    padding: 20px;
    border-radius: 0 0 8px 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  }
}

.table-section {
    max-height: 60vh;
    overflow-y: auto;
  ::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;
    }
    
    // 合计行样式
    .el-table__footer-wrapper {
      .el-table__footer {
        tbody td {
          background-color: #f0f9ff;
          color: #303133;
          font-weight: 600;
          padding: 12px 0;
        }
      }
    }
  }
}

// 展开行样式
.expand-container {
  padding: 16px;
  background: #fafafa;
  border-radius: 4px;
  margin: 8px 0;

  .expand-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 1px solid #e4e7ed;

    i {
      color: #409EFF;
      font-size: 16px;
    }
  }

  .item-name {
    display: flex;
    align-items: center;
    gap: 6px;

    .item-icon {
      color: #67C23A;
      font-size: 14px;
    }
  }

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

.store-name {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 600;
  color: #303133;
  
  i {
    color: #409EFF;
    font-size: 16px;
  }
}

.summary-text {
  color: #909399;
  font-style: italic;
}

.expand-empty {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 20px;
  color: #909399;
  font-size: 14px;

  i {
    font-size: 16px;
  }
}
</style>

