<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-select v-model="query.departmentId" placeholder="请选择部门" clearable filterable>
                <el-option v-for="dept in departmentOptions" :key="dept.id" :label="dept.fullName" :value="dept.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>
              <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="NCC-common-layout-main NCC-flex-main">
        <NCC-table v-loading="listLoading" :data="list" has-c>
          <el-table-column prop="employeeName" label="员工姓名"  />
          <el-table-column prop="storeName" label="门店名称"  />
          <el-table-column prop="departmentName" label="部门名称"  />
          <el-table-column prop="inviteCount" label="邀请数"  >
            <template slot-scope="scope">
              <span class="clickable-cell" @click="handleInviteClick(scope.row)">
                {{ scope.row.inviteCount || 0 }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="appointmentCount" label="预约数"  >
            <template slot-scope="scope">
              <span class="clickable-cell" @click="handleAppointmentClick(scope.row)">
                {{ scope.row.appointmentCount || 0 }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="到店人数" label="到店人数"  >
            <template slot-scope="scope">
              <span class="clickable-cell" @click="handleVisitClick(scope.row)">
                {{ scope.row.visitCount || 0 }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="billingCount" label="开单数"  >
            <template slot-scope="scope">
              <span class="clickable-cell" @click="handleBillingClick(scope.row)">
                {{ scope.row.billingCount || 0 }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="billingAmount" label="开单金额"  >
            <template slot-scope="scope">
              <span class="amount-value">¥{{ formatMoney(scope.row.billingAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="consumeAmount" label="消耗金额"  >
            <template slot-scope="scope">
              <span class="amount-paid">¥{{ formatMoney(scope.row.consumeAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="headCount" label="人头数"  >
            <template slot-scope="scope">
              {{ scope.row.headCount || 0 }}
            </template>
          </el-table-column>
          <el-table-column prop="personCount" label="人次"  >
            <template slot-scope="scope">
              {{ scope.row.personCount || 0 }}
            </template>
          </el-table-column>
          <el-table-column prop="projectCount" label="项目数"  >
            <template slot-scope="scope">
              {{ scope.row.projectCount || 0 }}
            </template>
          </el-table-column>
        </NCC-table>

        <!-- 分页组件 -->
        <pagination 
          v-show="total > 0" 
          :total="total" 
          :page.sync="query.currentPage"
          :limit.sync="query.pageSize" 
          @pagination="search" 
        />
      </div>
    </div>
  </div>
</template>

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

export default {
  name: 'StoreOverallStatistics',
  components: {
    Pagination
  },
  data() {
    return {
      query: {
        storeId: undefined,
        departmentId: undefined,
        startTime: undefined,
        endTime: undefined,
        currentPage: 1,
        pageSize: 20
      },
      storeOptions: [],
      departmentOptions: [],
      list: [],
      total: 0,
      listLoading: false
    }
  },
  created() {
    this.setDefaultTimeRange()
    this.initStoreOptions()
    this.initDepartmentOptions()
    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)
      })
    },

    // 初始化部门选项
    initDepartmentOptions() {
      request({
        url: '/api/permission/Organize/96240625-934F-490B-8AA6-0BC775B18468/Department',
        method: 'GET'
      }).then(res => {
        // 将树形结构扁平化
        this.departmentOptions = res.data.list.map(item => ({
          id: item.id,
          fullName: item.fullName
        }))
      }).catch(err => {
        console.error('获取部门列表失败:', err)
      })
    },



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

      const params = {
        currentPage: this.query.currentPage,
        pageSize: this.query.pageSize
      }

      if (this.query.storeId) {
        params.StoreId = this.query.storeId
      }

      if (this.query.departmentId) {
        params.DepartmentId = this.query.departmentId
      }

      if (this.query.startTime) {
        params.StartTime = this.query.startTime
      }

      if (this.query.endTime) {
        params.EndTime = this.query.endTime
      }

      request({
        url: '/api/Extend/lqkdkdjlb/get-health-coach-statistics',
        method: 'GET',
        data: params
      }).then(res => {
        if (res.data && res.data.list) {
          this.list = res.data.list
          this.total = (res.data.pagination && res.data.pagination.total) || res.data.list.length || 0
        } else {
          this.list = []
          this.total = 0
        }
        this.listLoading = false
      }).catch(err => {
        console.error('查询失败:', err)
        this.$message({
          type: 'error',
          message: '查询失败，请重试',
          duration: 1500
        })
        this.listLoading = false
      })
    },

    // 重置查询条件
    reset() {
      this.query = {
        storeId: undefined,
        departmentId: undefined,
        startTime: undefined,
        endTime: undefined,
        currentPage: 1,
        pageSize: 20
      }
      this.setDefaultTimeRange()
      this.list = []
      this.total = 0
      this.search()
    },

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

    // 将时间字符串转换为时间戳（毫秒）
    getTimestamp(timeStr) {
      if (!timeStr) return ''
      return new Date(timeStr).getTime()
    },

    // 处理邀请数点击事件
    handleInviteClick(row) {
      if (row && row.employeeId) {
        this.$router.push({
          path: '/lqYaoyjl',
          query: {
            employeeId: row.employeeId,
            storeId: row.storeId || '',
            startTime: this.getTimestamp(this.query.startTime),
            endTime: this.getTimestamp(this.query.endTime),
          }
        })
      } else {
        this.$message({
          type: 'warning',
          message: '无法获取健康师ID',
          duration: 1500
        })
      }
    },

    // 处理预约数点击事件
    handleAppointmentClick(row) {
      if (row && row.employeeId) {
        this.$router.push({
          path: '/lqYyjl',
          query: {
            employeeId: row.employeeId,
            storeId: row.storeId || '',
            startTime: this.getTimestamp(this.query.startTime),
            endTime: this.getTimestamp(this.query.endTime),
          }
        })
      } else {
        this.$message({
          type: 'warning',
          message: '无法获取健康师ID',
          duration: 1500
        })
      }
    },

    // 处理到店人数点击事件
    handleVisitClick(row) {
      if (row && row.employeeId) {
        this.$router.push({
          path: '/lqYyjl',
          query: {
            employeeId: row.employeeId,
            storeId: row.storeId || '',
            startTime: this.getTimestamp(this.query.startTime),
            endTime: this.getTimestamp(this.query.endTime),
            type:'已确认'
          }
        })
      } else {
        this.$message({
          type: 'warning',
          message: '无法获取健康师ID',
          duration: 1500
        })
      }
    },

    // 处理开单数点击事件
    handleBillingClick(row) {
      if (row && row.employeeId) {
        this.$router.push({
          path: '/lqKdKdjlb',
          query: {
            employeeId: row.employeeId,
            storeId: row.storeId || '',
            startTime: this.getTimestamp(this.query.startTime),
            endTime: this.getTimestamp(this.query.endTime),
          }
        })
      } else {
        this.$message({
          type: 'warning',
          message: '无法获取健康师ID',
          duration: 1500
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.amount-value {
  color: #409EFF;
  font-weight: 500;
}

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

.clickable-cell {
  color: #409EFF;
  cursor: pointer;
  text-decoration: none;
  transition: all 0.3s;

  &:hover {
    color: #66b1ff;
    text-decoration: underline;
  }

  &:active {
    color: #3a8ee6;
  }
}
</style>

