<script setup lang="ts">
import { reactive, ref, onMounted, toRaw } from 'vue';
import { PageContainer } from 'antdv-pro-layout';
import { SizeType } from 'ant-design-vue/lib/config-provider';
import { ColumnsType } from 'ant-design-vue/lib/table';
import { parseDateToStr } from '@/utils/date-utils';
import { getNeFile, listNeFiles } from '@/api/tool/neFile';
import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';
import useNeInfoStore from '@/store/modules/neinfo';
import useI18n from '@/hooks/useI18n';
import { Modal, message } from 'ant-design-vue/lib';
import saveAs from 'file-saver';
import { useRoute } from 'vue-router';
const neInfoStore = useNeInfoStore();
const { t } = useI18n();
const route = useRoute();

// 获取地址栏参数
const routeParams = route.query as Record<string, any>;

/**网元参数 */
let neType = ref<string[]>([]);
/**下载触发等待 */
let loading = ref(false);
/**访问路径 */
let nePathArr = ref<string[]>([]);

/**查询参数 */
let queryParams = reactive({
  /**网元类型 */
  neType: '',
  neId: '',
  /**读取路径 */
  path: '',
  /**前缀过滤 */
  search: '',
  /**当前页数 */
  pageNum: 1,
  /**每页条数 */
  pageSize: 20,
});

/**表格状态类型 */
type TabeStateType = {
  /**加载等待 */
  loading: boolean;
  /**紧凑型 */
  size: SizeType;
  /**记录数据 */
  data: object[];
};

/**表格状态 */
let tableState: TabeStateType = reactive({
  loading: false,
  size: 'small',
  data: [],
});

/**表格字段列 */
let tableColumns: ColumnsType = [
  {
    title: t('views.logManage.neFile.fileMode'),
    dataIndex: 'fileMode',
    align: 'center',
    width: 150,
  },
  {
    title: t('views.logManage.neFile.owner'),
    dataIndex: 'owner',
    align: 'left',
    width: 100,
  },
  {
    title: t('views.logManage.neFile.group'),
    dataIndex: 'group',
    align: 'left',
    width: 100,
  },
  {
    title: t('views.logManage.neFile.size'),
    dataIndex: 'size',
    align: 'left',
    width: 100,
  },
  {
    title: t('views.logManage.neFile.modifiedTime'),
    dataIndex: 'modifiedTime',
    align: 'left',
    customRender(opt) {
      if (!opt.value) return '';
      return parseDateToStr(opt.value * 1000);
    },
    width: 150,
  },
  {
    title: t('views.logManage.neFile.fileName'),
    dataIndex: 'fileName',
    align: 'left',
  },
  {
    title: t('common.operate'),
    key: 'fileName',
    align: 'center',
    width: 100,
  },
];

/**表格分页器参数 */
let tablePagination = reactive({
  /**当前页数 */
  current: 1,
  /**每页条数 */
  pageSize: 20,
  /**默认的每页条数 */
  defaultPageSize: 20,
  /**指定每页可以显示多少条 */
  pageSizeOptions: ['10', '20', '50', '100'],
  /**只有一页时是否隐藏分页器 */
  hideOnSinglePage: false,
  /**是否可以快速跳转至某页 */
  showQuickJumper: true,
  /**是否可以改变 pageSize */
  showSizeChanger: true,
  /**数据总数 */
  total: 0,
  showTotal: (total: number) => t('common.tablePaginationTotal', { total }),
  onChange: (page: number, pageSize: number) => {
    tablePagination.current = page;
    tablePagination.pageSize = pageSize;
    queryParams.pageNum = page;
    queryParams.pageSize = pageSize;
    fnGetList();
  },
});

/**信息文件下载 */
function fnDownloadFile(row: Record<string, any>) {
  if (loading.value) return;
  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('views.logManage.neFile.downTip', { fileName: row.fileName }),
    onOk() {
      loading.value = true;
      const hide = message.loading(t('common.loading'), 0);
      getNeFile({
        neType: queryParams.neType,
        neId: queryParams.neId,
        path: queryParams.path,
        fileName: row.fileName,
      })
        .then(res => {
          if (res.code === RESULT_CODE_SUCCESS) {
            message.success({
              content: t('common.msgSuccess', {
                msg: t('common.downloadText'),
              }),
              duration: 2,
            });
            saveAs(res.data, `${row.fileName}`);
          } else {
            message.error({
              content: t('views.logManage.neFile.downTipErr'),
              duration: 2,
            });
          }
        })
        .finally(() => {
          hide();
          loading.value = false;
        });
    },
  });
}

/**进入目录 */
function fnDirCD(dir: string, index?: number) {
  if (index === undefined) {
    nePathArr.value.push(dir);
    queryParams.search = '';
    fnGetList(1);
    return;
  }
  if (index === 0) {
    const neType = queryParams.neType;
    if (neType === 'IMS') {
      nePathArr.value = ['/var/log/ims'];
      queryParams.search = '';
    } else {
      nePathArr.value = ['/var/log'];
      queryParams.search = neType.toLowerCase();
    }
    fnGetList(1);
  } else {
    nePathArr.value = nePathArr.value.slice(0, index + 1);
    queryParams.search = '';
    fnGetList(1);
  }
}

/**网元类型选择对应修改 */
function fnNeChange(keys: any, _: any) {
  // 不是同类型时需要重新加载
  if (Array.isArray(keys) && queryParams.neType !== keys[0]) {
    const neType = keys[0];
    queryParams.neType = neType;
    queryParams.neId = keys[1];
    if (neType === 'IMS') {
      nePathArr.value = ['/var/log/ims'];
      queryParams.search = '';
    } else {
      nePathArr.value = ['/var/log'];
      queryParams.search = neType.toLowerCase();
    }
    fnGetList(1);
  }
}

/**查询备份信息列表, pageNum初始页数 */
function fnGetList(pageNum?: number) {
  if (queryParams.neId === '') {
    message.warning({
      content: t('views.logManage.neFile.neTypePlease'),
      duration: 2,
    });
    return;
  }
  if (tableState.loading) return;
  tableState.loading = true;
  if (pageNum) {
    queryParams.pageNum = pageNum;
  }
  queryParams.path = nePathArr.value.join('/');
  listNeFiles(toRaw(queryParams)).then(res => {
    if (res.code === RESULT_CODE_SUCCESS && Array.isArray(res.rows)) {
      tablePagination.total = res.total;
      tableState.data = res.rows;
      if (tablePagination.total <=(queryParams.pageNum - 1) * tablePagination.pageSize &&queryParams.pageNum !== 1) {
        tableState.loading = false;
        fnGetList(queryParams.pageNum - 1);
      }
    }
    tableState.loading = false;
  });
}

onMounted(() => {
  // 获取网元网元列表
  neInfoStore.fnNelist().then(res => {
    if (res.code === RESULT_CODE_SUCCESS && Array.isArray(res.data)) {
      if (res.data.length === 0) {
        message.warning({
          content: t('common.noData'),
          duration: 2,
        });
      } else if (routeParams.neType) { 
        neType.value = [routeParams.neType, routeParams.neId]
        fnNeChange(neType.value, undefined);
      }
    }
  });
});
</script>

<template>
  <PageContainer>
    <a-card :bordered="false" :body-style="{ padding: '0px' }">
      <!-- 插槽-卡片左侧侧 -->
      <template #title>
        <a-form :model="queryParams" name="queryParams" layout="horizontal">
          <a-row :gutter="16">
            <a-col :lg="8" :md="12" :xs="24">
              <a-form-item
                :label="t('views.logManage.neFile.neType')"
                name="neType"
                style="margin-bottom: 0"
              >
                <a-cascader
                  v-model:value="neType"
                  :options="neInfoStore.getNeCascaderOptions"
                  @change="fnNeChange"
                  :allow-clear="false"
                  :placeholder="t('views.logManage.neFile.neTypePlease')"
                  :disabled="loading || tableState.loading"
                />
              </a-form-item>
            </a-col>
            <a-col :lg="16" :md="18" :xs="24" v-if="nePathArr.length > 0">
              <a-form-item
                :label="t('views.logManage.neFile.nePath')"
                name="configName"
                style="margin-bottom: 0"
              >
                <a-breadcrumb>
                  <a-breadcrumb-item
                    v-for="(path, index) in nePathArr"
                    :key="path"
                    @click="fnDirCD(path, index)"
                  >
                    {{ path }}
                  </a-breadcrumb-item>
                </a-breadcrumb>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </template>

      <!-- 插槽-卡片右侧 -->
      <template #extra>
        <a-space :size="8" align="center">
          <a-tooltip>
            <template #title>{{ t('common.reloadText') }}</template>
            <a-button type="text" @click.prevent="fnGetList()">
              <template #icon><ReloadOutlined /></template>
            </a-button>
          </a-tooltip>
        </a-space>
      </template>

      <!-- 表格列表 -->
      <a-table
        class="table"
        row-key="fileName"
        :columns="tableColumns"
        :loading="tableState.loading"
        :data-source="tableState.data"
        :size="tableState.size"
        :pagination="tablePagination"
        :scroll="{ x: 800 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'fileName'">
            <a-space :size="8" align="center">
              <a-button
                type="link"
                @click.prevent="fnDownloadFile(record)"
                v-if="record.fileType === 'file'"
              >
                <template #icon><DownloadOutlined /></template>
                {{ t('common.downloadText') }}
              </a-button>
              <a-button
                type="link"
                @click.prevent="fnDirCD(record.fileName)"
                v-if="record.fileType === 'dir'"
              >
                <template #icon><FolderOutlined /></template>
                {{ t('views.logManage.neFile.dirCd') }}
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
  </PageContainer>
</template>

<style lang="less" scoped></style>
