<template>
  <div id="main" class="h-all">
    <el-container class="h-all">
      <el-header height="auto">
        <!-- 条件查询工具栏 -->
        <div class="header-search">
          <div class="search-input-box">
            <label>{{$t("Performance.startTime") + '：'}}</label>
            <el-date-picker
              v-model="beginTimestamp"
              type="datetime"
              size="mini"
              format="yyyy-MM-dd HH:mm"
              :clearable="false"
              align="center"
              :picker-options="startDatePicker"
              @change="beginDateChange"
              :placeholder="$t('Performance.startTimePlaceholder')">
            </el-date-picker>
          </div>
          <div class="search-input-box">
            <label>{{$t("Performance.endTime") + '：'}}</label>
            <el-date-picker
              v-model="endTimestamp"
              type="datetime"
              size="mini"
              format="yyyy-MM-dd HH:mm"
              :clearable="false"
              align="center"
              :picker-options="endDatePicker"
              @change="endDateChange"
              :placeholder="$t('Performance.endTimePlaceholder')">
            </el-date-picker>
          </div>
          <div class="search-input-box">
            <label>{{$t("Security.loginUser") + '：'}}</label>
            <el-select v-model="selectUserKey" size="mini" :placeholder="$t('common.selectOption')" :clearable="true">
              <el-option
                v-for="item in userList"
                :key="item.userKey"
                :label="item.userName"
                :value="item.userKey">
              </el-option>
            </el-select>
          </div>
          <div class="search-input-box">
            <label>{{$t("Security.loginStatus") + '：'}}</label>
            <el-select v-model="selectedLoginResult" size="mini" :placeholder="$t('common.selectOption')"
                       :clearable="true">
              <el-option
                v-for="item in loginResults"
                :key="item.loginResult"
                :label="item.value"
                :value="item.loginResult">
              </el-option>
            </el-select>
          </div>
          <div class="search-input-box">
            <el-button size='mini' icon="el-icon-search" type="primary" @click="queryLoginLogsByCondition">{{$t("common.queryBtn")}}</el-button>
            <el-button v-if="false" size='mini' icon="el-icon-delete" type="primary" @click="deleteLoginLogs">{{$t("common.deleteBtn")}}</el-button>
            <el-button size='mini' icon="el-icon-download" type="primary" @click="exportToExcelInit">{{$t("common.exportBtn")}}</el-button>
          </div>
        </div>
      </el-header>
      <!-- table数据表格 -->
      <el-main class="adapt-height-box">
        <el-table
          :empty-text="$t('common.noData')"
          ref="multipleTable"
          :data="loginLogList"
          header-row-class-name="table-header"
          cell-class-name="table-cell"
          class="adapt-height"
          height="auto"
          border
          stripe
          tooltip-effect="dark"
          :highlight-current-row="true"
          @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            v-if="false"
            width="28">
          </el-table-column>
          <el-table-column
            type="index"
            :label="$t('Performance.index')"
            width="50">
          </el-table-column>
          <el-table-column
            prop="userName"
            :label="$t('Security.loginUser')"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="loginTime"
            :label="$t('Security.loginTime')"
            :formatter="formatDate"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="loginIp"
            :label="$t('Security.loginIP')"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="loginResult"
            :label="$t('Security.loginStatus')"
            :formatter="formatLoginResult"
            :show-overflow-tooltip="true">
          </el-table-column>
        </el-table>
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-size="pageSize"
          layout="prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </el-main>
    </el-container>
  </div>
</template>

<script>
  import UserService from '../../domain/services/UserService'
  import LoginLogService from '../../domain/services/UserLogService'
  import HelperUtil from "../../utils/HelperUtil";

  export default {
    name: 'LoginLogManagement',
    //创建期间
    beforeCreate() {

    },
    //vue加载初始化函数，加载数据
    created: function () {
      this.setDefaultDateTime();
      this.getAllUsers();
    },
    //存放数据
    data: function () {
      return {
        beginItem: 1,
        endItem: 100,
        total: 100,
        currentPage: 1,
        pageSize: 100,


        //日期控件
        beginTimestamp: "",  //开始时间
        endTimestamp: "",  //结束时间
        addBeginTimestamp: "00.000",  //查询开始时间默认添加
        addEndTimestamp: "59.999", //查询结束时间默认添加
        startDatePicker: this.beginDate(),
        endDatePicker: this.endDate(),

        //用户列表
        userList: [],
        userCollection: {},
        selectUserKey: '',

        //操作结果列表
        loginResults: [{
          loginResult: 0,
          value: this.$t('Security.loginSuccess')
        }, {
          loginResult: 1,
          value: this.$t('Security.loginFailed')
        },{
          loginResult: 2,
          value: this.$t('Security.logout')
        },],
        selectedLoginResult: '',

        //登录日志列表实体类
        loginLogKey: '',
        userKey: '',
        loginIp: '',
        loginResult: '',
        loginTime: '',


        //双向绑定展示数据
        loginLogList: [],

        //查询条件List
        selectList: [],
        selectList1: [],
      }
    },
    methods: {
      /*---------------------------页面显示---------------------------*/

      /***
       * @Description  : 当前页面变化获取新的性能List
       * @author       : zf
       * @date         : 2018/12/20 20:12
       */
      handleCurrentChange(val) {
        this.currentPage = val;
        this.beginItem = ((val - 1) * 100) + 1;
        this.endItem = this.beginItem + 99;
        if (this.endItem > this.total) {
          this.endItem = this.total
        }
        this.queryLoginLogByConditionCurrentPage();
      },
      /***
       * @Description  : 多选框变化
       * @author       : zf
       * @date         : 2019/1/4 11:33
       */
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },

      /***
       * @Description  : 日期过滤
       * @author       : zf
       * @date         : 2019/1/2 19:40
       */
      formatDate: function (row, column) {
        let showDate;
        let arr;
        if (row.loginTime !== "") {
          arr = row.loginTime.split(".");
          showDate = "" + arr[0].substring(0, 4) + "-" + arr[0].substring(4, 6) + "-" + arr[0].substring(6, 8) + " ";
          showDate = showDate + arr[1].substring(0, 2) + ":" + arr[1].substring(2, 4) + ":" + arr[1].substring(4, 6) + '.' + arr[2];
        }
        else {
          showDate = row.loginTime
        }
        return showDate
      },

      /***
       * @Description  : 用户名过滤（对象形式的转换）
       * @author       : zf
       * @date         : 2019/03/18 10:15
       */
      formatUserKey: function (row, column) {
        if(this.userCollection[row.userKey] !== undefined){
          return this.userCollection[row.userKey].userName
        }
        else{
          return row.userKey
        }
      },

      /***
       * @Description  : 登录结果过滤
       * @author       : zf
       * @date         : 2019/03/18 10:18
       */
      formatLoginResult: function (row, column) {
        let result = row.loginResult;
        if (row.loginResult === 0) {
          result = this.$t('Security.loginSuccess')
        }
        else if (row.loginResult === 1) {
          result = this.$t('Security.loginFailed')
        }
        else if (row.loginResult === 2) {
          result = this.$t('Security.logout')
        }
        return result
      },

      /***
       * @Description  : 检测时间合法
       * @author       : zf
       * @date         : 2019/1/21 13:37
       */
      //设置禁止选择当前日期之后的时间，且开始时间小于结束时间
      beginDate: function () {
        let self = this;
        return {
          disabledDate(time) {
            return time.getTime() > self.endTimestamp.getTime() || time.getTime() > Date.now()
          }
        }
      },
      //结束时间必须大于开始时间
      endDate: function () {
        let self = this;
        return {
          disabledDate(time) {
            return time.getTime() < (self.beginTimestamp.getTime() - 1000 * 3600 * 24) || time.getTime() > Date.now()
          }
        }
      },
      //开始时间被清空后重新赋值
      beginDateChange: function () {
        const setTimes = new Date();
        if (this.beginTimestamp === null) {
          setTimes.setTime(this.endTimestamp.getTime() - (60 * 60 * 1000));
          this.beginTimestamp = setTimes;
          this.InfoTip.warningTip_alarm(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.START_TIME_EMPTY_CODE))
        }
        if (this.beginTimestamp > this.endTimestamp) {
          setTimes.setTime(this.endTimestamp.getTime() - (60 * 60 * 1000));
          this.beginTimestamp = setTimes;
          this.InfoTip.warningTip_alarm(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.START_END_TIME_CODE))
        }
      },
      //结束时间被清空后重新赋值
      endDateChange: function () {
        const setTimes = new Date();
        const curTimes = new Date();
        if (this.endTimestamp === null) {
          if ((this.beginTimestamp.getTime() + (60 * 60 * 1000)) > curTimes.getTime()) {
            this.endTimestamp = curTimes
          }
          else {
            setTimes.setTime(this.beginTimestamp.getTime() + (60 * 60 * 1000));
            this.endTimestamp = setTimes
          }
          this.InfoTip.warningTip_alarm(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.END_TIME_EMPTY_CODE))
        }
        if (this.endTimestamp < this.beginTimestamp) {
          if ((this.beginTimestamp.getTime() + (60 * 60 * 1000)) > curTimes.getTime()) {
            this.endTimestamp = curTimes
          }
          else {
            setTimes.setTime(this.beginTimestamp.getTime() + (60 * 60 * 1000));
            this.endTimestamp = setTimes
          }
          this.InfoTip.warningTip_alarm(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.START_END_TIME_CODE))
        }
        if (this.endTimestamp > curTimes) {
          if ((this.beginTimestamp.getTime() + (60 * 60 * 1000)) > curTimes.getTime()) {
            this.endTimestamp = curTimes
          }
          else {
            setTimes.setTime(this.beginTimestamp.getTime() + (60 * 60 * 1000));
            this.endTimestamp = setTimes
          }
          this.InfoTip.warningTip_alarm(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.START_END_TIME_CODE))
        }
      },

      /*---------------------------初始化页面数据---------------------------*/

      /***
       * @Description  : 获取默认时间
       * @author       : zf
       * @date         : 2019/1/4 11:32
       */
      setDefaultDateTime: function () {
        const start = new Date();
        const end = new Date();
        start.setTime(start.getTime() - 3600 * 1000);
        this.beginTimestamp = start;
        this.endTimestamp = end
      },

      /***
       * @Description  : 获取全部用户，初始化表格+用户下拉菜单
       * @author       : zf
       * @date         : 2019/03/13 11:01
       */
      getAllUsers: function () {
        let _this = this;
        UserService.getAllUserCollection().then(result => {
          //成功
          _this.userCollection = result;
          _this.userList = Object.values(result)
        }).catch(err => {
          //失败
          _this.InfoTip.errorTip(_this,err)
        })

      },

      /*---------------------------查询功能实现---------------------------*/

      /***
       * @Description  : 获取查询条件列表
       * @author       : zf
       * @date         : 2019/1/4 11:29
       */
      setQuerySelectList: function () {
        this.selectList = [];
        let year;
        let month;
        let day;
        let hours;
        let minutes;
        if (this.beginTimestamp !== '' && this.beginTimestamp !== null) {
          year = '' + this.beginTimestamp.getFullYear();
          month = '' + (this.beginTimestamp.getMonth() + 1);
          day = '' + this.beginTimestamp.getDate();
          hours = '' + this.beginTimestamp.getHours();
          minutes = '' + this.beginTimestamp.getMinutes();
          if (month.length === 1) {
            month = '0' + month
          }
          if (day.length === 1) {
            day = '0' + day
          }
          if (hours.length === 1) {
            hours = '0' + hours
          }
          if (minutes.length === 1) {
            minutes = '0' + minutes
          }
          let begin = '' + year + month + day + '.' + hours + minutes + this.addBeginTimestamp;
          this.selectList.push({
            quaryAttribute: 'loginTime',
            compareSymbol: ">=",
            compareValue: begin,
          })
        }
        if (this.endTimestamp !== '' && this.endTimestamp !== null) {
          year = '' + this.endTimestamp.getFullYear();
          month = '' + (this.endTimestamp.getMonth() + 1);
          day = '' + this.endTimestamp.getDate();
          hours = '' + this.endTimestamp.getHours();
          minutes = '' + this.endTimestamp.getMinutes();
          if (month.length === 1) {
            month = '0' + month
          }
          if (day.length === 1) {
            day = '0' + day
          }
          if (hours.length === 1) {
            hours = '0' + hours
          }
          if (minutes.length === 1) {
            minutes = '0' + minutes
          }
          let end = '' + year + month + day + '.' + hours + minutes + this.addEndTimestamp;
          this.selectList.push({
            quaryAttribute: 'loginTime',
            compareSymbol: "<=",
            compareValue: end,
          })
        }
        if (this.selectUserKey !== '' && this.selectUserKey !== null) {
          this.selectList.push({
            quaryAttribute: 'userKey',
            compareSymbol: "=",
            compareValue: this.selectUserKey,
          })
        }
        if (this.selectedLoginResult !== '' && this.selectedLoginResult !== null) {
          this.selectList.push({
            quaryAttribute: 'loginResult',
            compareSymbol: "=",
            compareValue: this.selectedLoginResult,
          })
        }
      },

      /***
       * @Description  : 点击查询按钮事件
       * @author       : zf
       * @date         : 2018/12/13 16:37
       */
      queryLoginLogsByCondition: function () {
        this.beginItem = 1;
        this.setQuerySelectList();
        let _this = this;
        let loadingInstance = _this.Loading.openLoading();
        LoginLogService.queryLoginLogCountsByCondition(this.selectList).then(result => {
          //成功
          _this.Loading.closeLoading(loadingInstance);
          _this.total =  result;
          if (_this.total === 0 || _this.total < 0) {
            _this.InfoTip.warningTip_alarm(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.QUERY_NULL_CODE))
            _this.loginLogList = [];
          }
          else {
            if (_this.total < 100 && _this.total > 0) {
              _this.endItem = _this.total
            }
            else {
              _this.endItem = 100
            }
            _this.queryLoginLogByConditionCurrentPage();
            _this.InfoTip.successTip(_this,HelperUtil.getStatusCodeObjectByCode(_this.successCode.QUERY_CODE));
          }
        }).catch(err => {
          //失败
          _this.Loading.closeLoading(loadingInstance);
          _this.InfoTip.errorTip(_this,err);
          _this.loginLogList = [];
          _this.endItem = 100;
        })
      },

      /***
       * @Description  : 获取当前分页性能列表
       * @author       : zf
       * @date         : 2018/12/20 20:17
       */
      queryLoginLogByConditionCurrentPage: function () {
        let _this = this;
        let loadingInstance = _this.Loading.openLoading();
        LoginLogService.queryLoginLogSplitByCondition(this.beginItem, 100, this.selectList).then(result => {
          //成功
          _this.loginLogList = Object.values(result);
          _this.Loading.closeLoading(loadingInstance);
        }).catch(err => {
          //失败
          _this.loginLogList = [];
          _this.Loading.closeLoading(loadingInstance);
          _this.InfoTip.errorTip(_this,err);
        })
      },

      /*---------------------------删除某些操作日志---------------------------*/

      deleteLoginLogs: function () {

      },

      /*---------------------------导出功能实现---------------------------*/

      /**
       * @Description  ：导出文件
       */
      exportToExcelInit: function () {
        let _this = this;
        let loadingInstance = _this.Loading.openLoading();
        LoginLogService.exportLoginLogToExcel(this.selectList1).then(result => {
          //成功
          _this.Loading.closeLoading(loadingInstance);
        }).catch(err => {
          //失败
          _this.Loading.closeLoading(loadingInstance);
          _this.InfoTip.errorTip(_this,err);
        })
      },

    },
    watch:{
      '$i18n.locale' () {
        this.loginResults[0].value=this.$t('Security.loginSuccess');
        this.loginResults[1].value=this.$t('Security.loginFailed');
        this.loginResults[2].value=this.$t('Security.logout');
      }
    },
  }
</script>

<style scoped>
</style>
