<template>
  <div class="dialog">
    <el-dialog
      :title="t('marketingApps.statistical')"
      width="80%"
      v-model="visible"
      :destroy-on-close="true"
      :close-on-click-modal="false" 
      draggable>
      <div class="dialog-body">
        <div class="statistics-table-wrapper">
          <el-row v-show="showSearch">
            <el-form :inline="true" :model="state.queryForm" @keyup.enter="withCollapsedChildren(getDataList)" ref="queryRef">
              <el-form-item :label="t('marketingApps.time')" prop="timeRange">
                <el-date-picker
                  :end-placeholder="$t('syslog.inputEndPlaceholderTip')"
                  :start-placeholder="$t('syslog.inputStartPlaceholderTip')"
                  range-separator="To"
                  type="datetimerange"
                  v-model="state.queryForm.timeRange"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :disabled-date="disabledDate"
                />
              </el-form-item>
            </el-form>
            <el-form-item>
              <el-button @click="withCollapsedChildren(getDataList)" type="primary" icon="Search">{{ t('common.queryBtn') }}</el-button>
            </el-form-item>
          </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 :formatter="statusFormatter" 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 :formatter="statusFormatter" :label="t('marketingApps.ip')" prop="ip" show-overflow-tooltip></el-table-column> -->
                    <el-table-column :formatter="statusFormatter" :label="t('marketingApps.fingerprint')" prop="fingerprint" show-overflow-tooltip></el-table-column>
                    <el-table-column :formatter="statusFormatter" :label="t('marketingApps.device')" prop="device" show-overflow-tooltip>
                      <template #default="{ row }">
                        系统类型：{{ statusFormatter('','',row.osType,'') }} <br>
                        系统版本：{{ statusFormatter('','',row.osVersion,'') }}
                      </template>
                    </el-table-column>
                    <el-table-column :formatter="statusFormatter" :label="t('marketingApps.browser')" prop="browser" show-overflow-tooltip>
                      <template #default="{ row }">
                        浏览器名称：{{ statusFormatter('','',row.browser,'') }} <br>
                        浏览器版本：{{ statusFormatter('','',row.browserVersion,'') }}
                      </template>
                    </el-table-column>
                    <el-table-column :formatter="statusFormatter" :label="t('marketingApps.firstAccessTime')" prop="firstTime" show-overflow-tooltip></el-table-column>
                    <el-table-column :formatter="statusFormatter" :label="t('marketingApps.lastAccessTime')" prop="lastTime" show-overflow-tooltip></el-table-column>
                    <el-table-column :formatter="statusFormatter" :label="t('marketingApps.lastVisitedPage')" prop="url" show-overflow-tooltip></el-table-column>
                    <el-table-column :formatter="statusFormatter" :label="t('marketingApps.accessVolume')" prop="count" 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 :formatter="statusFormatter" :label="t('marketingApps.IP')" prop="ip" show-overflow-tooltip></el-table-column>
            <el-table-column :formatter="statusFormatter" :label="t('marketingApps.firstAccessTime')" prop="firstTime" show-overflow-tooltip></el-table-column>
            <el-table-column :formatter="statusFormatter" :label="t('marketingApps.lastAccessTime')" prop="lastTime" show-overflow-tooltip></el-table-column>
            <el-table-column :formatter="statusFormatter" :label="t('marketingApps.accessSource')" prop="utmSource" show-overflow-tooltip></el-table-column>
            <el-table-column :formatter="statusFormatter" :label="t('marketingApps.lastVisitedPage')" prop="url" show-overflow-tooltip></el-table-column>
            <el-table-column :formatter="statusFormatter" :label="t('marketingApps.area')" prop="region" show-overflow-tooltip></el-table-column>
            <el-table-column :formatter="statusFormatter" :label="t('marketingApps.accessVolume')" prop="count" 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>
          <br>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watchEffect } from 'vue';
import { BasicTableProps, useTable } from '/@/hooks/table';
import { getStatPage, getStatSecondPage } from '/@/api/marketing/apps';
import { useI18n } from 'vue-i18n';
import dayjs from 'dayjs';

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

//  table hook
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {
    timeRange: [],
    appId: '',
  },
  pageList: getStatPage,
  createdIsNeed: false,
  pagination: {
    current: 1,
    size: 10,
    total: 0,
    pageSizes: [5, 10, 20, 50, 100]
  },
});

const { getDataList, currentChangeHandle, sortChangeHandle, sizeChangeHandle, tableStyle } = useTable(state);

// 打开弹窗
const openDialog = async (_row: any) => {
  visible.value = true;
  state.queryForm.appId = _row.appId;
  expandedRowKeys.value = [];
  getDataList();
};

const disabledDate = (time: Date) => {
  return time.getTime() > new Date().setHours(23, 59, 59, 999);
};

// 初始化二级表格数据和分页
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);
  })
})

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

/**
 * 关闭所有二级表格，后执行对应函数
 * @param callback 执行函数
 * @param args 执行函数的参数
 */
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);
  }
};

const statusFormatter = (row: any, column: any, cellValue: any, index: any) => {
  let unknownArray = ['unknown', 'Unknown', '未知'];
  if(unknownArray.includes(cellValue)) return '--';
  return cellValue || '--';
}

// 暴露变量 只有暴漏出来的变量 父组件才能使用
defineExpose({
  openDialog,
});

</script>
<style scoped lang="scss">
.dialog-body {
  padding: 0 0 10px 0;
  .statistics-table-wrapper {
    height: 70vh;
    position: relative;
    .child-table-container {
      margin: 20px;
    }
  }
}
</style>