<template>
  <div class="layout-padding" style="width: 100%;">
    <div class="layout-padding-auto layout-padding-view">
      <el-row class="ml10" v-show="showSearch">
        <el-form :inline="true" :model="state.queryForm" @keyup.enter="withCollapsedChildren(getDataList)" ref="queryRef">
          <el-form-item :label="t('systoken.ip')" prop="ip">
            <el-input :placeholder="t('systoken.inputIpTip')" v-model="state.queryForm.ip"></el-input>
          </el-form-item>
          <!-- <el-form-item :label="t('systoken.domain')" prop="domain">
            <el-input :placeholder="t('systoken.inputDomainTip')" v-model="state.queryForm.domain"></el-input>
          </el-form-item>
          <el-form-item :label="t('systoken.referrer')" prop="referrer">
            <el-input :placeholder="t('systoken.inputReferrer')" v-model="state.queryForm.referrer"></el-input>
          </el-form-item> -->
          <el-form-item>
            <el-button @click="withCollapsedChildren(getDataList)" icon="Search" type="primary">{{ t('common.queryBtn') }} </el-button>
            <el-button @click="resetQuery" icon="Refresh">{{ t('common.resetBtn') }}</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <el-table class="statistics-table" :data="state.dataList" row-key="ip" @sort-change="withCollapsedChildren(sortChangeHandle)" style="width: 100%"
        v-loading="state.loading" border :cell-style="tableStyle.cellStyle"
        :header-cell-style="tableStyle.headerCellStyle"
        :expand-row-keys="expandedRowKeys"
        @expand-change="handleExpandChange"
        >
        <!-- <el-table-column align="center" type="selection" width="40" /> -->
        <el-table-column show-overflow-tooltip type="expand">
          <template #default="{ row }">
            <div class="child-table-container">
              <el-table :data="row.childTableData" v-loading="row.childTableData.childLoading" border :cell-style="tableStyle.cellStyle"
                :header-cell-style="tableStyle.headerCellStyle">
                <!-- <el-table-column :label="t('systoken.ip')" prop="ip" show-overflow-tooltip></el-table-column> -->
                <el-table-column :label="t('systoken.domain')" prop="domain" show-overflow-tooltip></el-table-column>
                <el-table-column :label="t('systoken.fingerprint')" prop="fingerprint" show-overflow-tooltip></el-table-column>
                <el-table-column :label="t('systoken.referrer')" prop="referrer" show-overflow-tooltip></el-table-column>
                <el-table-column :label="t('systoken.content')" prop="total" show-overflow-tooltip></el-table-column>
                <el-table-column :label="t('systoken.dayActive')" prop="daily" show-overflow-tooltip></el-table-column>
                <el-table-column :label="t('systoken.hourActive')" prop="hourly" show-overflow-tooltip></el-table-column>
                <el-table-column :label="t('systoken.fifteenOnline')" prop="online" show-overflow-tooltip></el-table-column>
              </el-table>
              <div class="pagination-container" @click.stop>
                <pagination v-bind="row.childPagination"
                  :current-page="row.childPagination.page"
                  :page-size="row.childPagination.size"
                  :total="row.childPagination.total"
                  :key="`pagination-${row.ip}-${row.childPagination.page}`"
                  @size-change="size => handlePageSizeChange(row, size)"
                  @current-change="page => handlePageChange(row, page)" />
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="t('systoken.ip')" prop="ip" show-overflow-tooltip></el-table-column>
        <el-table-column :label="t('systoken.content')" prop="total" show-overflow-tooltip></el-table-column>
        <el-table-column :label="t('systoken.dayActive')" prop="daily" show-overflow-tooltip></el-table-column>
        <el-table-column :label="t('systoken.hourActive')" prop="hourly" show-overflow-tooltip></el-table-column>
        <el-table-column :label="t('systoken.fifteenOnline')" prop="online" show-overflow-tooltip></el-table-column>
      </el-table>

      <pagination 
        @current-change="page => withCollapsedChildren(currentChangeHandle, page)" 
        @size-change="size => withCollapsedChildren(sizeChangeHandle, size)" 
        v-bind="state.pagination">
      </pagination>
    </div>
  </div>
</template>

<script lang="ts" setup name="StatisticsIndex">
import { BasicTableProps, useTable } from '/@/hooks/table';
import { pageList, detailList } from '/@/api/marketing/statistics';
import { useI18n } from 'vue-i18n';
import { ref, reactive, watchEffect } from 'vue';

const { t } = useI18n();
// 定义变量内容
const queryRef = ref();
const showSearch = ref(true);
const expandedRowKeys = ref<number[]>([]); // 记录展开的行

// 接受props
const props = defineProps({
  row: {
    type: Object,
    default: () => ({})
  },
  type: {
    type: String,
    default: 'index'
  },
  appName: {
    type: String,
    default: ''
  }
});

//  table hook
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {
    ip: '',
    appId: props.row.id || '',
  },
  pageList: pageList,
  pagination: {
    current: 1,
    size: 10,
    total: 0,
    pageSizes: [5, 10, 20, 50, 100]
  }
});
const { getDataList, currentChangeHandle, sortChangeHandle, sizeChangeHandle, tableStyle } = useTable(state);

// 清空搜索条件
const resetQuery = () => {
  queryRef.value?.resetFields();
  withCollapsedChildren(getDataList);
};

// 初始化二级表格数据和分页
const initChildData = (parentRow) => {
  parentRow.expanded = false;
  parentRow.childTableData = []
  parentRow.childLoading = false;
  parentRow.childPagination = reactive({
    page: 1,
    size: 5,
    total: 0,
    pageSizes: [5, 10, 20, 50, 100]
  });
};

// 初始化所有二级表格数据
watchEffect(() => {
  state?.dataList?.forEach(row => {
    initChildData(row);
  })
}, [state.pageList])

// 获取二级表格数据
const loadChildData = async (parentRow) => {
  parentRow.childLoading = true;
  try {
    const res = await detailList({
      ip: parentRow.ip,
      current: parentRow.childPagination.page,
      size: parentRow.childPagination.size
    });
    const data = res.data;
    parentRow.childTableData = data.records;
    parentRow.childPagination.total = data.total;
  } finally {
    parentRow.childLoading = false;
  }
};

// 确保在请求数据前关闭所有二级表格
const withCollapsedChildren = (callback: Function, ...args: any[]) => {
  expandedRowKeys.value = [];
  return callback(...args);
};

// 处理二级表格分页大小变化
const handlePageSizeChange = (row: any, size: number) => {
  row.childPagination.size = size;
  row.childPagination.page = 1; // 重置为第一页
  loadChildData(row);
};

// 处理二级表格页码变化
const handlePageChange = (row: any, page: number) => {
  row.childPagination.page = page;
  loadChildData(row);
};

// 二级表格展开/关闭
const handleExpandChange = (row: any, expandedRows: any[]) => {
  expandedRowKeys.value = expandedRows.map(item => item.ip);
  row.expanded = !row.expanded;

  // 加载二级表格第1页数据
  if (row.expanded && (!row.childTableData || row.childTableData.length === 0)) {
    loadChildData(row);
  }
};

</script>

<style lang="scss">
// .statistics-table {
//   tr>.el-table__cell.el-table__expanded-cell {
//     padding-top: 0;
//   }
// }
.child-table-container {
  margin: 20px;
}
// .child-table-container {
//   margin: -1px 0 0 48px;

//   .el-table__header {
//     display: none;
//   }
// }
</style>