<script setup lang="ts">
import useStore from '@/stores';
import { reactive, ref, computed } from 'vue';
import { showElMessage } from '@/utils/utils';
import { traduction } from '@/utils/language';
import { ITableColumns, ISensorsTable } from '@/model/base-interface';
import { getOnlineUserData, deleteOnlineUser } from './online-user.server';

import GlobalStoreService from '@/services/gloabal-store-service';

import Lock from '@/components/Lock/Lock.vue';
import Dialog from '@/components/Dialog/Dialog.vue';

import TableNoData from '@/components/TableNoData/TableNoData.vue';

const globalStoreService = new GlobalStoreService();

const successMsg = traduction('COMMON_SUCCESS');
const errorMsg = traduction('COMMON_FAILED');

const store = useStore();
const isSystemLock = computed(() => {
  return store.state.glob.systemLocked;
});

const columns: ITableColumns[] = [
  {
    title: 'ONLINE_NO',
    content: 'code',
    idName: 'code',
  },
  {
    title: 'COMMON_USERNAME',
    content: 'UserName',
    idName: 'userName',
  },
  {
    title: 'ONLINE_LOGIN_METHOD',
    content: 'Interface',
    idName: 'interface',
  },
  {
    title: 'COMMON_LOGIN_IP',
    content: 'IPAddress',
    idName: 'ipAddress',
  },
  {
    title: 'COMMON_LOGIN_TIME',
    content: 'LoginTime',
    idName: 'loginTime',
  },
  {
    title: 'COMMON_OPERATE',
    content: 'operation',
    idName: 'operation',
  },
];

let dataList: ISensorsTable[] = [];
let tableData: ISensorsTable[] = reactive([]);

const searchContent = ref('');
let currentPage = ref(1);
let total = ref(0);
let pageSize = ref(10);
let checkItem: any = null;
const dialog = ref();

function getData() {
  tableData.splice(0);

  // 如果请求过最新数据（为什么是最新：因为这里有注销操作），那么不再发送请求，直接对现有请求数据做重新组合
  if (dataList.length > 0) {
    initShowData();
    return;
  }

  globalStoreService.setValue('isLoading', true);
  getOnlineUserData()
    .then((data: any) => {
      if (data && data.Members) {
        const members: any = data.Members;
        members.forEach((item: any) => {
          item.LoginTime = item.LoginTime.replace(/[T]/, ' ').slice(0, -6);
        });
        dataList.push(...members);
        initShowData();
        total.value = data.Count;
        globalStoreService.setValue('isLoading', false);
      } else {
        globalStoreService.setValue('isLoading', false);
        showElMessage('error', errorMsg);
      }
    })
    .catch(() => {
      globalStoreService.setValue('isLoading', false);
    });
}

// 加工展示数据
function initShowData() {
  const showList = dataList.slice(
    (currentPage.value - 1) * pageSize.value,
    currentPage.value * pageSize.value,
  );
  showList.forEach((item: any, index: number) => {
    item.code = index + 1 + ((currentPage.value - 1) * pageSize.value);
  });
  tableData.push(...showList);
}

// 点击注销
function loginOut(item: any) {
  if (!isSystemLock.value) {
    checkItem = item;
    dialog.value.show();
  }
}

// 确认注销
function sureLoginOut(flag: boolean) {
  if (flag) {
    deleteOnlineUser(checkItem.SessionID)
      .then(() => {
        dataList = [];
        dialog.value.hide();
        showElMessage('success', successMsg);
        getData();
      })
      .catch(() => {
        dialog.value.hide();
        showElMessage('error', errorMsg);
      });
  } else {
    dialog.value.hide();
  }
}

function handleSizeChange(val: number) {
  pageSize.value = val;
  getData();
}

function handleCurrentChange(val: number) {
  getData();
}

getData();
</script>

<template>
  <div id="onlineUser" class="online-user-box">
    <div class="content">
      <div class="text">{{ $t('ONLINE_USER_INFO') }}</div>
      <el-table v-addId.table="'onlineUserTable'" :data="tableData" border resizable>
        <el-table-column
          v-for="item in columns"
          :key="item.title"
          :prop="item.content"
          :label="$t(item.title)"
        >
          <template #default="scope">
            <span v-if="item.content === 'operation'">
              <span
                v-if="!scope.row.MySession"
                :id="'loginOut' + scope.row.code"
                :class="['login-out', isSystemLock ? 'disabled-btn' : '']"
                @click="loginOut(scope.row)"
              >
                {{ !scope.row.MySession ? $t('SERVICE_VMM_LOGOUT_LABEL') : '' }}
              </span>
            </span>
            <span v-else :id="item.idName + scope.row.code">{{ scope.row[item.content] }}</span>
          </template>
        </el-table-column>
        <template #empty>
          <TableNoData />
        </template>
      </el-table>

      <!-- 点击注销的弹窗 -->
      <Dialog
        ref="dialog"
        :config="{
          title: traduction('COMMON_INFORMATION'),
          content: traduction('COMMON_ASK_OK')
        }"
        @close="sureLoginOut"
      />
    </div>

    <el-pagination
      v-model:currentPage="currentPage"
      v-addId.pagination="'onlinePagination'"
      :page-sizes="[10, 15, 30, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<style lang="scss" scoped>
.online-user-box {
  flex: 1;
  margin-right: 24px;
  padding: 16px;
  background-color: var(--o-bg-color-base);
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  .content {
    flex: 1;
    padding-bottom: 16px;
    position: relative;
    display: flex;
    flex-direction: column;

    .text {
      line-height: 24px;
      font-size: 16px;
      color: var(--o-text-color-primary);
      font-weight: 600;
      margin-bottom: 16px;
    }

    .login-out {
      cursor: pointer;
      color: var(--o-color-primary);

      &:hover {
        color: var(--o-color-primary-secondary);
      }
    }

    .dialog-title {
      display: flex;
      align-items: center;
      .title-text {
        font-size: 16px;
        line-height: 24px;
        font-weight: 900;
      }
      :deep(.el-icon) {
        margin-right: 5px;
        font-size: 18px;
      }
    }

    :deep(.el-table--border) {
      padding-top: 0;
    }
  }

  :deep(.el-dialog) {
    width: 432px;
  }
}
</style>
