<template>
  <div class="firm-statistics-detail">

    <!-- 查询条件 -->
    <div class="query-section">
      <a-form layout="inline" :model="queryForm">
        <a-form-item label="年度">
          <a-select v-model:value="queryForm.year" placeholder="请选择年度" style="width: 120px">
            <a-select-option v-for="year in yearOptions" :key="year" :value="year">{{ year }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="季度">
          <a-select v-model:value="queryForm.quarter" placeholder="请选择季度" style="width: 120px">
            <a-select-option v-for="quarter in quarterOptions" :key="quarter.value" :value="quarter.value">{{ quarter.label }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="律所名称">
          <DepartmentTreeSelect v-model:value="queryForm.firmId" placeholder="请选择机构" style="width: 220px" />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleQuery" :loading="loading">
            <SearchOutlined />
            查询
          </a-button>
          <a-button @click="handleReset" style="margin-left: 8px;">
            <ReloadOutlined />
            重置
          </a-button>
        </a-form-item>
        <a-form-item style="margin-left: auto;">
          <a-button type="primary" @click="handleExport" :loading="exportLoading">
            <ExportOutlined />
            导出
          </a-button>
        </a-form-item>
      </a-form>
    </div>

    <!-- 统计报表 -->
    <div class="statistics-report-container">
      <!-- 报表标题 -->
    <div class="report-header">
      <h1>律师事务所律师参与公益法律服务统计表</h1>
      <div class="report-subtitle">统计时间：{{ queryForm.year }}年<span v-if="queryForm.quarter != null">第{{ queryForm.quarter }}季度</span></div>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-section">
      <a-spin size="large" />
      <div>正在加载数据...</div>
    </div>
    
    <!-- 报表表格 -->
    <div v-else class="report-table">
      <!-- 表头 -->
      <div class="report-row header-row">
        <div class="report-cell">序号</div>
        <div class="report-cell">律所名称</div>
        <div class="report-cell">律师名称</div>
        <div class="report-cell">执业证号</div>
        <div class="report-cell">季度累计服务时长</div>
        <div class="report-cell">季度累计服务成本</div>
        <div class="report-cell">年度累计服务时长</div>
        <div class="report-cell">年度累计服务成本</div>
      </div>
      
      <!-- 数据行 -->  
      <template v-for="(item, index) in tableData" :key="index">
        <!-- 律所数据行 -->
        <div class="report-row data-row">
          <div class="report-cell">{{ index + 1 }}</div>
          <div class="report-cell">
            <div class="firm-name-cell">
              <span @click="toggleExpand(index)" class="expand-icon" v-if="hasLawyerData(item)">
                <RightOutlined v-if="!expandedRows.has(index)" />
                <DownOutlined v-else />
              </span>
              {{ item.firmName || '-' }}
            </div>
          </div>
          <div class="report-cell">
              {{ item.certificateNumber || '-' }}
          </div>
          <div class="report-cell">{{ item.lawyerName || '-' }}</div>
          <div class="report-cell">{{ formatNumber(item.quarterlyServiceDuration) }}</div>
          <div class="report-cell">{{ formatCurrency(item.quarterlyServiceCost) }}</div>
          <!-- <div class="report-cell">0</div>-->
          <div class="report-cell">{{ formatNumber(item.annualServiceDuration) }}</div>
          <!-- <div class="report-cell">0</div>-->
          <div class="report-cell">{{ formatCurrency(item.annualServiceCost) }}</div>
        </div>
        
        <!-- 展开的律师数据行 -->
        <div v-if="expandedRows.has(index) && hasLawyerData(item)" class="expanded-content">
          <!-- 律师数据行 -->
          <div v-for="(lawyerItem, lawyerIndex) in item.lawyerServiceVOList" :key="`lawyer-${index}-${lawyerIndex}`" class="report-row lawyer-data-row">
            <div class="report-cell"></div>
            <div class="report-cell"></div>
            <div class="report-cell">{{ lawyerItem.lawyerName || '-' }}</div>
            <div class="report-cell">{{ lawyerItem.certificateNumber || '-' }}</div>
            <div class="report-cell">{{ formatNumber(lawyerItem.quarterlyServiceDuration) }}</div>
            <div class="report-cell">{{ formatCurrency(lawyerItem.quarterlyServiceCost) }}</div>
            <!--<div class="report-cell">0</div>-->
            <div class="report-cell">{{ formatNumber(lawyerItem.annualServiceDuration) }}</div>
            <!--<div class="report-cell">0</div>-->
            <div class="report-cell">{{ formatCurrency(lawyerItem.annualServiceCost) }}</div>
          </div>
        </div>
      </template>
        
        <!-- 汇总行 -->
        <div v-if="summaryData" class="report-row summary-row">
          <div class="report-cell">汇总</div>
          <div class="report-cell">-</div>
          <div class="report-cell">-</div>
          <div class="report-cell">-</div>
          <div class="report-cell">{{ formatNumber(summaryData.totalQuarterlyDuration) }}</div>
          <div class="report-cell">{{ formatCurrency(summaryData.totalQuarterlyCost) }}</div>
          <div class="report-cell">{{ formatNumber(summaryData.totalAnnualDuration) }}</div>
          <div class="report-cell">{{ formatCurrency(summaryData.totalAnnualCost) }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, reactive } from 'vue';
import { ExportOutlined, ArrowLeftOutlined, DownOutlined, RightOutlined, SearchOutlined, ReloadOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { serviceApplicationsApi } from '/@/api/business/service-applications/service-applications-api';
import DepartmentTreeSelect from '/@/components/system/department-tree-select/index.vue';

// 展开/折叠状态管理
const expandedRows = ref(new Set());

// 切换展开/折叠状态
function toggleExpand(index) {
  console.log(`切换第${index}行展开状态`);
  console.log(`当前展开状态:`, Array.from(expandedRows.value));
  
  if (expandedRows.value.has(index)) {
    expandedRows.value.delete(index);
  } else {
    expandedRows.value.add(index);
  }
  
  console.log(`切换后展开状态:`, Array.from(expandedRows.value));
  console.log(`第${index}行是否有律师数据:`, hasLawyerData(tableData.value[index]));
}

// 检查是否有律师数据
function hasLawyerData(item) {
  return item && item.lawyerServiceVOList && Array.isArray(item.lawyerServiceVOList) && item.lawyerServiceVOList.length > 0;
}

// 接收父组件传递的参数（可选）
const props = defineProps({
  params: {
    type: Object,
    default: null
  }
});

const exportLoading = ref(false);
const tableData = ref([]);
const loading = ref(false);

// 查询表单
const queryForm = reactive({
  year: new Date().getFullYear(),
  quarter: null,
  firmId: null
});

// 年度选项
const yearOptions = ref([]);
// 季度选项
const quarterOptions = ref([
  { value: 1, label: '第一季度' },
  { value: 2, label: '第二季度' },
  { value: 3, label: '第三季度' },
  { value: 4, label: '第四季度' }
]);

// 是否是CEO角色
const isCeo = ref(false);

// 初始化年度选项
function initYearOptions() {
  const currentYear = new Date().getFullYear();
  const years = [];
  for (let i = currentYear - 5; i <= currentYear + 1; i++) {
    years.push(i);
  }
  yearOptions.value = years;
}

// 查询按钮点击事件
async function handleQuery() {
  loading.value = true;
  try {
    const params = {
      year: queryForm.year,
      quarter: queryForm.quarter,
      firmId: queryForm.firmId || props.params?.firmId
    };
    
    const response = await serviceApplicationsApi.statisticsDepartment(params);
    tableData.value = response.data || [];
    
  } catch (error) {
    message.error('查询失败');
    console.error('查询失败:', error);
  } finally {
    loading.value = false;
  }
}

// 重置查询条件
function handleReset() {
  queryForm.quarter = null;
  queryForm.firmId = null;
  // 重置后自动查询
  handleQuery();
}

// 计算汇总数据
const summaryData = computed(() => {
  if (!tableData.value || tableData.value.length === 0) {
    return null;
  }

  const summary = {
    totalQuarterlyDuration: 0,
    totalQuarterlyCost: 0,
    totalAnnualDuration: 0,
    totalAnnualCost: 0
  };

  tableData.value.forEach(item => {
    summary.totalQuarterlyDuration += Number(item.quarterlyServiceDuration) || 0;
    summary.totalQuarterlyCost += Number(item.quarterlyServiceCost) || 0;
    summary.totalAnnualDuration += Number(item.annualServiceDuration) || 0;
    summary.totalAnnualCost += Number(item.annualServiceCost) || 0;
  });

  return summary;
});

// 格式化数字
function formatNumber(value) {
  if (value === null || value === undefined) return '-';
  const num = Number(value);
  return isNaN(num) ? '-' : num.toFixed(2);
}

// 格式化货币
function formatCurrency(value) {
  if (value === null || value === undefined) return '-';
  const num = Number(value);
  return isNaN(num) ? '-' : `¥${num.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')}`;
}

// 获取统计数据
async function fetchStatisticsData() {
  if (!props.params || !props.params.year) {
    tableData.value = [];
    return;
  }

  loading.value = true;
  try {
    const params = {
      year: props.params.year,
      quarter: props.params.quarter,
      firmId: props.params.firmId
    };
    
    // 调用API获取统计数据
    const response = await serviceApplicationsApi.statisticsDepartment(params);
    tableData.value = response.data || [];
    console.log('API返回的数据:', tableData.value);
    // 检查是否有律师数据
    tableData.value.forEach((item, index) => {
    });
  } catch (error) {
    message.error('获取统计数据失败');
    tableData.value = [];
  } finally {
    loading.value = false;
  }
}

// 导出Excel
async function handleExport() {
  if (!tableData.value || tableData.value.length === 0) {
    message.warning('暂无数据可导出');
    return;
  }

  exportLoading.value = true;
  try {
    console.log('开始导出律所统计详情...');
    const exportParams = {
      quarter: props.params.quarter,
      year: props.params.year,
      firmId: props.params.firmId
      // 去除分页参数，导出所有数据
    };
    
    await serviceApplicationsApi.exportLawyer(exportParams);
    message.success('导出成功');
    console.log('律所统计详情导出成功');
  } catch (error) {
    message.error('导出失败');
    console.error('律所统计详情导出失败:', error);
  } finally {
    exportLoading.value = false;
  }
}

// 监听参数变化，重新获取数据
watch(() => props.params, (newParams) => {
  if (newParams) {
    fetchStatisticsData();
  }
}, { immediate: true, deep: true });

onMounted(() => {
  console.log('律所统计详情组件已加载，参数:', props.params);
  initYearOptions();
  // 如果有父组件传递的参数，同步到查询表单
  if (props.params) {
    if (props.params.year) {
      queryForm.year = props.params.year;
    }
    if (props.params.quarter !== undefined) {
      queryForm.quarter = props.params.quarter;
    }
    if (props.params.firmId) {
      queryForm.firmId = props.params.firmId;
    }
  }
  // 自动查询
  handleQuery();
});
</script>
<style scoped>
.firm-statistics-detail {
  padding: 0 16px;
}

.detail-header {
  margin-bottom: 20px;
  padding: 16px 0;
}

.back-btn {
  color: #1e3a8a;
}

.query-section {
  margin-bottom: 20px;
  padding: 16px;
  background: #f5f5f5;
  border-radius: 4px;
}

.query-section :deep(.ant-form) {
  display: flex;
  align-items: center;
  width: 100%;
}

.query-section :deep(.ant-form-item:last-child) {
  margin-left: auto;
}

.export-section {
  display: none;
}

.statistics-report-container {
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
}

.report-header {
  background: #f5f5f5;
  padding: 20px;
  text-align: center;
  border-bottom: 1px solid #ddd;
}

.report-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #333;
  font-weight: 600;
}

.report-subtitle {
  font-size: 14px;
  color: #666;
}

.loading-section {
  padding: 60px 20px;
  text-align: center;
  background: #fff;
}

.loading-section div:last-child {
  margin-top: 16px;
  color: #666;
}

.report-table {
  width: 100%;
  border-collapse: collapse;
}

.report-row {
  display: flex;
  width: 100%;
}

.report-cell {
  padding: 12px;
  border-right: 1px solid #ddd;
  border-bottom: 1px solid #ddd;
  text-align: center;
  min-height: 50px;
  box-sizing: border-box;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 所有列平分宽度 */
.report-cell {
  flex: 1;
  min-width: 0;
}

.report-cell:last-child {
  border-right: none;
}

.header-row {
  background-color: #0044cc;
  color: white;
  font-weight: 600;
}

.data-row {
  background-color: white;
  color: #333;
}

.summary-row {
  background-color: #f0f0f0;
  color: #333;
  font-weight: 600;
}

/* 最后一行单元格没有下边框 */
.report-row:last-child .report-cell {
  border-bottom: none;
}

/* 展开/折叠功能样式 */
.firm-name-cell {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.expand-icon {
  cursor: pointer;
  margin-right: 8px;
  color: #1890ff;
  font-size: 12px;
  width: 16px;
  height: 16px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

/* 展开内容样式 */
.expanded-content {
  display: block !important;
  padding: 0;
  margin: 0;
  background: white;
  border: none;
  border-radius: 0;
}

/* 律师数据行样式 */
.lawyer-data-row {
  background-color: white;
  border-left: none;
}

.lawyer-data-row:hover {
  background-color: #f9f9f9;
}

/* 律师数据行标题样式 */
.lawyer-header-row {
  background-color: #f0f0f0;
  color: #333;
  font-weight: 600;
  border-bottom: 1px solid #ddd;
}
</style>