<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" @click="localUpload"
                     v-if="importCommand.visible">{{$t("ProfileManagement.localUpload")}}</el-button>
          <el-button size='mini' icon="el-icon-upload2" type="primary" @click="equipmentToUpload"
                     v-if="UploadConfigToDeviceCommand.visible">{{$t("DeviceConfigurationManagement.profileUpload")}}</el-button>
          <el-button size='mini' icon="el-icon-upload2" type="primary" @click="oneKeyUpload"
                     v-if="updateCommand.visible">{{$t('common.oneKeyUpload')}}</el-button>
          <el-button size='mini' icon="el-icon-delete" type="danger" @click="deleteConfigInit"
                     v-if="deleteCommand.visible">{{$t("ProfileManagement.delete")}}</el-button>
        </div>
        <div class="header-search">
          <div class="search-input-box">
            <label>{{$t('common.startTime')}}：</label>
            <el-date-picker
              v-model="beginTimestamp"
              type="datetime"
              size="mini"
              format="yyyy-MM-dd HH:mm"
              clearable="false"
              align="center"
              style="width: 173px"
              :picker-options="startDatePicker"
              @change="beginDateChange"
              :placeholder="$t('AlarmQuery.chooseStartTime')">
            </el-date-picker>
          </div>
          <div class="search-input-box">
            <label>{{$t('common.endTime')}}：</label>
            <el-date-picker
              v-model="endTimestamp"
              type="datetime"
              size="mini"
              format="yyyy-MM-dd HH:mm"
              clearable="false"
              align="center"
              style="width: 173px"
              :picker-options="endDatePicker"
              @change="endDateChange"
              :placeholder="$t('AlarmQuery.chooseEndTime')">
            </el-date-picker>
          </div>
<!--          <div class="search-input-box">-->
<!--            <label>{{$t('ProfileManagement.deviceName')}}：</label>-->
<!--            <el-select v-model="chooseDevice" size="mini" :clearable="true">-->
<!--              <el-option-->
<!--                v-for="item in deviceList"-->
<!--                :key="item.deviceKey"-->
<!--                :label="item.displayName"-->
<!--                :value="item.deviceKey">-->
<!--              </el-option>-->
<!--            </el-select>-->
<!--          </div>-->
          <div class="search-input-box">
            <label>{{$t('ProfileManagement.source')}}：</label>
            <el-select v-model="source" size="mini" :clearable="true">
              <el-option
                v-for="item in sourceList"
                :key="item.key"
                :label="item.label"
                :value="item.key">
              </el-option>
            </el-select>
          </div>
          <div class="search-input-box">
            <el-button size='mini' icon="el-icon-search" type="primary" @click="queryConfigFileDataByCondition">
              {{ $t("common.queryBtn")}}
            </el-button>
          </div>
        </div>
      </el-header>
      <el-main class="adapt-height-box">
        <el-table
          :empty-text="$t('common.noData')"
          header-row-class-name="table-header"
          cell-class-name="table-cell"
          class="adapt-height"
          height="auto"
          border
          ref="singleTable"
          :data="configList"
          highlight-current-row
          stripe
          tooltip-effect="dark"
          @selection-change="handleSelectionChangeMain">
          <el-table-column
            type="selection"
            width="28">
          </el-table-column>
          <el-table-column
            prop="configFileName"
            :label="$t('ProfileManagement.configFileName')"
            :show-overflow-tooltip="true">
          </el-table-column>
<!--          <el-table-column-->
<!--            prop="configFileName"-->
<!--            :label="$t('ProfileManagement.deviceName')"-->
<!--            :show-overflow-tooltip="true">-->
<!--          </el-table-column>-->
          <el-table-column
            prop="timestamp"
            :formatter="formatTime"
            :label="$t('ProfileManagement.timestamp')"
            :show-overflow-tooltip="true">
          </el-table-column>
          <!--<el-table-column-->
          <!--prop="codeByMd5"-->
          <!--:label="$t('ProfileManagement.codeByMd5')"-->
          <!--:show-overflow-tooltip="true">-->
          <!--</el-table-column>-->
          <!--<el-table-column-->
          <!--prop="path"-->
          <!--:label="$t('ProfileManagement.path')"-->
          <!--:show-overflow-tooltip="true">-->
          <!--</el-table-column>-->
          <el-table-column
            prop="description"
            :label="$t('ProfileManagement.description')"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="source"
            :label="$t('ProfileManagement.source')"
            :show-overflow-tooltip="true"
            :formatter="formatSource">
          </el-table-column>
          <el-table-column
            width="155px"
            :label="$t('common.operation')">
            <template slot-scope="scope">
              <el-button
                size="mini"
                style="background: #53D214"
                :title="$t('ProfileManagement.viewConfigFile')"
                @click="viewDetail(scope.row)">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-chakan"></use>
                </svg>
              </el-button>
              <el-button
                size="mini"
                style="background: #175BE3"
                :title="$t('ProfileManagement.downloadToDevice1')"
                @click="downloadToDeviceInit(scope.row)">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-beifen"></use>
                </svg>
              </el-button>
              <el-button
                size="mini"
                style="background: #008000"
                :title="$t('ProfileManagement.downloadToLocal1')"
                @click="downloadToLocal(scope.row)">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-xiazai"></use>
                </svg>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </el-main>
    </el-container>
    <el-dialog
      :title="this.title"
      :visible.sync="configFileDialogVisible"
      width="55%" center class="AlarmDisplay" style="font-size: 20px">
      <pre>{{this.content}}</pre>
    </el-dialog>
    <CommandExecuteContext v-bind:commands="commandContext"></CommandExecuteContext>
  </div>
</template>

<script>
import DeviceService from '@/domain/services/DeviceService.js'
import ConfigFileService from '@/domain/services/ConfigFileService.js'
import CommandExecuteContext from '@/commands/CommandExecuteContext'
import ConfigFileCommands from '@/commands/ConfigFileCommands'
import CodeDiff from 'vue-code-diff'
import HelperUtil from '@/utils/HelperUtil.js'

export default {
  components: {
    CommandExecuteContext,
    CodeDiff
  },
  name: 'ManualStartDeviceConfiguration',
  data: function () { // 存放 数据
    return {
      commandContext: {},
      downloadToDeviceFlag: -1,
      endTimestamp: '',
      beginTimestamp: '',
      addTimestamp: '00.000',
      addTimestamp1: '59.999',
      startDatePicker: this.beginDate(),
      endDatePicker: this.endDate(),
      chooseDevice: '',
      source: '',
      sourceList: [
        {
          key: 0,
          label: this.$t('ProfileManagement.LocalUpload')
        },
        {
          key: 1,
          label: this.$t('ProfileManagement.DeviceUpload')
        }
      ],
      selectList: [],
      deleteList: [],
      // update
      updateInitList: [],
      updateConfigFileKey: null,

      flag: false,
      // loading窗口
      fullscreenLoading: false,
      radio: '',

      dialog_updateConf: false,
      formLabelWidth: '120px',

      // 双向绑定弹出窗口ipput域
      form: {
        configFileKey: '',
        configFileName: '',
        timestamp: '',
        codeByMd5: '',
        path: '',
        delFlag: '',
        description: '',
        source: ''
      },

      // 配置文件数组
      configList: [],
      //
      deviceList: [],
      configFileDialogVisible: false,
      content: '',
      title: '',
      multipleSelectionMain: [],
      // 下载到设备的多选框
      multipleSelectionDownload: [],
      beginItem: 1,
      endItem: 100,
      total: 100,
      currentPage: 1,
      pageSize: 100
    }
  },

  computed: {
    deleteCommand () {
      return ConfigFileCommands.deleteConfigCommand(this.deleteList, this.commandContext)
    },
    updateCommand () {
      return ConfigFileCommands.updateConfigCommand(this.updateInitList, this.commandContext)
    },
    localToDeviceCommand () {
      return ConfigFileCommands.localConfigToDeviceCommand(this.updateInitList, this.commandContext)
    },

    downloadConfigToDeviceCommand () {
      return ConfigFileCommands.downloadConfigToDeviceCommand(this.updateConfigFileKey, this.commandContext)
    },

    UploadConfigToDeviceCommand () {
      return ConfigFileCommands.uploadConfigToDeviceCommand(this.updateConfigFileKey, this.commandContext)
    },

    importCommand () {
      return ConfigFileCommands.importConfigCommand(this.commandContext)
    }
  },
  methods: {
    /**
     * @Description  : bianhua
     * @author       : ls
     * @date         : 2020/7/16 15:06
     * @param        :
     * @return       :
     */
    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.configFileByConditionCurrentPage()
    },
    /**
     * @Description  : 条件查询
     * @author       : ls
     * @date         : 2020/7/16 14:52
     * @param        :
     * @return       :
     */
    queryConfigFileDataByCondition: function () {
      this.beginItem = 1
      this.setSelectList()
      this.queryConfigFileTotalNumber()
    },
    /**
     * @Description  : 总数
     * @author       : ls
     * @date         : 2020/7/16 14:52
     * @param        :
     * @return       :
     */
    queryConfigFileTotalNumber: function () {
      let _this = this
      let loadingInstance = _this.Loading.openLoading()
      ConfigFileService.queryConfigFileTotalNumber(_this.selectList).then(result => {
        _this.Loading.closeLoading(loadingInstance)
        _this.total = result
        if (_this.total === 0 || _this.total < 0) {
          _this.configList = []
          _this.InfoTip.warningTip_alarm(_this, HelperUtil.getCheckStatusCodeObjectByCode(_this.successCode.QUERY_NULL_CODE))
        } else {
          if (_this.total < 100 && _this.total > 0) {
            _this.endItem = _this.total
          } else {
            _this.endItem = 100
          }
          _this.InfoTip.successTip(_this, HelperUtil.getStatusCodeObjectByCode(_this.successCode.QUERY_CODE))
          _this.configFileByConditionCurrentPage()
        }
      }).catch(err => {
        _this.endItem = 100
        _this.Loading.closeLoading(loadingInstance)
        _this.InfoTip.errorTip(_this, err)
      })
    },
    /**
     * @Description  :
     * @author       : ls
     * @date         : 2020/7/16 14:45
     * @param        :
     * @return       :
     */
    queryConfigFile: function () {
      this.beginItem = 1
      this.setSelectList()
      let _this = this
      let loadingInstance = _this.Loading.openLoading()
      ConfigFileService.queryConfigFileTotalNumber(_this.selectList).then(result => {
        _this.Loading.closeLoading(loadingInstance)
        _this.total = result
        if (_this.total === 0 || _this.total < 0) {
          _this.configList = []
        } else {
          if (_this.total < 100 && _this.total > 0) {
            _this.endItem = _this.total
          } else {
            _this.endItem = 100
          }
          _this.configFileByConditionCurrentPage()
        }
      }).catch(err => {
        _this.endItem = 100
        _this.Loading.closeLoading(loadingInstance)
        _this.InfoTip.errorTip(_this, err)
      })
    },
    /**
     * @Description  : 条件查询
     * @author       : ls
     * @date         : 2020/7/16 14:48
     * @param        :
     * @return       :
     */
    configFileByConditionCurrentPage: function () {
      let _this = this
      let loadingInstance = _this.Loading.openLoading()
      ConfigFileService.queryConfigFileDataSplitNumber(_this.beginItem, _this.endItem, _this.selectList).then(result => {
        // 成功
        _this.configList = Object.values(result)
        _this.Loading.closeLoading(loadingInstance)
      }).catch(err => {
        // 失败
        _this.Loading.closeLoading(loadingInstance)
        _this.InfoTip.errorTip(_this, err)
      })
    },
    /**
     * @Description  : 格式化
     * @author       : ls
     * @date         : 2020/7/16 14:46
     * @param        :
     * @return       :
     */
    formatSource: function (row, column) {
      if (row.source === 0) {
        return this.$t('ProfileManagement.LocalUpload')
      } else if (row.source === 1) {
        return this.$t('ProfileManagement.DeviceUpload')
      }
    },
    /**
     * @Description  : 查询条件
     * @author       : ls
     * @date         : 2020/7/16 14:42
     * @param        :
     * @return       :
     */
    setSelectList: function () {
      this.selectList = []
      if (this.beginTimestamp !== null && this.beginTimestamp !== '') {
        this.selectList.push({
          quaryAttribute: 'timestamp',
          compareSymbol: '>',
          compareValue: HelperUtil.getTimeInit(this.beginTimestamp) + this.addTimestamp
        })
      }
      if (this.endTimestamp !== '' && this.endTimestamp !== null) {
        this.selectList.push({
          quaryAttribute: 'timestamp',
          compareSymbol: '<',
          compareValue: HelperUtil.getTimeInit(this.endTimestamp) + this.addTimestamp1
        })
      }
      if (this.source !== '' && this.source !== null) {
        this.selectList.push({
          quaryAttribute: 'source',
          compareSymbol: '=',
          compareValue: this.source
        })
      }
      if (this.chooseDevice !== '' && this.chooseDevice !== null) {
        this.selectList.push({
          quaryAttribute: 'deviceKey',
          compareSymbol: '=',
          compareValue: this.chooseDevice
        })
      }
    },
    /**
       * @Description  :主页面表格多选框改变时，将所选行进行保存
       * @author       :
       * @param        :
       * @return       :
       * @exception    :
       * @date         :
       */
    handleSelectionChangeMain (val) {
      this.multipleSelectionMain = val
    },
    /**
     * @Description  : 格式化时间
     * @author       : ls
     * @date         : 2020/7/16 11:21
     * @param        :
     * @return       :
     */
    formatTime: function (val) {
      return HelperUtil.timeTran(val.timestamp)
    },
    /**
       * @Description  :获取全部网元信息
       * @author       ::
       * @date         :
       */
    getAllDevice: function () {
      let _this = this
      console.log('获取全部网元信息:')
      DeviceService.getAllDeviceCollection().then(result => {
        // 成功
        _this.deviceList = Object.values(result)
      }).catch(err => {
        // 失败
        _this.InfoTip.errorTip(_this, err)
      })
    },
    /**
     * @Description  : 开始时间
     * @author       : ls
     * @date         : 2020/6/12 9:03
     * @param        :
     * @return       :
     */
    beginDate: function () {
      return {
        disabledDate: time => {
          if (this.endTimestamp) {
            return (
              time.getTime() > new Date(this.endTimestamp).getTime()
            )
          }
        }
      }
    },
    /**
     * @Description  : 结束时间
     * @author       : ls
     * @date         : 2020/6/12 9:05
     * @param        :
     * @return       :
     */
    endDate: function () {
      return {
        disabledDate: time => {
          if (this.beginTimestamp) {
            return (
              time.getTime() < new Date(this.beginTimestamp).getTime()
            )
          }
        }
      }
    },
    /**
     * @Description  : 本地上传
     * @author       : ls
     * @date         : 2020/7/16 11:22
     * @param        :
     * @return       :
     */
    localUpload: function () {
      this.importCommand.execute()
    },
    /**
     * @Description  : 设备上传
     * @author       : ls
     * @date         : 2020/7/16 11:22
     * @param        :
     * @return       :
     */
    equipmentToUpload: function () {
      this.UploadConfigToDeviceCommand.execute()
    },

    /**
     * @Description  : 下载到设备
     * @author       : ls
     * @date         : 2020/7/16 11:19
     * @param        :
     * @return       :
     */
    downloadToDeviceInit: function (val) {
      this.updateConfigFileKey = val.configFileKey
      this.downloadConfigToDeviceCommand.execute()
    },
    /**
     * @Description  : 下载到本地
     * @author       : ls
     * @date         : 2020/7/16 11:19
     * @param        :
     * @return       :
     */
    downloadToLocal: function (val) {
      let _this = this
      let loadingInstance = this.Loading.openLoading()
      ConfigFileService.downloadConfigFile(val.configFileKey, val.configFileName).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
    },
    /**
     * @Description  : 查看配置文件
     * @author       : ls
     * @date         : 2020/11/2 15:58
     * @param        :
     * @return       :
     */
    viewDetail: function (row) {
      let this_ = this
      this_.title = row.configFileName
      ConfigFileService.viewConfigFile(row.configFileKey).then(result => {
        this_.readFile(result)
      }).catch(err => {
        this_.InfoTip.errorTip(this, err)
      })
    },
    /**
     * @Description  : 读取文件
     * @author       : ls
     * @date         : 2020/11/2 16:04
     * @param        :
     * @return       :
     */
    readFile (result) {
      let _this = this
      var fr = new FileReader()
      fr.addEventListener('load', function (ev) {
        _this.content = ev.target.result
        _this.configFileDialogVisible = true
      })
      fr.readAsText(result)
    },
    /**
       * @Description  :修改配置文件始化
       * @author       :
       * @date         :
       */
    updateConfInit: function () {
      if (this.multipleSelectionMain.length == 0) {
        this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.UPDATE_SELECT_CODE))
      } else if (this.multipleSelectionMain.length > 1) {
        this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.UPDATE_ONLY_ONE_CODE))
      } else {
        this.updateInitList = this.multipleSelectionMain[0]
        this.currentRow = this.multipleSelectionMain[0]
        var tempSource = this.currentRow.source

        if (this.currentRow.source == 0) { tempSource = this.$t('ProfileManagement.LocalUpload') } else if (this.currentRow.source == 1) { tempSource = this.$t('ProfileManagement.DeviceUpload') }
        this.updateInitList.source = tempSource
        this.updateCommand.execute()
      }
    },
    oneKeyUpload: function () {
      this.localToDeviceCommand.execute()
    },
    /**
     * @Description  : 删除
     * @author       : ls
     * @date         : 2020/7/16 13:56
     * @param        :
     * @return       :
     */
    deleteConfigInit: function () {
      if (this.multipleSelectionMain.length == 0) {
        this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.DELETE_SELECT_CODE))
      } else {
        this.deleteList = []
        for (var i = 0; i < this.multipleSelectionMain.length; i++) {
          this.deleteList[i] = this.multipleSelectionMain[i]['configFileKey']
        }
        this.deleteCommand.execute()
      }
    }
  },
  created: function () {
    this.queryConfigFile()
    this.getAllDevice()
  },
  watch: {
    commandContext (newVal, oldVal) {
      if (JSON.stringify(newVal) === '{}') {
        this.queryConfigFile()
        this.$refs.singleTable.clearSelection()
      }
      deep: true
    }
  }

}
</script>
<style scoped>
</style>
