<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="importSubnetCommand.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="createSubnetInit" v-if="createAndCopyCommand.visible">
            {{$t("common.createBtn")}}
          </el-button>
          <el-button size='mini' icon="el-icon-document" type="primary" @click="copySubnetInit" v-if="createAndCopyCommand.visible">
            {{$t("common.copyBtn")}}
          </el-button>
          <el-button size='mini' icon="el-icon-edit" type="primary" @click="updateSubnetInit" v-if="updateSubnetCommand.visible">
            {{$t("common.updateBtn")}}
          </el-button>
          <el-button size='mini' icon="el-icon-delete" type="primary" @click="deleteSubnetInit" v-if="deleteSubnetCommand.visible">{{$t("common.deleteBtn")}}</el-button>
        </div>
        <div class="header-search">
          <div class="search-input-box">
            <label>{{ $t('SubnetConfigurationManagement.subnetName') }}：</label>
            <el-input width="200" size='mini' :placeholder="$t('common.placeholder')" v-model="querySubnetNameInput" clearable></el-input>
          </div>
          <div class="search-input-box">
            <label>{{ $t('SubnetConfigurationManagement.domain') }}：</label>
            <el-input size='mini' :placeholder="$t('common.placeholder')" v-model="queryDomainInput" clearable></el-input>
          </div>
          <div class="search-input-box">
            <el-button icon="el-icon-search" type="primary" size='mini' @click="querySubnetByCondition"
                       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')"
          tooltip-effect="dark"
          ref="singleTable"
          :data="subnetList"
          stripe
          header-row-class-name="table-header"
          cell-class-name="table-cell"
          class="adapt-height"
          height="auto"
          border
          @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            width="28">
          </el-table-column>
          <el-table-column
            prop="subnetKey"
            v-if="false"
            :label="$t('SubnetConfigurationManagement.subnetID')">
          </el-table-column>
          <el-table-column
            prop="subnetName"
            width="400"
            :label="$t('SubnetConfigurationManagement.subnetName')"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="domain"
            width="600"
            :label="$t('SubnetConfigurationManagement.domain')"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column

            :label="$t('common.look')">
            <template slot-scope="scope">
              <el-row type="flex" justify="left">
                <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 SubnetCommands from '@/commands/SubnetCommands'
  import SubnetService from '@/domain/services/SubnetService'
  import loading from "../../../utils/Loading";
  import HelperUtil from "../../../utils/HelperUtil";

  //loading提示

  export default {
    name: 'SubnetConfigurationManagement',

    components: {
      CommandExecuteContext,
    },

    data: function () {   //存放 数据
      return {
        //命令
        commandContext: {},

        //为了创建复制初始化传参
        createAndCopyInitList: [],
        createAndCopyTitle: '',

        //删除相关
        deleteList: [],

        //为修改传参数
        updateInitList: [],

        //条件查询输入框
        querySubnetNameInput: null,
        queryDomainInput: null,


        formLabelWidth: '120px',
        form: {
          subnetKey:null,
          subnetName: null,
          domain: null,
        },
        subnetList: [],

//        subnetList: [{
//          "subnetKey": "15541176417580002",
//          "subnetName": "管理子网D",
//          "domain": "管理",
//          "delFlag": 0,
//          "modifyTime": "20190401.192616.208"
//        },
//          {
//            "subnetKey": "15465836484220006",
//            "subnetName": "管理子网",
//            "domain": "管理子网",
//            "delFlag": 0,
//            "modifyTime": "20190401.190151.085"
//          },
//          {
//            "subnetKey": "15532219201460000",
//            "subnetName": "11111",
//            "domain": "",
//            "delFlag": 0,
//            "modifyTime": "20190322.103200.146"
//          },
//          {
//            "subnetKey": "15483851078070000",
//            "subnetName": "业务子网",
//            "domain": "业务",
//            "delFlag": 0,
//            "modifyTime": "20190318.180212.254"
//          }
//        ],

        multipleSelection: [],

        // 数据加载过程中，覆盖界面
        fullscreenLoading: false,
      }
    },

    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 SubnetCommands.createAndCopySubnetCommand(this.createAndCopyTitle, this.createAndCopyInitList, this.commandContext)
      },

      deleteSubnetCommand(){
        return SubnetCommands.deleteSubnetCommand(this.deleteList, this.commandContext)
      },
      updateSubnetCommand(){
        return SubnetCommands.updateSubnetCommand(this.updateInitList, this.commandContext)
      },
      importSubnetCommand(){
        return SubnetCommands.importSubnetCommand(this.commandContext)
      },
    },

    methods: {
      /**
       * @Description  ：单选一行，跳转设备配置界面，初始化加载该子网数据
       * @author       : bjh
       * @param        :
       * @return       :
       * @exception    :
       * @date         : 2018/12/20 11:02
       */
      handleSelectDevice(index, row) {
        console.log('查看设备：')
        let flag = false;
        for (let item of this.openTab) {
          console.log("item.name", item.name)
          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: {subnetKey: row.subnetKey}});
            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: {subnetKey: row.subnetKey}});
        }
      },

      /**
       * @Description  ：表格多选框改变时，将所选行进行保存
       * @author       : bjh
       * @param        :
       * @return       :
       * @exception    :
       * @date         : 2018/12/7 13:48
       */
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },

      /**
       * @Description  ：在表格数据重新载入时，对条件查询框进行清空
       * @author       : bjh
       * @param        :
       * @return       :
       * @exception    :
       * @date         : 2019/1/10 19:03
       */
      clearQueryInput: function (vue) {
        vue.querySubnetNameInput = '';
        vue.queryDomainInput = '';
      },
//
      /**
       * @Description  ：获取全部子网信息
       * @author       : bjh
       * @param        :
       * @return       :
       * @exception    :
       * @date         : 2018/12/7 14:06
       */
      getAllSubnetInit: function () {
        let _this = this
        console.log('获取全部子网信息：')
        //为了测试其他先注释了
        let loadingInstance=loading.openLoading();
         SubnetService.getAllSubnetCollection().then(result => {
          //成功
           _this.subnetList = Object.values(result)
           loadingInstance.close();

         }).catch(err =>{
          //失败
           //this.$message.error('Error ' + err.errorCode+":"+err.errorCause)
           this.InfoTip.errorTip(this,err);
           loadingInstance.close();
        })

      },

      /**
       * @Description  ：增删改后调用，重新加载table
       * @author       : bjh
       * @param        :
       * @return       :
       * @exception    :
       * @date         : 2018/12/7 14:06
       */
      getAllSubnet: function (vue) {
        console.log('获取全部子网信息：')
        //为了测试其他先注释了
        let loadingInstance=loading.openLoading();
        SubnetService.getAllSubnetCollection().then(result => {
          //成功

         vue.subnetList = Object.values(result)
         loadingInstance.close();
        }).catch(err =>{
          //失败
         //vue.$message.error('Error ' + err.errorCode+":"+err.errorCause)
          this.InfoTip.errorTip(this,err);
          loadingInstance.close();
        })
      },

      /**
       * @Description  ：创建子网初始化
       * @author       : bjh
       * @param        :
       * @return       :
       * @exception    :
       * @date         : 2018/12/7 13:29
       */
      createSubnetInit: function () {
        this.createAndCopyTitle = this.$t('SubnetConfigurationManagement.createSubnetInfo');//{{$t('DeviceConfigurationManagement.copyDeviceInfo')"}}

        this.createAndCopyInitList = {
          "subnetKey": "",
          "subnetName": "",
          "domain": "",
          "delFlag": '',
          "modifyTime": ""
        };
        this.createAndCopyCommand.execute();
      },

      /**
       * @Description  ：复制子网信息初始化
       * @author       : bjh
       * @param        :
       * @return       :
       * @exception    :
       * @date         : 2018/12/22 12:20
       */
      copySubnetInit: 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('SubnetConfigurationManagement.copySubnetInfo');
          this.createAndCopyInitList = {
            "subnetKey": "",
            "subnetName": this.multipleSelection[0].subnetName,
            "domain": this.multipleSelection[0].domain,
            "delFlag": '',
            "modifyTime": ""
          }
          this.createAndCopyCommand.execute();
        }
      },

      /**
       * @Description  ：修改子网信息初始化
       * @author       : bjh
       * @param        :
       * @return       :
       * @exception    :
       * @date         : 2018/12/7 9:03
       */
      updateSubnetInit: 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 = {
            "subnetKey": this.multipleSelection[0].subnetKey,
            "subnetName": this.multipleSelection[0].subnetName,
            "domain": this.multipleSelection[0].domain,
            "delFlag": '',
            "modifyTime": ""
          };
          console.log( "修改初始化");
          console.log( this.updateInitList);
          this.updateSubnetCommand.execute();
        }
      },

      /**
       * @Description  ：删除子网信息初始化(支持批量)
       * @author       : bjh
       * @param        :
       * @return       :
       * @exception    :
       * @date         : 2018/12/7 13:32
       */
      deleteSubnetInit: 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]['subnetKey']);
            var obj = {'subnetKey': this.multipleSelection[i]['subnetKey']}
            this.deleteList.push(obj)
          }
          this.deleteSubnetCommand.execute()
        }
      },

      /**
       * @Description  ：条件查询
       * @author       : bjh
       * @param        :
       * @return       :
       * @exception    :
       * @date         : 2018/12/7 23:06
       */
      querySubnetByCondition: function () {

        console.log('子网信息按条件查询：')
        var selectList = new Array();
        if ((this.querySubnetNameInput == null || this.querySubnetNameInput == "") && (this.queryDomainInput == null || this.queryDomainInput == "")) {

          this.$options.methods.getAllSubnet(this);

          return;
        } else {
          if (this.querySubnetNameInput === null) {
            this.querySubnetNameInput = '';
          }
          if (this.queryDomainInput === null) {
            this.queryDomainInput = ''
          }
          if (this.querySubnetNameInput != '' || this.querySubnetNameInput != null) {
            selectList.push({
              quaryAttribute: 'subnetName',
              compareSymbol: "like",
              compareValue: this.querySubnetNameInput,
            })
          }
          if (this.queryDomainInput != '' || this.queryDomainInput != null) {
            selectList.push({
              quaryAttribute: 'domain',
              compareSymbol: "like",
              compareValue: this.queryDomainInput,
            })
          }
        }
        let loadingInstance=loading.openLoading();
        //按条件查询
        let _this = this;
        SubnetService.conditionQuerySubnet(selectList).then(result => {

          //成功
          _this.subnetList = Object.values(result)
          _this.Loading.closeLoading(loadingInstance);
          if(_this.subnetList.length == 0){
            //查询为空
            _this.InfoTip.warningTip(_this, HelperUtil.getCheckStatusCodeObjectByCode(_this.successCode.QUERY_NULL_CODE))
          }else{
            _this.InfoTip.successTip(_this, HelperUtil.getStatusCodeObjectByCode(_this.successCode.QUERY_CODE));
          }
          console.log("查询成功")
        }).catch(err => {
          //失败
          //this.$message.error('Error ' + err.errorCode+":"+err.errorCause)
          this.InfoTip.errorTip(this,err);
          loadingInstance.close();
          console.log("查询失败")
        })

      },

      /**
       * @Description  ：导入文件
       * @author       : bjh
       * @param        :
       * @return       :
       * @exception    :
       * @date         : 2018/12/19 18:39
       */
      importToExcelInit: function () {
        console.log('导入文件：');
        this.importSubnetCommand.execute()
      },

      /**
       * @Description  ：导出文件
       * @author       : bjh
       * @param        :
       * @return       :
       * @exception    :
       * @date         : 2018/12/19 18:39
       */
      exportToExcelInit: function () {
//
        console.log('导出文件：')
        //传参
        var selectList = new Array();
        if ((this.querySubnetNameInput === null || this.querySubnetNameInput === '') && (this.queryDomainInput === null || this.queryDomainInput === '')) {
          selectList.push({
            quaryAttribute: 'subnetName',
            compareSymbol: "like",
            compareValue: '',
          });
          selectList.push({
            quaryAttribute: 'domain',
            compareSymbol: "like",
            compareValue: '',
          });
        } else {
          if (this.querySubnetNameInput === null) {
            this.querySubnetNameInput = '';
          }
          if (this.queryDomainInput === null) {
            this.queryDomainInput = ''
          }
          if (this.querySubnetNameInput != '' || this.querySubnetNameInput != null) {
            selectList.push({
              quaryAttribute: 'subnetName',
              compareSymbol: "like",
              compareValue: this.querySubnetNameInput,
            })
          }
          if (this.queryDomainInput != '' || this.queryDomainInput != null) {
            selectList.push({
              quaryAttribute: 'domain',
              compareSymbol: "like",
              compareValue: this.queryDomainInput,
            })
          }
        }

//        //传参需转换成JSON格式
//        var stringParams = JSON.stringify(selectList)
//
        let loadingInstance=loading.openLoading();
        SubnetService.downloadSubnet(selectList).then(result => {
          //成功
          this.InfoTip.successTip(this,HelperUtil.getStatusCodeObjectByCode(this.successCode.OTHERS_CODE));
          loadingInstance.close();
        }).catch(err => {
          //失败
          //this.$message.error('Error ' + err.errorCode+":"+err.errorCause)
          this.InfoTip.errorTip(this,err);
          loadingInstance.close();
        })
      },
    },

    beforeCreate: function () {

    },
    created: function () {


    },
    //初始化函数，加载数据
    mounted: function () {
      console.log("初始化加载数据");
      this.getAllSubnetInit()
    },
    watch: {
      commandContext(newVal, oldVal){
        if(JSON.stringify(newVal) === '{}'){
          this.querySubnetNameInput=''
          this.queryDomainInput=''
          // this.getAllSubnet(this)
          this.getAllSubnetInit()

          this.$refs.singleTable.clearSelection();
        }
        deep: true
      },
    },
  }
</script>

<style scoped>
</style>
