<template>
  <el-dialog
    title="合同费用统计"
    :visible.sync="visible"
    width="900px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <!-- 查询条件 -->
    <el-form
      :model="queryForm"
      :inline="true"
      label-width="100px"
      label-position="right"
      style="margin-bottom: 20px"
    >
      <el-form-item label="门店" required>
        <el-select
          v-model="queryForm.storeId"
          placeholder="请选择门店"
          clearable
          filterable
          style="width: 200px"
        >
          <el-option
            v-for="store in storeList"
            :key="store.id"
            :label="store.fullName"
            :value="store.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="年份" required>
        <el-date-picker
          v-model="queryForm.year"
          type="year"
          placeholder="选择年份"
          format="yyyy"
          value-format="yyyy"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="月份" required>
        <el-select
          v-model="queryForm.month"
          placeholder="请选择月份"
          style="width: 200px"
        >
          <el-option
            v-for="m in 12"
            :key="m"
            :label="m + '月'"
            :value="m"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery" :loading="loading">
          查询
        </el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 统计结果 -->
    <div v-if="statisticsData" class="statistics-result">
      <!-- 总费用卡片 -->
      <div class="total-card">
        <div class="total-icon">
          <i class="el-icon-money"></i>
        </div>
        <div class="total-content">
          <div class="total-label">总费用</div>
          <div class="total-value">{{ formatMoney(statisticsData.totalAmount) }}</div>
          <div class="total-info">
            {{ statisticsData.storeName }} - {{ statisticsData.year }}年{{ statisticsData.month }}月
          </div>
        </div>
      </div>

      <!-- 按分类统计 -->
      <div v-if="statisticsData.categoryDetails && statisticsData.categoryDetails.length > 0" class="category-section">
        <h3>按分类统计</h3>
        <el-table
          :data="statisticsData.categoryDetails"
          border
          stripe
          style="margin-top: 12px"
        >
          <el-table-column
            prop="category"
            label="分类"
            width="150"
            align="center"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.category || '无' }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="amount"
            label="费用总额"
            width="150"
            align="right"
          >
            <template slot-scope="scope">
              <span style="color: #f56c6c; font-weight: 600;">
                {{ formatMoney(scope.row.amount) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="detailCount"
            label="明细数量"
            width="120"
            align="center"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.detailCount || 0 }} 条</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="100"
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="viewCategoryDetails(scope.row)"
              >
                查看明细
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 无数据提示 -->
      <el-empty
        v-else
        description="暂无统计数据"
        :image-size="100"
      />
    </div>

    <!-- 明细弹窗 -->
    <el-dialog
      title="费用明细"
      :visible.sync="detailDialogVisible"
      width="800px"
      append-to-body
    >
      <el-table
        :data="currentCategoryDetails"
        border
        stripe
        max-height="400"
      >
        <el-table-column
          prop="contractTitle"
          label="合同标题"
          min-width="150"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{ scope.row.contractTitle || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="category"
          label="分类"
          width="120"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.category || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="dueAmount"
          label="应缴金额"
          width="120"
          align="right"
        >
          <template slot-scope="scope">
            <span>{{ formatMoney(scope.row.dueAmount) || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="isPaid"
          label="缴费状态"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag :type="scope.row.isPaid === 1 ? 'success' : 'warning'">
              {{ scope.row.isPaid === 1 ? '已缴费' : '未缴费' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="actualPaymentAmount"
          label="实际缴费金额"
          width="140"
          align="right"
        >
          <template slot-scope="scope">
            <span>{{ formatMoney(scope.row.actualPaymentAmount) || '无' }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getExpenseStatistics } from '@/api/extend/contract'
import { getStoreSelector } from '@/api/extend/store'

export default {
  name: 'StatisticsDialog',
  data() {
    const currentYear = new Date().getFullYear()
    const currentMonth = new Date().getMonth() + 1

    return {
      visible: false,
      loading: false,
      storeList: [],
      statisticsData: null,
      detailDialogVisible: false,
      currentCategoryDetails: [],
      queryForm: {
        storeId: '',
        year: currentYear.toString(),
        month: currentMonth,
        categories: []
      }
    }
  },
  methods: {
    // 打开弹窗
    open() {
      this.visible = true
      this.loadStoreList()
      // 重置查询条件为当前年月
      const currentYear = new Date().getFullYear()
      const currentMonth = new Date().getMonth() + 1
      this.queryForm = {
        storeId: '',
        year: currentYear.toString(),
        month: currentMonth,
        categories: []
      }
      this.statisticsData = null
    },
    // 加载门店列表
    async loadStoreList() {
      try {
        const response = await getStoreSelector()
        if (response.code === 200 && response.data) {
          this.storeList = response.data.list || []
        }
      } catch (error) {
        console.error('获取门店列表失败:', error)
        this.storeList = []
      }
    },
    // 查询统计
    async handleQuery() {
      if (!this.queryForm.storeId) {
        this.$message.warning('请选择门店')
        return
      }
      if (!this.queryForm.year) {
        this.$message.warning('请选择年份')
        return
      }
      if (!this.queryForm.month) {
        this.$message.warning('请选择月份')
        return
      }

      this.loading = true
      try {
        const params = {
          storeId: this.queryForm.storeId,
          year: parseInt(this.queryForm.year),
          month: this.queryForm.month,
          categories: this.queryForm.categories.length > 0 ? this.queryForm.categories : undefined
        }

        const response = await getExpenseStatistics(params)

        if (response.code === 200 && response.data) {
          this.statisticsData = response.data
        } else {
          this.$message.error(response.msg || '获取统计数据失败')
          this.statisticsData = null
        }
      } catch (error) {
        console.error('获取统计数据失败:', error)
        this.$message.error('获取统计数据失败')
        this.statisticsData = null
      } finally {
        this.loading = false
      }
    },
    // 重置查询
    resetQuery() {
      const currentYear = new Date().getFullYear()
      const currentMonth = new Date().getMonth() + 1
      this.queryForm = {
        storeId: '',
        year: currentYear.toString(),
        month: currentMonth,
        categories: []
      }
      this.statisticsData = null
    },
    // 查看分类明细
    viewCategoryDetails(categoryData) {
      if (categoryData.details && categoryData.details.length > 0) {
        this.currentCategoryDetails = categoryData.details
        this.detailDialogVisible = true
      } else {
        this.$message.info('该分类暂无明细数据')
      }
    },
    // 关闭弹窗
    handleClose() {
      this.visible = false
      this.statisticsData = null
      this.detailDialogVisible = false
      this.currentCategoryDetails = []
    },
    // 格式化金额
    formatMoney(amount) {
      if (amount === null || amount === undefined) return '¥0.00'
      return '¥' + Number(amount).toFixed(2)
    }
  }
}
</script>

<style lang="scss" scoped>
.statistics-result {
  .total-card {
    display: flex;
    align-items: center;
    padding: 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 12px;
    margin-bottom: 20px;
    color: #fff;

    .total-icon {
      width: 80px;
      height: 80px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(255, 255, 255, 0.2);
      border-radius: 50%;
      margin-right: 20px;

      i {
        font-size: 40px;
      }
    }

    .total-content {
      flex: 1;

      .total-label {
        font-size: 14px;
        opacity: 0.9;
        margin-bottom: 8px;
      }

      .total-value {
        font-size: 32px;
        font-weight: 600;
        margin-bottom: 8px;
      }

      .total-info {
        font-size: 12px;
        opacity: 0.8;
      }
    }
  }

  .category-section {
    h3 {
      margin: 0 0 12px 0;
      color: #303133;
      font-size: 16px;
      font-weight: 600;
    }
  }
}

.dialog-footer {
  text-align: right;
}
</style>

