<template>
  <div id="main" class="h-all">
    <el-container class="h-all">
      <el-header height="auto">
        <!-- 通用工具栏 -->
        <div class="header-button-box">
          <el-button size = 'mini' icon="el-icon-circle-plus-outline" type="primary" @click="createSnapshotInit"
                     v-if="createCommand">{{$t('common.createBtn')}}</el-button>
          <el-button size = 'mini' icon="el-icon-delete" type="primary" @click="deleteSnapshotInit"
                     v-if="deleteSnapshotCommand">{{$t('common.deleteBtn')}}</el-button>
        </div>
        <!-- 条件查询工具栏 -->
        <div class="header-search">
          <div class="search-input-box">
            <label>{{$t('SnapShotManagement.SnapShotName')}}</label>
            <el-input size = 'mini' :placeholder="$t('common.placeholder')"  v-model="querySelectName" clearable></el-input>
          </div>
          <div class="search-input-box">
            <label>{{ $t('AlarmQuery.beginTimestamp') }}</label>
            <el-date-picker
              v-model="beginTime"
              type="datetime"
              size="mini"
              format="yyyy-MM-dd HH:mm"
              clearable="false"
              align="center"
              :picker-options="beginTimePicker"
              :placeholder="$t('AlarmQuery.chooseStartTime')">
            </el-date-picker>
          </div>
          <div class="search-input-box">
            <label>{{ $t("AlarmQuery.endTimestamp") }}</label>
            <el-date-picker
              v-model="endTime"
              type="datetime"
              size="mini"
              format="yyyy-MM-dd HH:mm"
              clearable="false"
              align="center"
              :picker-options="endTimePicker"
              :placeholder="$t('AlarmQuery.chooseEndTime')">
            </el-date-picker>
          </div>
          <div class="search-input-box">
            <el-button icon="el-icon-search" type="primary" size = 'mini' @click="querySnapshotByCondition" v-loading.fullscreen.lock="fullscreenLoading">{{$t('common.queryBtn')}}</el-button>
          </div>
        </div>
      </el-header>

      <!-- table数据表格 -->
      <el-main class="adapt-height-box">
        <el-table
          :empty-text="$t('common.noData')"
          tooltip-effect="dark"
          stripe
          header-row-class-name="table-header"
          cell-class-name="table-cell"
          class="adapt-height"
          height="auto"
          border
          ref="singleTable"
          :data="SnapshotList"
          highlight-current-row
          @current-change="handleCurrentChange"
          @selection-change="handleSelectionChange">

          <el-table-column
            type="selection"
            width="28">
          </el-table-column>
          <el-table-column
            :show-overflow-tooltip="true"
            prop="snapshotName"
            :label="$t('SnapShotManagement.SnapShotName')">
          </el-table-column>
          <el-table-column
            prop="timestamp"
            :label="$t('SnapShotManagement.timeStamp')"
            :show-overflow-tooltip="true"
            :formatter="formatTime"
          ></el-table-column>
          <el-table-column
            prop="description"
            :label="$t('SnapShotManagement.description')"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column
            :label="$t('common.operation')">
            <template slot-scope="scope">
                <el-button
                  style="margin-top:-3.8px"
                  size="mini"
                  type="text"
                  @click="handleSnapshotRecover(scope.row)">{{$t('SnapShotManagement.recover')}}
                </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>

    <CommandExecuteContext v-bind:commands="commandContext"></CommandExecuteContext>

  </div>
</template>

<script>
  import CommandExecuteContext from '@/commands/CommandExecuteContext'
  import CabinetCommands from "@/commands/CabinetCommands"
  import SnapshotCommands from "@/commands/SnapshotCommands"
  import CabinetService from '@/domain/services/CabinetService'
  import SnapshotService from '@/domain/services/SnapshotService'
  import HelperUtil from '@/utils/HelperUtil'
  import { EventBus } from '@/domain/EventBus'
  import {USER_NAME} from '@/utils/constantCollection';
  import UserService from "../../domain/services/UserService";
  export default {
    name: 'SnapShot',
    components: {
      CommandExecuteContext,
    },

    data: function () {   //存放数据
      return {

        beginTime: '',
        endTime: '',
        beginTimePicker: this.beginDate(),
        endTimePicker: this.endDate(),
        addTimestamp: "00.000",
        addTimestamp1: "59.999",
        syncAllDataFlag: 'false',

        //命令
        commandContext: {},
        //为了创建复制初始化传参
        createAndCopyInitList: [],
        createAndCopyTitle: '',
        //删除相关
        deleteList: [],
        fullscreenLoading: false,

        //条件查询
        querySelectName: '', // 条件查询快照名称

        formLabelWidth: '120px',

        //双向绑定弹出窗口iput域
        form:{
          snapshotKey: '',
          snapshotName: '',
          snapshotDescription: '',
        },

        //双向绑定展示数据
        SnapshotList: [],
        //双向绑定展示数据
        QuerySnapShotList: [],
        value: '',
        //保存当前行数据
        currentRow: null,
        //保存多选行数据
        multipleSelection: [],
      }
    },
    computed: {
      //命令
      createCommand () {
        return SnapshotCommands.createSnapshotCommand(this.createTitle, this.createInitList, this.commandContext)
      },
      deleteSnapshotCommand () {
        return SnapshotCommands.deleteSnapshotCommand(this.deleteList, this.commandContext)
      }
    },

    methods: {
      handleCurrentChange (val)
      {
        this.currentRow = val
      },

      handleSelectionChange (val)
      {
        this.multipleSelection = val
      },

      //获取所有快照
      getAllSnapShotInit: function () {
        let _this = this;
        SnapshotService.getAllSnapshotCollection().then(result => {
          //成功
          _this.SnapshotList = Object.values(result)
        }).catch(err => {
          //失败
          console.log('获取快照信息失败')
          _this.InfoTip.errorTip(_this, err);
        })
      },

      // 快照回退初始化
      handleSnapshotRecover: function (row) {
        let _this = this;
        _this.InfoTip.conformTip(_this, HelperUtil.getCheckStatusCodeObjectByCode(_this.successCode.RECOVER_CONFIRM)
        ).then(() => {
          this.SnapshotRecover(row.snapshotKey);
        }).catch(() => {
          // alert('回退失败')
        })
      },

      // 快照回退
      SnapshotRecover: function (sKey) {
        let _this = this;
        SnapshotService.recoverSnapshot(sKey).then(result => {
          // _this.InfoTip.successTip(_this, HelperUtil.getCheckStatusCodeObjectByCode(_this.successCode.SNAPSHOT_RECOVER_SUCCESS))
          UserService.getAllUserCollection().then(result => {
            let userList = Object.values(result)
            var user = window.sessionStorage.getItem(USER_NAME)
              if (userList.some(function (item1) {
                return item1.userName === user
              })) {
                _this.InfoTip.successTip(_this, HelperUtil.getCheckStatusCodeObjectByCode(_this.successCode.SNAPSHOT_RECOVER_SUCCESS))
              } else {
                _this.InfoTip.successTip(_this, HelperUtil.getCheckStatusCodeObjectByCode(_this.successCode.SNAPSHOT_RECOVER_SUCCESS))
                UserService.logout().then(() => {
                  HelperUtil.toLoginPage()
                  _this.InfoTip.successTip(_this, HelperUtil.getStatusCodeObjectByCode(_this.successCode.OTHERS_CODE))
                }).catch((err) => {
                  _this.InfoTip.errorTip(_this, err)
                })
              }
          }).catch(err1 => {
            _this.InfoTip.errorTip(_this, err1)
          })
          // this.syncAllDataFlag = true;
          // EventBus.$emit('i-got-syncFlag', this.syncAllDataFlag);
        }).catch(err => {
          _this.InfoTip.errorTip(_this, err)
        })
      },

      //获取所有快照
      getAllSnapShot: function (vue) {
        let _this = vue;
        SnapshotService.getAllSnapshotCollection().then(result => {
          //成功
          _this.SnapshotList = Object.values(result)
        }).catch(err => {
          //失败
          console.log('获取快照信息失败')
          _this.InfoTip.errorTip(_this, err);
        })
      },

      createSnapshotInit:function () {
        this.createTitle = this.$t('SnapshotManagement.dialogSnapshotCreate');
        this.createInitList = {
          "snapshotKey": "",
          "snapshotName": "",
          'description':'',
          "delFlag": '',
          "timestamp": ""
        }
        this.createCommand.execute();
      },

      // 删除快照
      deleteSnapshotInit:function () {
        if (this.multipleSelection.length == 0) {
          //请至少选择一条信息进行删除
          this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.DELETE_SELECT_CODE))
          return;
        } else {
          this.deleteList = []
          for (var i = 0; i < this.multipleSelection.length; i++) {
            this.deleteList.push(this.multipleSelection[i]['snapshotKey']);
          }
          this.deleteSnapshotCommand.execute()
        }
      },
      // 条件查询
      querySnapshotByCondition: function () {
        if(this.querySelectName == '' && this.beginTime == '' && this.endTime == ''){
          //所有查询条件为空点查询--》重新刷新表格
          this.$options.methods.getAllSnapShot(this);
          return;
        }
        this.selectList = []

        var year;
        var month;
        var day;
        var hours;
        var minutes;
        if (this.beginTime !== '' && this.beginTime != null) {
          year = '' + this.beginTime.getFullYear();
          month = '' + (this.beginTime.getMonth() + 1);
          day = '' + this.beginTime.getDate();
          hours = '' + this.beginTime.getHours();
          minutes = '' + this.beginTime.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
          }
          var begin = '' + year + month + day + '.' + hours + minutes + this.addTimestamp;
          console.log('开始时间');
          console.log(begin);
          this.selectList.push({
            quaryAttribute: 'timestamp',
            compareSymbol: ">=",
            compareValue: begin,
          })
        }

        if (this.endTime !== '' && this.endTime != null) {
          year = '' + this.endTime.getFullYear();
          month = '' + (this.endTime.getMonth() + 1);
          day = '' + this.endTime.getDate();
          hours = '' + this.endTime.getHours();
          minutes = '' + this.endTime.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
          }
          var end = '' + year + month + day + '.' + hours + minutes + this.addTimestamp1;
          console.log('结束时间');
          console.log(end);
          this.selectList.push({
            quaryAttribute: 'timestamp',
            compareSymbol: "<=",
            compareValue: end,
          })
        }

        if(this.querySelectName !== '') {
          this.selectList.push({ quaryAttribute: 'snapshotName',
            compareSymbol: "like",
            compareValue: this.querySelectName,})
        }
        //按条件查询
        let _this = this;
        let loadingInstance = _this.Loading.openLoading();
        SnapshotService.conditionQuerySnapshot(this.selectList).then(result => {
          //成功
          _this.SnapshotList = Object.values(result);
          _this.Loading.closeLoading(loadingInstance);
          if(_this.SnapshotList.length == 0){
            //查询为空
            _this.InfoTip.warningTip(_this, HelperUtil.getCheckStatusCodeObjectByCode(_this.successCode.QUERY_NULL_CODE))
          }else{
            _this.InfoTip.successTip(_this, HelperUtil.getStatusCodeObjectByCode(_this.successCode.QUERY_CODE));
          }
        }).catch(err => {
          //失败
          _this.Loading.closeLoading(loadingInstance);
          _this.InfoTip.errorTip(_this, err);
        })
      },

      // 格式化时间
      formatTime: function (row, column) {
        var oldTime = row.timestamp
        var time = ''
        var year = oldTime.substring(0,4)
        var month = oldTime.substring(4,6)
        var day = oldTime.substring(6,8)
        var hour = oldTime.substring(9,11)
        var minute = oldTime.substring(11,13)
        var second = oldTime.substring(13,15)
        var millisecond = oldTime.substring(16,19)

        time = year+'-'+month+'-'+day+' '+ hour+':'+minute+':'+second+'.'+millisecond

        return time
      },

      // 时间控件
      beginDate: function () {
        return {
          disabledDate: time => {
            if (this.endTime) {
              return (
                time.getTime() > new Date(this.endTime).getTime()
              )
            } else {
              return time.getTime() > Date.now()
            }
          }
        }
      },
      endDate: function () {
        return {
          disabledDate: time => {
            if (this.beginTime) {
              return (
                time.getTime() > Date.now() ||
                time.getTime() < new Date(this.beginTime).getTime()
              );
            } else {
              return time.getTime() > Date.now();
            }
          }
        }
      }
    },
    //vue加载初始化函数，加载数据
    created: function () {
      this.getAllSnapShotInit()
    },
    watch: {
      commandContext(newVal, oldVal){
        if(JSON.stringify(newVal) === '{}'){
          this.querySelectName = ''
          this.getAllSnapShot(this)
          this.$refs.singleTable.clearSelection();
        }
        deep: true
      },
    }
  }
</script>

<style scoped>
</style>
