<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="uploadTopologicalCommand.visible"
                     @click="uploadTopologicalInit">{{$t('common.importBtn')}}
          </el-button>
          <el-button size='mini'  icon="el-icon-download" type="primary"
                     @click="downloadTopologicalInit">{{$t('common.exportBtn')}}
          </el-button>
          <el-button size='mini' icon="el-icon-switch-button" type="primary"
                     @click="enabledInit">{{$t("TopologicalDynamicConfiguration.enabled")}}
          </el-button>
          <el-button size='mini' icon="el-icon-error" type="primary"
                     @click="disabledInit">{{$t("TopologicalDynamicConfiguration.disabled")}}
          </el-button>
          <el-button size='mini' icon="el-icon-delete" type="primary" v-if="deleteTopologicalCommand.visible"
                     @click="deleteTopologicalInit" >{{$t('common.deleteBtn')}}
          </el-button>
        </div>
        <div class="header-search">
          <div class="search-input-box">
            <label>{{ $t('TopologicalDynamicConfiguration.topologicalName')}}:</label>
            <el-input size='mini' :placeholder="$t('common.placeholder')" v-model="queryTopologicalName"
                      clearable>
            </el-input>
          </div>
          <div class="search-input-box">
            <label>{{$t('TopologicalDynamicConfiguration.ServiceType')}}:</label>
            <el-select v-model="querySelectService" size="mini" :placeholder="$t('TopologicalDynamicConfiguration.selectServiceType')" :clearable="true">
              <el-option
                v-for="item in QueryServiceType"
                :key="item.serviceTypeKey"
                :label="item.serviceTypeName"
                :value="item.serviceTypeKey">
              </el-option>
            </el-select>
          </div>
          <div class="search-input-box">
            <label>{{$t('TopologicalDynamicConfiguration.status')}}:</label>
            <el-select v-model="queryStatus" size="mini" :placeholder="$t('TopologicalDynamicConfiguration.selectStatus')" :clearable="true">
              <el-option
                v-for="item in queryStatusList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div class="search-input-box">
            <el-button size='mini' icon="el-icon-search" type="primary" @click="queryTopoByCondition"
                       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"
          stripe
          header-row-class-name="table-header"
          cell-class-name="table-cell"
          class="adapt-height"
          height="auto"
          border
          ref="singleTable"
          :data="topoList"
          highlight-current-row
          :span-method="cellMerge"
          @current-change="handleCurrentChange"
          @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            width="28">
          </el-table-column>
          <el-table-column
            prop="topoKey"
            label="主键"
            v-if="false">
          </el-table-column>
          <el-table-column
            :show-overflow-tooltip="true"
            prop="topoName"
            :label="$t('TopologicalDynamicConfiguration.topologicalName')">
          </el-table-column>
          <el-table-column
            prop="serviceTypeKey"
            :label="$t('TopologicalDynamicConfiguration.serviceType')"
            :show-overflow-tooltip="true"
            :formatter="formatServiceType">
          </el-table-column>
          <el-table-column
            prop="activeFlag"
            :label="$t('TopologicalDynamicConfiguration.status')"
            :formatter="formatStatus"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="startNode"
            :label="$t('TopologicalDynamicConfiguration.startNodeDevice')"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="endNode"
            :label="$t('TopologicalDynamicConfiguration.endNodeDevice')"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="bandwidth"
            :label="$t('TopologicalDynamicConfiguration.bandwidth')"
            :show-overflow-tooltip="true">
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>
    <CommandExecuteContext v-bind:commands="commandContext"></CommandExecuteContext>
  </div>
</template>

<script>
  import TopologicalDynamicService from '@/domain/services/Business/TopologicalDynamicService.js'
  import TopologicalDynamicCommands from '@/commands/TopologicalDynamicCommands.js'
  import CommandExecuteContext from '@/commands/CommandExecuteContext'
  import HelperUtil from '@/utils/HelperUtil'
  import ServiceTypeService from '@/domain/services/Business/ServiceTypeService'
  import loading from "../../utils/Loading";
  import {LANGUAGE_LOCALSTORAGE} from "../../utils/constantCollection";

  export default {
    name: 'TopologicalDynamicConfiguration',
    data: function () {   //存放 数据
      return {
        commandContext: {},
        deleteList: [],   // 删除集合
        queryTopologicalName: "",
        querySelectService: "",
        queryStatus: "",
        queryStatusList: [{
          value: 1,
          label: this.$t('TopologicalDynamicConfiguration.enabled')
        }, {
          value: 0,
          label: this.$t('TopologicalDynamicConfiguration.disabled')
        }],

        QueryServiceType: [],
        topoList: [], // 拓扑集合

        enableList: [],
        disableList: [],

        serviceTypeList: [],

        deviceList: [],

        multipleSelection: [],   // 选中值
        currentRow: null,
        fullscreenLoading: false,
        selectList:[],
        enableString: '',
        disableString: '',

        // 命令
        configurationUpdateshow: false,
        formLabelWidth: '120px',

        contentSpanArr: [],
        position: 0,
      }
    },
    mounted: function () {
      this.getAllTopoInit()
      // this.getSpanArr()
    },
    components: {
      CommandExecuteContext,
    },
    watch: {
      commandContext (newVal, oldVal) {
        if (JSON.stringify(newVal) === '{}') {
          this.queryTopologicalName = ''
          this.querySelectService = ''
          this.queryStatus = ''
          this.getAllTopo(this);
          this.$refs.singleTable.clearSelection();
        }
        deep: true
      },

      '$i18n.locale' () {
        this.queryStatusList[0].label=this.$t('TopologicalDynamicConfiguration.enabled');
        this.queryStatusList[1].label=this.$t('TopologicalDynamicConfiguration.disabled');
      }
    },
    created: function () {
      this.getAllServiceType()
      this.getAllTopoInit()
      // this.getSpanArr(this.topoList)
    },
    computed: {
      openTab() {
        return this.$store.state.openTab;
      },
      activeIndex: {
        get() {
          return this.$store.state.activeIndex;
        },
        set(val) {
          this.$store.commit('set_active_index', val);
        }
      },
      uploadTopologicalCommand () {
        return TopologicalDynamicCommands.uploadTopologicalCommand(this.commandContext)
      },
      deleteTopologicalCommand () {
        return TopologicalDynamicCommands.deleteTopologicalCommand(this.deleteList, this.commandContext)
      },
      enableTopologicalCommand () {
        return TopologicalDynamicCommands.enableTopologicalCommand(this.enableString, this.commandContext)
      },
      disableTopologicalCommand () {
        return TopologicalDynamicCommands.disableTopologicalCommand(this.disableString, this.commandContext)
      },
    },
    methods: {
      /**
       * @Description  :单选一行,将所选行进行保存
       * @author       ::zyh
       */
      handleCurrentChange(val) {
        this.currentRow = val;
      },


      /**
       * @Description  :表格多选框改变时,将所选行进行保存
       * @author       ::zyh
       */
      handleSelectionChange(val) {
        this.multipleSelection = val
      },


      /**
       * @Description  :获取所有业务类型
       * @author       ::zyh
       */
      getAllServiceType: function () {
        let loadingInstance=loading.openLoading();
        let _this = this
        ServiceTypeService.getAllServiceTypeCollection().then(result => {
          //成功
          this.QueryServiceType =  Object.values(result)
        loadingInstance.close();
      }).catch(err => {
          //失败
          loadingInstance.close();
        this.InfoTip.errorTip(_this, err);
      })
      },

      /**
       * @Description  :获取所有动态拓扑信息
       * @author       ::zyh
       */
      getAllTopoInit: function () {
        let _this = this;
        TopologicalDynamicService.getAllTopologicalCollection().then(result => {
          // 成功
          _this.topoList = []
        var dynNodes= []
        let topoTmpList = Object.values(result)
        // alert(topoTmpList.topoKey)
        for(var i = 0;i < topoTmpList.length;i++){
          var topoKey = topoTmpList[i].topoKey;
          // alert(topoTmpList.topoKey)
          var topoName = topoTmpList[i].topoName;
          var serviceType = topoTmpList[i].serviceType;
          var bandwidth = topoTmpList[i].bandwidth;
          var activeFlag = topoTmpList[i].activeFlag;
          dynNodes = topoTmpList[i].dynNodes;
          for(var j = 0;j < dynNodes.length;j++){
            var topo = {}
            topo.topoKey = topoKey;
            // alert(topo.topoKey)
            topo.topoName = topoName;
            // alert(topo.topoName)
            topo.serviceType = serviceType;
            topo.bandwidth = bandwidth;
            topo.activeFlag = activeFlag;
            topo.startNode = dynNodes[j].startNode;
            topo.endNode = dynNodes[j].endNode;
            _this.topoList.push(topo)
          }
        }
        this.getSpanArr(_this.topoList)
      }).catch(err => {
          // 失败
          _this.InfoTip.errorTip(_this, err);
      })
      },


      /**
       * @Description  :获取所有动态拓扑信息
       * @author       ::zyh
       */
      getAllTopo: function (vue) {
        let _this = vue;
        TopologicalDynamicService.getAllTopologicalCollection().then(result => {
          // _this.topoList = Object.values(result)
          _this.topoList = []
        var dynNodes= []
        let topoTmpList = Object.values(result)
        for(var i = 0;i < topoTmpList.length;i++){
          var topoKey = topoTmpList[i].topoKey;
          var topoName = topoTmpList[i].topoName;
          var serviceType = topoTmpList[i].serviceType;
          var bandwidth = topoTmpList[i].bandwidth;
          var activeFlag = topoTmpList[i].activeFlag;
          dynNodes = topoTmpList[i].dynNodes;
          for(var j = 0;j < dynNodes.length;j++){
            var topo = {}
            topo.topoKey = topoKey;
            topo.topoName = topoName;
            topo.serviceType = serviceType;
            topo.bandwidth = bandwidth;
            topo.activeFlag = activeFlag;
            topo.startNode = dynNodes[j].startNode;
            topo.endNode = dynNodes[j].endNode;
            _this.topoList.push(topo)
          }
        }
        this.getSpanArr(_this.topoList)
      }).catch(err => {
          //失败
          _this.InfoTip.errorTip(_this, err);
      })
      },


      /**
       * @Description  :表格合并
       * @author       ::zyh
       */
      getSpanArr: function(topoList){
        this.contentSpanArr = []
        for (var i = 0; i < topoList.length; i++) {
          if (i === 0) {
            this.contentSpanArr.push(1);
            this.position = 0;
          } else {     // 判断当前元素与上一个元素是否相同
            if (topoList[i].topoName === topoList[i - 1].topoName){
              this.contentSpanArr[this.position] +=1;
              this.contentSpanArr.push(0);
            } else {
              this.contentSpanArr.push(1);
              this.position = i;
            }
          }
        }
      },



      /**
       * @Description  :表格合并
       * @author       ::zyh
       */
      cellMerge({row, column, rowIndex, columnIndex}) {
        if (columnIndex === 2 || columnIndex === 3 || columnIndex === 1 || columnIndex === 0) {
          const _row = this.contentSpanArr[rowIndex];
          const _col = _row > 0 ? 1 : 0;
          return {
            rowspan: _row,
            colspan: _col
          }
        }
      },


      /**
       * @Description  :上传初始化
       * @author       ::zyh
       */
      uploadTopologicalInit: function () {
        this.uploadTopologicalCommand.execute()
      },


      /**
       * @Description  : 导出动态拓扑初始化
       * @author       ::zyh
       */
      downloadTopologicalInit: function () {
        let _this = this;
        _this.selectList = this.handleQueryCondition();
        let loadingInstance = loading.openLoading();
        TopologicalDynamicService.downloadTopoDynamic(_this.selectList).then(result => {
          loadingInstance.close();
      }).catch(err => {
          loadingInstance.close();
        this.InfoTip.errorTip(this, err);
      });
      },


      /**
       * @Description  : 启用动态拓扑初始化
       * @author       ::zyh
       */
      enabledInit: function () {
        if (this.multipleSelection.length == 0) {
          this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.ENABLE_SELECT_CODE))
          return;
        } else if (this.multipleSelection.length > 1) {
          this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.ENABLE_SELECT_CODE))
          return;
        } else {
          this.enableString = this.multipleSelection[0]['topoKey']
          this.enableTopologicalCommand.execute();
        };
      },

      /**
       * @Description  : 禁用动态拓扑初始化
       * @author       ::zyh
       */
      disabledInit: function () {
        if (this.multipleSelection.length == 0) {
          this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.DISABLE_SELECT_CODE))
          return;
        } else if (this.multipleSelection.length > 1) {
          this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.DISABLE_SELECT_CODE))
          return;
        } else {
          this.disableString = this.multipleSelection[0]['topoKey'];
          this.disableTopologicalCommand.execute();
        };
      },


      /**
       * @Description  :删除动态拓扑初始化
       * @author       ::zyh
       */
      deleteTopologicalInit: 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++) {
            if (this.multipleSelection[i]['activeFlag'] == 1) {
              this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.DELETE_STATUS_CODE))
            }else if(i>0 && this.multipleSelection[i]['topoKey']!=this.multipleSelection[i-1]['topoKey']){
              this.deleteList.push(this.multipleSelection[i]['topoKey']);
              this.deleteTopologicalCommand.execute();
            }
          }
          if (this.multipleSelection[0]['activeFlag'] == 1){
            this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.DELETE_STATUS_CODE))
          }else{
            this.deleteList.push(this.multipleSelection[0]['topoKey']);
            this.deleteTopologicalCommand.execute();
          }

        }
      },


      /**
       * @Description  :条件查询动态拓扑初始化
       * @author       ::zyh
       */
      queryTopoByCondition: function () {
        var lan = localStorage.getItem(LANGUAGE_LOCALSTORAGE)
        let _this = this;
        _this.selectList = this.handleQueryCondition();
        let loadingInstance = _this.Loading.openLoading();
        TopologicalDynamicService.conditionQueryTopo(_this.selectList).then(result => {
          // _this.topoList = Object.values(result);
          _this.topoList = []
        var dynNodes= []
        let topoTmpList = Object.values(result)
        for(var i=0;i<topoTmpList.length;i++){
          var topoKey = topoTmpList[i].topoKey;
          var topoName = topoTmpList[i].topoName;
          var serviceType = topoTmpList[i].serviceType;
          var bandwidth = topoTmpList[i].bandwidth;
          var activeFlag = topoTmpList[i].activeFlag;
          dynNodes = topoTmpList[i].dynNodes;
          // alert(dynNodes.length);
          for(var j=0;j<dynNodes.length;j++){
            var topo = {}
            topo.topoKey = topoKey;
            topo.topoName = topoName;
            topo.serviceType = serviceType;
            topo.bandwidth = bandwidth;
            topo.activeFlag = activeFlag;
            topo.startNode = dynNodes[j].startNode;
            // alert(topo.startNode);
            topo.endNode = dynNodes[j].endNode;
            _this.topoList.push(topo)
          }
        }
        this.getSpanArr(_this.topoList)
        _this.Loading.closeLoading(loadingInstance);
        _this.InfoTip.successTip(_this, HelperUtil.getStatusCodeObjectByCode(_this.successCode.QUERY_CODE));
      }).catch(err => {
          _this.Loading.closeLoading(loadingInstance);
        _this.InfoTip.errorTip(_this, err);
      })
      },

      handleQueryCondition: function () {
        let selectList = new Array();
        if (this.queryTopologicalName != '' && this.queryTopologicalName != null) {
          selectList.push({
            quaryAttribute: 'topoName',
            compareSymbol: "like",
            compareValue: this.queryTopologicalName,
          })
        }
        if (this.querySelectService != '' && this.querySelectService != null) {
          selectList.push({
            quaryAttribute: 'serviceType',
            compareSymbol: "like",
            compareValue: this.querySelectService,
          })
        }
        if (this.queryStatus != '' && this.queryStatus!= null) {
          selectList.push({
            quaryAttribute: 'activeFlag',
            compareSymbol: "==",
            compareValue: this.queryStatus,
          })
        }
        return selectList;
      },

      /**
       * @Description  :业务类型过滤
       * @author       ::zyh
       */
      formatServiceType: function (row, column) {
        for (var j = 0; j < this.QueryServiceType.length; j++) {
          if (row.serviceType == this.QueryServiceType[j]['serviceTypeKey']) {
            return this.QueryServiceType[j]['serviceTypeName']
            break;
          }
        }
        return row.serviceType;
      },

      /**
       * @Description  :拓扑状态过滤
       * @author       ::zyh
       */
      formatStatus: function (row, column) {
        let result = row.activeFlag;
        if (row.activeFlag === 0) {
          result = this.$t('TopologicalDynamicConfiguration.disabled')
        }
        if (row.activeFlag === 1) {
          result = this.$t('TopologicalDynamicConfiguration.enabled')
        }
        return result
      },

    },
  }
</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>