<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="importToExcelInit"
                     v-if="importCabinetCommand.visible">{{$t('common.importBtn')}}</el-button>
          <el-button size = 'mini' icon="el-icon-download" type="primary" @click="exportToExcelInit">{{$t('common.exportBtn')}}</el-button>
          <el-button size = 'mini' icon="el-icon-circle-plus-outline" type="primary" @click="createCabinetInit"
                     v-if="createAndCopyCommand.visible">{{$t('common.createBtn')}}</el-button>
          <el-button size = 'mini' icon="el-icon-document" type="primary" @click="copyCabinetInit"
                     v-if="createAndCopyCommand.visible">{{$t('common.copyBtn')}}</el-button>
          <el-button size = 'mini' icon="el-icon-edit" type="primary" @click="updateCabinetInit"
                     v-if="updateCabinetCommand.visible">{{$t('common.updateBtn')}}</el-button>
          <el-button size = 'mini' icon="el-icon-delete" type="primary" @click="deleteCabinetInit"
                     v-if="deleteCabinetCommand.visible">{{$t('common.deleteBtn')}}</el-button>
          <!--<el-button size = 'mini' icon="el-icon-delete" type="primary" @click="TestSessionID">测试SessionID</el-button>-->
        </div>
        <!-- 条件查询工具栏 -->
        <div class="header-search">
          <div class="search-input-box">
            <label>{{$t('CabinetConfigurationManagement.CabinetNameQuery')}}</label>
            <el-input size = 'mini' :placeholder="$t('common.placeholder')"  v-model="querySelectName" clearable></el-input>
          </div>
          <div class="search-input-box">
            <label>{{$t('CabinetConfigurationManagement.BelongLocationQuery')}}</label>
            <el-select v-model="querySelectBelong" size="mini" :placeholder="$t('CabinetConfigurationManagement.SelectLocation')" :clearable="true">
              <el-option
                v-for="item in QueryLocationList"
                :key="item.locationKey"
                :label="item.locationName"
                :value="item.locationKey">
              </el-option>
            </el-select>
          </div>
          <div class="search-input-box">
            <label>{{$t('CabinetConfigurationManagement.CabinetTypeQuery')}}</label>
            <el-input size = 'mini' :placeholder="$t('common.placeholder')"  v-model="querySelectType" clearable></el-input>
          </div>
          <div class="search-input-box">
            <el-button icon="el-icon-search" type="primary" size = 'mini' @click="queryCabinetByCondition" 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="CabinetList"
          highlight-current-row
          @current-change="handleCurrentChange"
          @selection-change="handleSelectionChange">

          <el-table-column
            type="selection"
            width="28">
          </el-table-column>
          <el-table-column
            prop="cabinetKey"
            label="主键"
            v-if="false">
          </el-table-column>
          <el-table-column
            :show-overflow-tooltip="true"
            prop="cabinetName"
            :label="$t('CabinetConfigurationManagement.CabinetNameColumn')">
          </el-table-column>
          <el-table-column
            :show-overflow-tooltip="true"
            prop="cabinetType"
            :label="$t('CabinetConfigurationManagement.CabinetTypeColumn')">
          </el-table-column>
          <el-table-column
            :show-overflow-tooltip="true"
            prop="locationKey"
            :label="$t('CabinetConfigurationManagement.BelongLocationColumn')"
            :formatter="formatLocationKey"
            width="200">
          </el-table-column>

          <el-table-column
            prop="height"
            :label="$t('CabinetConfigurationManagement.Height')"
            width="100"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="depth"
            :label="$t('CabinetConfigurationManagement.Deep')"
            width="100"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="width"
            :label="$t('CabinetConfigurationManagement.Width')"
            width="100"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="frameCount"
            :label="$t('CabinetConfigurationManagement.FrameCount')"
            width="80"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="voltage"
            :label="$t('CabinetConfigurationManagement.Voltage')"
            width="80"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            :label="$t('common.look')">
            <template slot-scope="scope">
              <el-row type="flex">
                <el-button
                  style="margin-top:-3.8px"
                  size="mini"
                  type="text"
                  @click="handleSelectDevice(scope.$index, scope.row)">{{$t('common.device')}}</el-button>
              </el-row>
            </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 CabinetService from '@/domain/services/CabinetService'
  import LocationService from '@/domain/services/LocationService'
  import HelperUtil from '@/utils/HelperUtil'

  let protocal = '';
  let ip = '';
  let project = '';
  let port= '';
  let port2= port.substring(1);
  export default {
    name: 'CabinetConfigurationManagement',
    components: {
      CommandExecuteContext,
    },

    data: function () {   //存放数据
      return {
        //命令
        commandContext: {},
        //为了创建复制初始化传参
        createAndCopyInitList: [],
        createAndCopyTitle: '',
        //删除相关
        deleteList: [],
        //为修改传参数
        updateInitList: [],

        //window.innerHeight:浏览器的可用高度
        fullscreenLoading: false,

        //条件查询
        querySelectName: "", //条件查询机房名
        querySelectType: "",//条件查询机架类型
        querySelectBelong: "",//条件查询所属机房

        formLabelWidth: '120px',

        //双向绑定弹出窗口iput域
        form:{
          cabinetKey: "",
          locationKey: "",
          cabinetName: "",
          cabinetType: "",
          height: "",
          depth: "",
          width: "",
          frameCount: "",
          voltage: "",
        },

        //双向绑定展示数据
        CabinetList: [],
        //双向绑定展示数据
        QueryLocationList: [],
        value: '',
        //保存当前行数据
        currentRow: null,
        //保存多选行数据
        multipleSelection: [],
      }
    },

    computed: {
      openTab () {
        return this.$store.state.openTab;
      },
      activeIndex:{
        get () {
          return this.$store.state.activeIndex;
        },
        set (val) {
          this.$store.commit('set_active_index', val);
        }
      },

      //命令
      createAndCopyCommand(){
        return CabinetCommands.createAndCopyCabinetCommand(this.createAndCopyTitle, this.createAndCopyInitList, this.commandContext)
      },
      deleteCabinetCommand(){
        return CabinetCommands.deleteCabinetCommand(this.deleteList, this.commandContext)
      },
      updateCabinetCommand(){
        return CabinetCommands.updateCabinetCommand(this.updateInitList, this.commandContext)
      },
      importCabinetCommand(){
        return CabinetCommands.importCabinetCommand(this.commandContext)
      },
    },

    //vue加载初始化函数，加载数据
    created:function(){
      //如果是由机房界面带参调用则初始化执行条件查询，否则执行全部查询
      if(this.$route.query.locationKey!=null){
        //跳转条件查询框初始化对应机房名称值
        this.querySelectBelong = this.$route.query.locationKey;
        this.TurnFromLocation(this.$route.query.locationKey);
      }else{
        //获取所有机架信息
        this.getAllCabinetInit()
      }
      //额外获取所有关联机房信息
      this.getAllLocation()
    },
    methods: {

      /**
       * @Description  ：单选一行，将所选行进行保存
       * @date         : 2018/12/11 19:47
       */
      handleCurrentChange(val) {
        this.currentRow = val;
      },

      /**
       * @Description  ：表格多选框改变时，将所选行进行保存
       * @date         : 2018/12/14 14:05
       */
      handleSelectionChange (val) {
        this.multipleSelection = val
      },

      /**
       * @Description  ：过滤locationKey，转为显示lacationName（测试成功）
       * @date         : 2018/12/21 00:28
       */
      formatLocationKey: function (row, column){
        for(var i= 0;i<this.QueryLocationList.length;i++){
          if(this.QueryLocationList[i]['locationKey']==row.locationKey){
            return this.QueryLocationList[i]['locationName']
            break;
          }
        }
      },

      /**
       * @Description  ：单选一行，跳转设备配置界面，初始化加载该机架对应设备数据（测试成功）
       * @date         : 2018/12/21 15:19
       */
      handleSelectDevice(index,row){
        let flag = false;
        for (let item of this.openTab) {
          if (item.name === '网元配置') {
            this.$store.commit('delete_keepAliveRouter', 'DeviceConfigurationManagement')
            this.$store.commit('delete_tabs', '/TheLayout/DeviceConfigurationManagement')
            this.$store.commit('add_tabs', {route: '/TheLayout/DeviceConfigurationManagement', name: '网元配置',title:'TheLayoutHeader.deviceConfigurationManagement'})
            this.$store.commit('set_active_index', '/TheLayout/DeviceConfigurationManagement')
            this.$store.commit('add_keepAliveRouter', 'DeviceConfigurationManagement');
            this.$router.push({path: '/TheLayout/DeviceConfigurationManagement',query:{cabinetKey:row.cabinetKey,locationFromCabinet:row.locationKey}});
            flag = true;
            break;
          }
        }
        if(!flag){
          this.$store.commit('add_tabs', {route: '/TheLayout/DeviceConfigurationManagement', name: '网元配置',title:'TheLayoutHeader.deviceConfigurationManagement'})
          this.$store.commit('add_keepAliveRouter', 'DeviceConfigurationManagement');
          this.$store.commit('set_active_index', '/TheLayout/DeviceConfigurationManagement')
          this.$router.push({path: '/TheLayout/DeviceConfigurationManagement',query:{cabinetKey:row.cabinetKey,locationFromCabinet:row.locationKey}});
        }
      },

      /**
       * @Description  ：为实现界面Key转Name过滤，先行获取机房消息（测试成功）
       * @date         : 2018/12/21 00:20
       */
      getAllLocation: function (){
        let _this = this;
        LocationService.getAllLocationCollection().then(result => {
          //成功
          _this.QueryLocationList = Object.values(result)
        }).catch(err =>{
          //失败
        })
      },

      /**
       * @Description  ：获取全部机架信息（已调通）
       * @date         : 2018/12/11 19:51
       */
      getAllCabinetInit: function () {
        let _this = this;
        CabinetService.getAllCabinetCollection().then(result => {
          //成功
          _this.CabinetList = Object.values(result)
        }).catch(err =>{
          //失败
        })
      },

      /**
       * @Description  ：增删改后调用，重新加载table（已调通）
       * @date         : 2018/12/11 20:03
       */
      getAllCabinet: function (vue) {
        let _this = vue;
        CabinetService.getAllCabinetCollection().then(result => {
          //成功
          _this.CabinetList = Object.values(result)
        }).catch(err =>{
          //失败
        })
      },

      /**
       * @Description  ：创建机架初始化（含下拉列表，已调通）
       * @date         : 2018/12/14 11:40
       */
      createCabinetInit:function () {
        this.createAndCopyTitle = this.$t('CabinetConfigurationManagement.dialogCabinetCreate');
        this.createAndCopyInitList = {
          "cabinetKey":"",
          "locationKey":"",
          "cabinetName":"",
          "cabinetType":"",
          "height":"",
          "depth":"",
          "width":"",
          "frameCount":"",
          "voltage":"",
          "delFlag": '',
          "modifyTime": ""
        };
        this.createAndCopyCommand.execute();
      },

      /**
       * @Description  ：修改机架信息初始化（含下拉列表，已调通）
       * @date         : 2018/12/14 13:41
       */
      updateCabinetInit: function () {
        if(this.multipleSelection.length == 0){
          //请选择一条信息进行修改
          this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.UPDATE_SELECT_CODE))
          return;
        }else if(this.multipleSelection.length > 1){
          //请只选择一条信息进行修改
          this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.UPDATE_ONLY_ONE_CODE))
          return;
        }else {
          this.updateInitList = {
            "cabinetKey":this.multipleSelection[0].cabinetKey,
            "locationKey":this.multipleSelection[0].locationKey,
            "cabinetName":this.multipleSelection[0].cabinetName,
            "cabinetType":this.multipleSelection[0].cabinetType,
            "height":this.multipleSelection[0].height,
            "depth":this.multipleSelection[0].depth,
            "width":this.multipleSelection[0].width,
            "frameCount":this.multipleSelection[0].frameCount,
            "voltage":this.multipleSelection[0].voltage,
            "delFlag": '',
            "modifyTime": ""
          };
          this.updateCabinetCommand.execute();
        }
      },


      /**
       * @Description  ：复制机架信息初始化（含向下拉列表，已调通）
       * @date         : 2018/12/14 13:37
       */
      copyCabinetInit: function () {
        if(this.multipleSelection.length == 0){
          //请选择一条信息进行复制
          this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.COPY_SELECT_CODE))
          return;
        }else if(this.multipleSelection.length > 1){
          //请只选择一条信息进行复制
          this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.COPY_ONLY_ONE_CODE))
          return;
        }else{
          this.createAndCopyTitle = this.$t('CabinetConfigurationManagement.dialogCabinetCopy');
          this.createAndCopyInitList = {
            "cabinetKey":this.multipleSelection[0].cabinetKey,
            "locationKey":this.multipleSelection[0].locationKey,
            "cabinetName":this.multipleSelection[0].cabinetName,
            "cabinetType":this.multipleSelection[0].cabinetType,
            "height":this.multipleSelection[0].height,
            "depth":this.multipleSelection[0].depth,
            "width":this.multipleSelection[0].width,
            "frameCount":this.multipleSelection[0].frameCount,
            "voltage":this.multipleSelection[0].voltage,
            "delFlag": '',
            "modifyTime": ""
          };
          this.createAndCopyCommand.execute();
        }
      },

      /**
       * @Description  ：删除机架信息初始化（支持批量删除，已调通）
       * @date         : 2018/12/14 14:37
       */
      deleteCabinetInit: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]['cabinetKey']);
            var obj = {'cabinetKey': this.multipleSelection[i]['cabinetKey']}
            this.deleteList.push(obj)
          }
          this.deleteCabinetCommand.execute()
        }
      },

      /**
       * @Description  ：条件查询（或逻辑关系查询，已调通）
       * @param        : 列表形式[{查询特征、比较方法（等于）、查询值}]
       * @date         : 2018/12/14 19:28
       */
      queryCabinetByCondition: function () {
        if(this.querySelectName == '' && this.querySelectType == '' && this.querySelectBelong == ''){
          //所有查询条件为空点查询--》重新刷新表格
          this.$options.methods.getAllCabinet(this);
          loading.close();
          return;
        }
        var selectList = new Array();
        if(this.querySelectName != ''){
          selectList.push({ quaryAttribute:'cabinetName',
            compareSymbol:"like",
            compareValue:this.querySelectName,})
        }
        if(this.querySelectType != ''){
          selectList.push({ quaryAttribute:'cabinetType',
            compareSymbol:"like",
            compareValue:this.querySelectType,})
        }
        if(this.querySelectBelong != ''&&this.querySelectBelong !=null){
          selectList.push({ quaryAttribute:'locationKey',
            compareSymbol:"=",
            compareValue:this.querySelectBelong,})
        }
        //按条件查询
        let _this = this;
        let loadingInstance = _this.Loading.openLoading();
        CabinetService.conditionQueryCabinet(selectList).then(result => {
          //成功
          _this.CabinetList= Object.values(result);
          _this.Loading.closeLoading(loadingInstance);
          if(_this.CabinetList.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  ：导入文件，有待实现
       */
      importToExcelInit:function () {
        this.importCabinetCommand.execute()
      },

      /**
       * @Description  ：导出文件（测试成功版）
       * @date         : 2018/12/22 01:28
       */
      exportToExcelInit:function () {
        //传参
        var selectList = new Array();
        if(this.querySelectName != ''){
          selectList.push({ quaryAttribute:'cabinetName',
            compareSymbol:"like",
            compareValue:this.querySelectName,})
        }
        if(this.querySelectType != ''){
          selectList.push({ quaryAttribute:'cabinetType',
            compareSymbol:"like",
            compareValue:this.querySelectType,})
        }
        if(this.querySelectBelong != ''&& this.querySelectBelong !=null){
          selectList.push({ quaryAttribute:'locationKey',
            compareSymbol:"like",
            compareValue:this.querySelectBelong ,})
        }
        let loadingInstance = this.Loading.openLoading();
        CabinetService.downloadCabinet(selectList).then(result => {
          //成功
          this.Loading.closeLoading(loadingInstance);
        }).catch(err => {
          //失败
          this.Loading.closeLoading(loadingInstance);
          this.InfoTip.errorTip(this, err);
        })
      },

      /**
       * @Description  ：由机房转入机架（已调通）
       * @date         : 2018/12/21 20:10
       */
      TurnFromLocation:function (msg) {
        var selectList = new Array();
        selectList.push({ quaryAttribute:'locationKey',
          compareSymbol:"like",
          compareValue:msg,})
        //按条件查询
        let _this = this;
        CabinetService.conditionQueryCabinet(selectList).then(result => {
          //成功
          _this.CabinetList= Object.values(result)
          if(_this.CabinetList.length == 0){
            //查询为空
            _this.InfoTip.warningTip(_this, HelperUtil.getCheckStatusCodeObjectByCode(_this.successCode.QUERY_NULL_CODE))
          }
        }).catch(err => {
          //失败
          _this.InfoTip.errorTip(_this, err);
        })
      }

    },

    beforeCreate: function () {},

    watch: {
      '$route'(to, from) {
        // 对路由变化作出响应...
        if(to.name === '机架配置' && to.query.locationKey !== undefined){
          this.querySelectBelong = to.query.locationKey;
          this.TurnFromLocation(to.query.locationKey);
        }
      },
      commandContext(newVal, oldVal){
        if(JSON.stringify(newVal) === '{}'){
          this.querySelectName = ''
          this.querySelectType = ''
          this.querySelectBelong = null
          this.getAllCabinet(this)
          this.$refs.singleTable.clearSelection();
        }
        deep: true
      },
    }
  }
</script>

<style scoped>
</style>
