<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-upload2" type="primary" v-if="uploadCommand.visible"
                     @click="uploadFirmWareInit">
            {{$t("FirmWareConfiguration.firmWareUpload")}}
          </el-button>
          <el-button size='mini'  icon="el-icon-download" type="primary"
                     @click="downloadFirmWareToLocal">
            {{$t("FirmWareConfiguration.firmWareDownload")}}
          </el-button>
          <el-button size='mini' icon="el-icon-refresh" type="primary" v-if="updateCommand.visible"
                     @click="updateFirmWareInit">
            {{$t("FirmWareConfiguration.firmWareUpdate")}}
          </el-button>
          <el-button size='mini' icon="el-icon-back" type="primary" v-if="recoverCommand.visible"
                     @click="recoverFirmWareInit">
            {{$t("FirmWareConfiguration.firmWareRecover")}}
          </el-button>
          <el-button size='mini' icon="el-icon-delete" type="primary" v-if="deleteCommand.visible"
                     @click="deleteFirmWareInit" >
            {{$t("FirmWareConfiguration.firmWareDelete")}}
          </el-button>
        </div>
        <div class="header-search">
          <div class="search-input-box">
            <label>{{ $t('FirmWareConfiguration.firmWareName')}}：</label>
            <el-input size='mini' :placeholder="$t('common.placeholder')" v-model="queryFirmWareName"
                      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="startDatePicker"
              @change="beginDateChange"
              :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="endDatePicker"
              @change="endDateChange"
              :placeholder="$t('AlarmQuery.chooseEndTime')">
            </el-date-picker>
          </div>
          <div class="search-input-box">
            <el-button size='mini' icon="el-icon-search" type="primary" @click="queryFirmWareByCondition"
                       v-loading.fullscreen.lock="fullscreenLoading">{{ $t("common.queryBtn")}}
            </el-button>
          </div>
        </div>
      </el-header>

      <el-main class="adapt-height-box">
        <el-table
          :empty-text="$t('common.noData')"
          border
          header-row-class-name="table-header"
          cell-class-name="table-cell"
          class="adapt-height"
          height="auto"
          ref="singleTable"
          :data="firmWareList"
          highlight-current-row
          stripe
          tooltip-effect="dark"
          @current-change="handleCurrentChange"
          @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            width="28">
          </el-table-column>
          <el-table-column
            :show-overflow-tooltip="true"
            prop="firmwareName"
            :label="$t('FirmWareConfiguration.firmWareName')">
          </el-table-column>
          <el-table-column
            prop="timestamp"
            :label="$t('FirmWareConfiguration.timeStamp')"
            :show-overflow-tooltip="true"
            :formatter="formatTime"
          ></el-table-column>
          <!--<el-table-column-->
            <!--:show-overflow-tooltip="true"-->
            <!--prop="description"-->
            <!--:label="$t('FirmWareConfiguration.firmWareDescription')">-->
          <!--</el-table-column>-->
          <el-table-column
            prop="deviceType"
            :label="$t('DeviceConfigurationManagement.nodeType')"
            :show-overflow-tooltip="true"
            :formatter="formatdeviceType">
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>
    <CommandExecuteContext v-bind:commands="commandContext"></CommandExecuteContext>
  </div>
</template>

<script>
import ElFormItem from '../../../../node_modules/element-ui/packages/form/src/form-item.vue'
import FirmWareCommands from '@/commands/FirmWareCommands.js'
import CommandExecuteContext from '@/commands/CommandExecuteContext'
import HelperUtil from '../../../utils/HelperUtil'

import FirmWareService from '@/domain/services/FirmWareService.js'

export default {

  components: {
    CommandExecuteContext,
    ElFormItem
  },
  name: 'FirmWareConfigurationManagement',
  data: function () { // 存放 数据
    return {
      queryFirmWareName: '', // 固件名称
      beginTime: '', // 开始时间
      endTime: '', // 结束时间
      startDatePicker: this.beginDate(),
      endDatePicker: this.endDate(),
      addTimestamp: '00.000',
      addTimestamp1: '59.999',

      deleteList: [], // 删除集合

      firmWareList: [], // 固件集合

      multipleSelection: [], // 选中值

      form: {
        firmwareKey: '',
        firmwareName: ''
      },
      // 命令
      commandContext: {},
      configurationUpdateshow: false,
      formLabelWidth: '120px'
    }
  },

  methods: {
    // ls获取全部固件信息
    getAllFirmWareInit: function () {
      let _this = this
      console.log('获取全部固件信息:')
      FirmWareService.getAllFirmWareCollection().then(result => {
        // 成功
        _this.firmWareList = Object.values(result)
      }).catch(err => {
        // 失败
        console.log('获取全部固件信息失败:')
        _this.InfoTip.errorTip(_this, err)
      })
    },

    getAllFirmWare: function (vue) {
      let _this = vue
      console.log('获取全部固件信息:')
      FirmWareService.getAllFirmWareCollection().then(result => {
        // 成功
        _this.firmWareList = Object.values(result)
      }).catch(err => {
        // 失败
        console.log('获取全部固件信息失败:')
        _this.InfoTip.errorTip(_this, err)
      })
    },

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

    // 固件上传初始化
    uploadFirmWareInit: function () {
      this.uploadCommand.execute()
    },

    // 固件下载
    downloadFirmWareToLocal: function () {
      let _this = this
      console.log('固件文件下载到本地:')
      if (this.multipleSelection.length == 0) {
        this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.PLEASE_SELECT_AT_LEASE_ONE_CONFIGURATION))
        return
      }
      if (this.multipleSelection.length > 1) {
        this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.PLEASE_SELECT_ONLY_ONE_CONFIGURATION))
        return
      }
      // 传参
      var selectList = new Array()
      selectList = this.multipleSelection
      // 放数据
      var currentFirmWareKey = this.multipleSelection[0].firmwareKey

      // 定义文件名称
      var name = this.multipleSelection[0].firmwareName.toString()// +'.conf';
      let loadingInstance = this.Loading.openLoading()
      // FirmWareService.downloadFirmWare(currentFirmWareKey, name, selectList).then(result => {
      FirmWareService.downloadFirmWare(currentFirmWareKey, name).then(result => {
        _this.InfoTip.successTip(_this, HelperUtil.getStatusCodeObjectByCode(_this.successCode.OTHERS_CODE))
        _this.Loading.closeLoading(loadingInstance)
        // 成功
      }).catch(err => {
        _this.Loading.closeLoading(loadingInstance)
        // 失败
        _this.InfoTip.errorTip(_this, err)
      })
      this.fullscreenLoading = false
    },

    // 固件更新初始化
    updateFirmWareInit: function () {
      if (this.multipleSelection.length == 0) {
        this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.PLEASE_SELECT_AT_LEASE_ONE_CONFIGURATION))
      } else if (this.multipleSelection.length > 1) {
        this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.PLEASE_SELECT_ONLY_ONE_CONFIGURATION))
      } else {
        this.updateFirmWareKey = this.multipleSelection[0].firmwareKey
        this.updateCommand.execute()
      }
    },

    // 固件回退初始化
    recoverFirmWareInit: function () {
      this.recoverCommand.execute()
    },

    // 删除固件
    deleteFirmWareInit: function () {
      if (this.multipleSelection.length == 0) {
        this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.DELETE_SELECT_CODE))
      } else {
        this.deleteList = new Array()
        for (var i = 0; i < this.multipleSelection.length; i++) {
          this.deleteList[i] = this.multipleSelection[i]['firmwareKey']
        }
        this.deleteCommand.execute()
      }
    },

    // 固件条件查询
    queryFirmWareByCondition: function () {
      if (this.queryFirmWareName == '' && this.beginTime == '' && this.endTime == '') {
        // 所有查询条件为空点查询--》重新刷新表格
        this.$options.methods.getAllFirmWare(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.queryFirmWareName !== '' && this.queryFirmWareName !== null) {
        this.selectList.push({ quaryAttribute: 'firmwareName',
          compareSymbol: 'like',
          compareValue: this.queryFirmWareName})
      }
      // 按条件查询
      let _this = this
      let loadingInstance = _this.Loading.openLoading()
      FirmWareService.conditionQueryFirmWare(this.selectList).then(result => {
        // 成功
        _this.firmWareList = Object.values(result)
        _this.Loading.closeLoading(loadingInstance)
        if (_this.firmWareList.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)
      })
    },
    /**
       * @Description  :过滤主页面本地上传，设备上传
       */
    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()
          }
        }
      }
    }
  },

  computed: {
    uploadCommand () {
      return FirmWareCommands.uploadFireWareCommand(this.commandContext)
    },
    deleteCommand () {
      return FirmWareCommands.deleteFirmWareCommand(this.deleteList, this.commandContext)
    },
    updateCommand () {
      return FirmWareCommands.updateFirmWareCommand(this.multipleSelection[0], this.commandContext)
    },
    recoverCommand () {
      return FirmWareCommands.recoverFirmWareCommand(this.multipleSelection[0], this.commandContext)
    }
  },
  created: function () {
    this.getAllFirmWareInit()
  },
  watch: {
    commandContext (newVal, oldVal) {
      if (JSON.stringify(newVal) === '{}') {
        this.queryFirmWareName = ''
        this.beginTime = ''
        this.endTime = null
        this.getAllFirmWare(this)
        this.$refs.singleTable.clearSelection()
      }
      deep: true
    }
  }
}
</script>

<style scoped>
  /*!* 外层布局容器样式 *!*/

  .el-table .warning-row {
    background: oldlace;
  }

  body .el-table colgroup.gutter {
    display: table-cell !important;
  }

  .el-table .current-row {
    background: #FF8040;
  }

</style>
