<template>
  <div class="app-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton animated>
        <template #template>
          <el-skeleton-item variant="image" style="width: 100%; height: 400px;" />
        </template>
      </el-skeleton>
    </div>

    <!-- 有权限时显示租户模块用量统计 -->
    <div v-else-if="hasDashboardPermission" class="module-usage-dashboard">
      <!-- 顶部统计卡片 -->
      <el-row :gutter="16" class="summary-row">
        <el-col :span="4">
          <div class="summary-card">
            <div class="summary-label">租户总数</div>
            <div class="summary-value primary">{{ summary.tenantCount }}</div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="summary-card">
            <div class="summary-label">员工总数</div>
            <div class="summary-value success">{{ summary.employeeCount }}</div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="summary-card">
            <div class="summary-label">外呼总次数</div>
            <div class="summary-value warning">{{ summary.callCount }}</div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="summary-card">
            <div class="summary-label">短信总条数</div>
            <div class="summary-value info">{{ summary.smsCount }}</div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="summary-card">
            <div class="summary-label">总消费额</div>
            <div class="summary-value danger">¥{{ summary.totalConsume }}</div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="summary-card">
            <div class="summary-label">活跃模块数</div>
            <div class="summary-value primary">{{ summary.activeModules }}</div>
          </div>
        </el-col>
      </el-row>

      <!-- 搜索栏 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form" label-width="80px">
        <el-form-item label="租户名称" prop="tenantName">
          <el-input v-model="queryParams.tenantName" placeholder="请输入租户名称" clearable size="small" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="统计日期" prop="statDate">
          <el-date-picker v-model="queryParams.statDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择日期" clearable size="small" style="width:160px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 租户用量表格 -->
      <el-table border v-loading="tableLoading" :data="list" style="width:100%" size="small">
        <el-table-column label="租户名称" align="center" prop="tenantName" width="140" fixed="left" />
        <el-table-column label="归属代理" align="center" prop="proxyName" width="120" />
        <el-table-column label="统计日期" align="center" prop="statDate" width="105" />
        <el-table-column label="部门数" align="center" prop="deptCount" width="70" />
        <el-table-column label="员工数" align="center" prop="employeeCount" width="70" />
        <el-table-column label="外呼次数" align="center" prop="outboundCallCount" width="80" />
        <el-table-column label="短信发送" align="center" prop="smsSentCount" width="85" />
        <el-table-column label="个微用户" align="center" prop="wxUserCount" width="85" />
        <el-table-column label="企微用户" align="center" prop="qwUserCount" width="85" />
        <el-table-column label="SOP数" align="center" prop="sopCount" width="65" />
        <el-table-column label="课程数" align="center" prop="courseCount" width="70" />
        <el-table-column label="直播次" align="center" prop="liveCount" width="70" />
        <el-table-column label="商品数" align="center" prop="productCount" width="70" />
        <el-table-column label="工作流" align="center" prop="workflowCount" width="70" />
        <el-table-column label="龙虾模板" align="center" prop="lobsterTemplateCount" width="80" />
        <el-table-column label="龙虾任务" align="center" prop="lobsterTaskCount" width="80" />
        <el-table-column label="活跃模块" align="center" prop="activeModuleCount" width="80">
          <template slot-scope="scope">
            <el-tag :type="scope.row.activeModuleCount > 5 ? 'success' : 'warning'" size="mini">
              {{ scope.row.activeModuleCount || 0 }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="当月消费" align="center" prop="totalConsumeAmount" width="110" fixed="right">
          <template slot-scope="scope">¥{{ scope.row.totalConsumeAmount || '0.00' }}</template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="70" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

      <!-- 详情弹窗 -->
      <el-dialog title="租户用量详情" :visible.sync="detailVisible" width="700px">
        <el-descriptions :column="3" border>
          <el-descriptions-item label="租户名称">{{ detail.tenantName }}</el-descriptions-item>
          <el-descriptions-item label="归属代理">{{ detail.proxyName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="统计日期">{{ detail.statDate }}</el-descriptions-item>
          <el-descriptions-item label="部门数量">{{ detail.deptCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="员工数量">{{ detail.employeeCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="外呼次数">{{ detail.outboundCallCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="短信发送量">{{ detail.smsSentCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="个微用户数">{{ detail.wxUserCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="个微绑定数">{{ detail.wxAccountCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="个微客户数">{{ detail.wxCustomerCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="企微用户数">{{ detail.qwUserCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="企微绑定数">{{ detail.qwAccountCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="SOP数量">{{ detail.sopCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="课程数量">{{ detail.courseCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="直播次数">{{ detail.liveCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="商品数量">{{ detail.productCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="订单数量">{{ detail.orderCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="工作流数量">{{ detail.workflowCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="龙虾模板数">{{ detail.lobsterTemplateCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="龙虾任务数">{{ detail.lobsterTaskCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="活跃模块数">
            <el-tag type="success" size="small">{{ detail.activeModuleCount || 0 }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="当月消费总额">¥{{ detail.totalConsumeAmount || '0.00' }}</el-descriptions-item>
        </el-descriptions>
      </el-dialog>
    </div>

    <!-- 无权限时显示欢迎页面 -->
    <welcome-page v-else />
  </div>
</template>

<script>
import { listModuleUsage, getTenantDetail } from '@/api/admin/moduleUsage'
const WelcomePage = () => import('./components/index/welcomePage')

export default {
  name: 'Index',
  components: {
    WelcomePage
  },
  data() {
    return {
      hasDashboardPermission: false,
      loading: true,
      tableLoading: false,
      list: [],
      total: 0,
      detailVisible: false,
      detail: {},
      summary: {
        tenantCount: 0,
        employeeCount: 0,
        callCount: 0,
        smsCount: 0,
        totalConsume: '0.00',
        activeModules: 0
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tenantName: null,
        statDate: null
      }
    }
  },
  created() {
    this.checkDashboardPermission()
  },
  methods: {
    checkDashboardPermission() {
      if (this.hasPermi(['his:index'])) {
        this.hasDashboardPermission = true
      } else if (this.hasRole(['admin'])) {
        this.hasDashboardPermission = true
      }
      this.loading = false

      if (this.hasDashboardPermission) {
        this.$nextTick(() => {
          this.getList()
        })
      }
    },

    getList() {
      this.tableLoading = true
      listModuleUsage(this.queryParams).then(res => {
        this.list = res.rows || []
        this.total = res.total || 0
        this.tableLoading = false
        this.computeSummary()
      }).catch(() => { this.tableLoading = false })
    },

    computeSummary() {
      // 从当前列表计算摘要（也可从后端单独获取汇总数据）
      const all = this.list
      this.summary.tenantCount = all.length
      this.summary.employeeCount = all.reduce((s, r) => s + (r.employeeCount || 0), 0)
      this.summary.callCount = all.reduce((s, r) => s + (r.outboundCallCount || 0), 0)
      this.summary.smsCount = all.reduce((s, r) => s + (r.smsSentCount || 0), 0)
      const totalConsume = all.reduce((s, r) => s + (parseFloat(r.totalConsumeAmount) || 0), 0)
      this.summary.totalConsume = totalConsume.toFixed(2)
      this.summary.activeModules = all.reduce((s, r) => s + (r.activeModuleCount || 0), 0)
    },

    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },

    handleDetail(row) {
      getTenantDetail(row.tenantId).then(res => {
        this.detail = res.data || {}
        this.detailVisible = true
      })
    },

    hasPermi(permissions) {
      return this.$store.state.user.permissions.some(permission => {
        return permissions.includes(permission)
      })
    },

    hasRole(roles) {
      return this.$store.state.user.roles.some(role => {
        return roles.includes(role)
      })
    }
  }
}
</script>

<style scoped>
.app-container {
  min-height: calc(100vh - 84px);
  padding: 16px;
  background: #f5f7fa;
}

.loading-container {
  padding: 20px;
}

.module-usage-dashboard {
  background: #fff;
  border-radius: 4px;
  padding: 16px 16px 4px;
}

.summary-row {
  margin-bottom: 16px;
}

.summary-card {
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  padding: 16px 12px;
  text-align: center;
  transition: all 0.3s;
}
.summary-card:hover {
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
  transform: translateY(-1px);
}

.summary-label {
  font-size: 13px;
  color: #909399;
  margin-bottom: 8px;
}

.summary-value {
  font-size: 22px;
  font-weight: 700;
}
.summary-value.primary { color: #409EFF; }
.summary-value.success { color: #67C23A; }
.summary-value.warning { color: #E6A23C; }
.summary-value.info   { color: #909399; }
.summary-value.danger { color: #F56C6C; }

.search-form {
  padding: 12px 0 4px;
  border-top: 1px solid #f0f0f0;
}
</style>
