<template>
  <div>
    <!-- 查询条件 -->
    <div class="search-bar run-search-bar">
      <div>
        <Button size="small" @click.native="search" type="warning" icon="ios-search">{{$t('common.search')}}</Button>
        <Button size="small" @click.native="formReset" type="info" icon="md-sync">{{$t('common.reset')}}</Button>
      </div>
      <div>
        <Form :model="formSearch" ref="userSessionFormSearch" slot="search-bar" label-position="top" class="ivu-form-no-margin-bottom" inline>
          <Form-item prop="userCode" :label="$t('module.userSession.userAccount')">
            <Input type="text" v-model="formSearch.userCode" placeholder="" size="small"></Input>
          </Form-item>
          <Form-item prop="userName" :label="$t('module.userSession.username')">
            <Input type="text" v-model="formSearch.userName" placeholder="" size="small"></Input>
          </Form-item>
        </Form>
      </div>
    </div>
    <!-- 用户会话列表展示 -->
    <div class="single-table-con">
      <Table size="small" :loading="tableLoading" :data="tableData" :columns="columns" stripe></Table>
      <div style="margin: 10px;overflow: hidden">
        <div style="float: right;">
          <Page :total="pageTotal" :page-size="pageSize" :current="currentPage" @on-change="changePage" size="small"></Page>
        </div>
      </div>
    </div>

  </div>
</template>
<script>
export default {
  name: 'user-session-manage',
  // title: '用户会话管理',
  data() {
    return {
      tableLoading: false,
      formSearch: {
        userCode: "",
        userName: ""
      },
      tableData: [],
      columns: [
        {
          type: "selection",
          width: 60,
          align: "center",
          fixed: 'left',
        },
        {
          title: this.$t('common.operating'),
          align: "center",
          width: 65,
          fixed: 'left',
          render: (h, params) => {
            return h("RowTools", {
              props: {
                data: [
                  {
                    type: "icon",
                    icon: "close-circled",
                    text: this.$t('module.userSession.closeSession'),
                    handle: () => {
                      this.deleteUser(params.row.USER_ID, params.row.USER_TOKEN);
                    }
                  }
                ]
              }
            });
          }
        },
        {
          title: this.$t('module.userSession.userAccount'),
          key: "USER_CODE",
          align: "center",
          fixed: 'left',
          width: 100
        },
        {
          title: this.$t('module.userSession.username'),
          key: "USER_NAME",
          align: "center",
          width: 100
        },
        {
          title: "token",
          key: "USER_TOKEN",
          align: "center",
          width: 800,
          render: (h, params) => {
            return h('div', {
              attrs: {
                title: params.row.USER_TOKEN,
                href: '#'
              },
              on: {
                click: (event) => {
                  console.log(params.row.USER_TOKEN);
                }
              }
            }, params.row.USER_TOKEN);
          }
        },
        {
          title: "IP",
          key: "USER_IP",
          width: 120
        },
        {
          title: this.$t('module.userSession.lastVisit'),
          key: "LAST_ACCESS_TIME",
          width: 160,
          sortable: true,
          render: (h, params) => {
            return new Date(params.row.LAST_ACCESS_TIME).Format()
          }
        },
        {
          title: this.$t('module.userSession.loginTime'),
          key: "LOGIN_TIME",
          sortable: true,
          // fixed: 'right',
          width: 140,
          render: (h, params) => {
            return new Date(params.row.LOGIN_TIME).Format()
          }
        }
      ],
      currentPage: 1,
      pageSize: 10,
      pageTotal: 0,
      userSessionOriginList: [],
      userSessionList: []
    };
  },
  created() {

    this.refreshDataSourch();
  },
  methods: {
    clickHandler(token) {
      this.$Message.info({
        content: token
      });
    },
    refreshDataSourch() {
      this.tableLoading = true;
      $store
        .dispatch("QueryUserSession", {
          commonPageDTO: {
            currentPage: 1,
            pageSize: 10000
          },
          /*sortDTO: {
            fieldName: "",
            orderBy: ""
          }*/
        })
        .then(res => {
          this.tableLoading = false;
          if (res.statusCode != 0) {
            this.$Message.warning({
              content: res.msg,
              duration: 3
            });
            return;
          }

          this.userSessionOriginList = res.dataResult;
          this.userSessionOriginList.sort(this.by("lastAccessTime", true));
          this.userSessionList = [];

          if (
            this.formSearch.userCode == "" &&
            this.formSearch.userName == ""
          ) {
            this.userSessionList = this.userSessionOriginList;
          } else {
            for (let i = 0; i < this.userSessionOriginList.length; i++) {
              let uSession = this.userSessionOriginList[i];
              if (
                this.formSearch.userCode != "" &&
                uSession.USER_CODE.toUpperCase().indexOf(this.formSearch.userCode.toUpperCase()) < 0
              ) {
                continue;
              }

              if (
                this.formSearch.userName != "" &&
                uSession.USER_NAME.toUpperCase().indexOf(this.formSearch.userName.toUpperCase()) < 0
              ) {
                continue;
              }
              this.userSessionList.push(uSession);
            }
          }

          this.pageTotal = this.userSessionList.length;
          this.currentPage = 1;
          this.loadSource();
        });
    },
    loadSource() {
      let start = (this.currentPage - 1) * this.pageSize;
      let end = start + this.pageSize;
      end = this.pageTotal > end ? end : this.pageTotal;
      this.tableData = [];
      for (let i = start; i < end; i++) {
        this.tableData.push(this.userSessionList[i]);
      }
    },
    changePage(page) {
      this.currentPage = page;
      this.loadSource();
    },
    by(name, isDESC) {
      return function (o, p) {
        var a, b;
        if (typeof o === "object" && typeof p === "object" && o && p) {
          a = o[name];
          b = p[name];
          if (a === b) {
            return 0;
          }
          if (typeof a === typeof b) {
            if (isDESC) {
              return a < b ? 1 : -1;
            }
            return a < b ? -1 : 1;
          }
          return typeof a < typeof b ? -1 : 1;
        } else {
          throw "error";
        }
      };
    },
    search() {
      //this.$refs['userTable'].load(this.formSearch);
      // console.log(this.formSearch.userCode);
      this.refreshDataSourch();
    },
    deleteUser(userId, token) {
      let deleteStr = userId;
      if (deleteStr == "") return;
      new $confirm(this.$t('module.userSession.confirmDelete'), this).then(() => {
        this.$store
          .dispatch("DeleteUserSession", {
            userId: deleteStr,
            token: token
          })
          .then(() => {
            this.search();
          });
      });
    },
    getIds() {
      let list = this.$refs["userTable"].getSelectioned() || [];
      let ids = [];
      for (let u of list) {
        ids.push(u.userId);
      }
      return ids.join(",");
    },
    formReset() {
      this.$refs["userSessionFormSearch"].resetFields();
      this.refreshDataSourch();
    }
  }
};
</script>
