<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="importLocationCommand.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="createLocationInit"
                     v-if="createAndCopyCommand.visible">{{$t('common.createBtn')}}
          </el-button>
          <el-button size='mini' icon="el-icon-document" type="primary" @click="copyLocationInit"
                     v-if="createAndCopyCommand.visible">{{$t('common.copyBtn')}}
          </el-button>
          <el-button size='mini' icon="el-icon-edit" type="primary" @click="updateLocationInit"
                     v-if="updateLocationCommand.visible">{{$t('common.updateBtn')}}
          </el-button>
          <el-button size='mini' icon="el-icon-delete" type="primary" @click="deleteLocationInit"
                     v-if="importLocationCommand.visible">
            {{$t('common.deleteBtn')}}
          </el-button>
        </div>
        <!-- 条件查询工具栏 -->
        <div class="header-search">
          <div class="search-input-box">
            <label>{{$t('LocationConfigurationManagement.queryLocationName')}}</label>
            <el-input size='mini' :placeholder="$t('common.placeholder')" v-model="querySelectName" clearable></el-input>
          </div>
          <div class="search-input-box">
            <label>{{$t('LocationConfigurationManagement.dialogLine')}}</label>
            <el-input size='mini' :placeholder="$t('common.placeholder')" v-model="querySelectLine" clearable></el-input>
          </div>
          <div class="search-input-box">
            <label>{{$t('LocationConfigurationManagement.dialogSite')}}</label>
            <el-input size='mini' :placeholder="$t('common.placeholder')" v-model="querySelectSite" clearable></el-input>
          </div>
          <div class="search-input-box">
            <el-button size='mini' icon="el-icon-search" type="primary" @click="queryLocationByCondition"
                       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="locationList"
          highlight-current-row
          @current-change="handleCurrentChange"
          @selection-change="handleSelectionChange">

          <el-table-column
            type="selection"
            width="28">
          </el-table-column>

          <el-table-column
            prop="locationKey"
            label="主键"
            v-if="false">
          </el-table-column>
          <el-table-column
            text-align="left"
            prop="locationId"
            width="220"
            :label="$t('LocationConfigurationManagement.locationId')"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="locationName"
            :label="$t('LocationConfigurationManagement.locationName')"
            width="180"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="line"
            :label="$t('LocationConfigurationManagement.line')"
            width="180"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="site"
            :label="$t('LocationConfigurationManagement.site')"
            width="180"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="km"
            :label="$t('LocationConfigurationManagement.km')"
            width="110"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="longitude"
            :label="$t('LocationConfigurationManagement.longitude')"
            width="110"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="latitude"
            :label="$t('LocationConfigurationManagement.latitude')"
            width="110"
            :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="handleSelectCabinet(scope.$index, scope.row)">{{$t('common.cabinet')}}
                </el-button>
                <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 LocationCommands from "@/commands/LocationCommands"
  import LocationService from '@/domain/services/LocationService'
  import HelperUtil from '@/utils/HelperUtil'
  import loading from "../../../utils/Loading";

  export default {
    name: "LocationConfigurationManagement",
    data: function () {   //存放数据
      return {

        commandContext: {},
        deleteList:[],
        fullscreenLoading: false,

        //Btn按钮text域
        createLocationBtn: "创建",
        updateLocationBtn: "修改",
        copyLocationBtn: "复制",
        deleteLocationBtn: "删除",
        importToExcelBtn: "导入",
        exportToExcelBtn: "导出",
        queryLocationBtn: "查询",

        //条件查询
        queryLocationName: "机房名称：",
        queryLocationLine: "所属线路：",
        queryLocationSite: "所属站点：",
        querySelectName: "", //条件查询机房名
        querySelectLine: "",//条件查询线路
        querySelectSite: "",//条件查询站点
        //selectList:this.handleQueryCondition(),

        //创建修改复制窗口是否打开
        dialog_locationCreate: false,
        dialog_locationUpdate: false,
        dialog_locationCopy: false,
        dialog_importFile: false,
        formLabelWidth: '120px',

        createAndCopyTitle: '',

        //双向绑定展示数据
        locationList: [],
        //保存当前行数据
        currentRow: null,
        //保存多选行数据
        multipleSelection: [],
        createAndCopyInitList: {},
        updateInitList:{},

        //查询条件
        selectList: [],

      }
    },

    mounted: function () {
      this.getAllLocationInit()
    },

    components: {
      CommandExecuteContext,
    },

    watch: {
      commandContext(newVal, oldVal) {
        if (JSON.stringify(newVal) === '{}') {
//          if(this.isQueryClean()){
          this.querySelectName = ''
          this.querySelectSite = ''
          this.querySelectLine = ''
          this.getAllLocation(this);
//          }else{
//
//            this.queryLocationByCondition();
//          }
          this.$refs.singleTable.clearSelection();

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

      //command命令
      createAndCopyCommand() {
        return LocationCommands.createAndCopyLocationCommand(this.createAndCopyTitle, this.createAndCopyInitList, this.commandContext)
      },
      deleteLocationCommand() {
        return LocationCommands.deleteLocationCommand(this.deleteList, this.commandContext)
      },
      updateLocationCommand() {
        return LocationCommands.updateLocationCommand(this.updateInitList, this.commandContext)
      },
      importLocationCommand() {
        return LocationCommands.importLocationCommand(this.commandContext)
      },

    },
    methods: {
      isQueryClean: function () {
        if (this.querySelectName == '' && this.querySelectSite == '' && this.querySelectLine == '') {
          return true;
        } else {
          return false;
        }
      },
      /**
       * @Description  ：单选一行，将所选行进行保存
       * @date         : 2018/12/8 0:44
       */
      handleCurrentChange(val) {
        this.currentRow = val;
      },

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

      /**
       * @Description  ：单选一行，跳转机架配置界面，初始化加载该机房数据（已调通）
       * @date         : 2018/12/21 15:01
       */
      handleSelectCabinet(index, row) {
        let flag = false;
        for (let item of this.openTab) {
          if (item.name === '机架配置') {
            this.$store.commit('delete_keepAliveRouter', 'CabinetConfigurationManagement')
            this.$store.commit('delete_tabs', '/TheLayout/CabinetConfigurationManagement')
            this.$store.commit('add_tabs', {route: '/TheLayout/CabinetConfigurationManagement', name: '机架配置',title:'TheLayoutHeader.cabinetConfigurationManagement'})
            this.$store.commit('set_active_index', '/TheLayout/CabinetConfigurationManagement')
            this.$store.commit('add_keepAliveRouter', 'CabinetConfigurationManagement');
            this.$router.push({
              path: '/TheLayout/CabinetConfigurationManagement',
              query: {locationKey: row.locationKey}
            });
            flag = true;
            break;
          }
        }
        if (!flag) {
          this.$store.commit('add_tabs', {route: '/TheLayout/CabinetConfigurationManagement', name: '机架配置',title:'TheLayoutHeader.cabinetConfigurationManagement'})
          this.$store.commit('add_keepAliveRouter', 'CabinetConfigurationManagement');
          this.$store.commit('set_active_index', '/TheLayout/CabinetConfigurationManagement')
          this.$router.push({path: '/TheLayout/CabinetConfigurationManagement', query: {locationKey: row.locationKey}});
        }
      },

      /**
       * @Description  ：单选一行，跳转设备配置界面，初始化加载该机房数据（已调通）
       * @date         : 2018/12/21 15:03
       */
      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: {locationKey: row.locationKey}
            });
            flag = true;
            break;
          }
        }
        if (!flag) {
          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: {locationKey: row.locationKey}});
        }
      },

      getAllLocationInit: function () {
        let _this = this;
        LocationService.getAllLocationCollection().then(result => {
          _this.locationList = Object.values(result);
         console.log()
        }).catch(err => {
          //失败
          _this.$message.error('Error ' + result.body.faultCode + ':' + result.body.faultCause);
        });
      },
      /**
       * @Description  ：增删改后调用，重新加载table   gai
       * @date         : 2018/12/8 17:21
       */
      getAllLocation: function (vue) {
        let _this = vue;
        LocationService.getAllLocationCollection().then(result => {

          _this.locationList = Object.values(result);
        }).catch(err => {
          //失败
          _this.$message.error('Error ' + result.body.faultCode + ':' + result.body.faultCause);
        });
      },

      /**
       * @Description  ：创建机房初始化
       * @date         : 2018/12/8 0:45
       */
      createLocationInit: function () {
        this.createAndCopyTitle = this.$t('LocationConfigurationManagement.dialogLocationCreate');
        this.createAndCopyInitList = {
          "locationKey": "",
          "locationID": "",
          "locationName": "",
          "line": "",
          "site": "",
          "km": "",
          "longitude": "",
          "latitude": "",
          "delFlag": "",
          "modifyTime": "",
        };
        this.createAndCopyCommand.execute();
      },

      /**
       * @Description  ：修改机房信息初始化
       * @date         : 2018/12/14 21:37
       */
      updateLocationInit: 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_SELECT_CODE))
          return;
        } else {
          this.updateInitList = {
            "locationKey": this.multipleSelection[0].locationKey,
            "locationID": this.multipleSelection[0].locationId,
            "locationName": this.multipleSelection[0].locationName,
            "line": this.multipleSelection[0].line,
            "site": this.multipleSelection[0].site,
            "km": this.multipleSelection[0].km,
            "longitude": this.multipleSelection[0].longitude,
            "latitude": this.multipleSelection[0].latitude,
            "delFlag": this.multipleSelection[0].delFlag,
            "modifyTime": this.multipleSelection[0].modifyTime,
          };
          this.updateLocationCommand.execute();
        }
      },
      /**
       * @Description  ：复制机房信息初始化
       * @date         : 2018/12/14 21:40
       */
      copyLocationInit: 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_SELECT_CODE))
          return;
        } else {
          this.createAndCopyTitle = this.$t('LocationConfigurationManagement.dialogLocationCopy');
          this.createAndCopyInitList = {
            //*******************************************************************************
            //特别注意！特别注意！特别注意！后台的locationId的d是小写！！而前端定义的变量的ID是大写！！
            //*********************************************
            //*********************************************
            "locationID": this.multipleSelection[0].locationId,
            //************************************************
            //***************************************************
            //代码你可以删，但这段注释你别删。
            "locationKey": this.multipleSelection[0].locationKey,
            "locationName": this.multipleSelection[0].locationName,
            "line": this.multipleSelection[0].line,
            "site": this.multipleSelection[0].site,
            "km": this.multipleSelection[0].km,
            "longitude": this.multipleSelection[0].longitude,
            "latitude": this.multipleSelection[0].latitude,
            "delFlag": "",
            "modifyTime": "",
          };
          this.createAndCopyCommand.execute();
        }
      },

      /**
       * @Description  ：删除机房信息初始化（支持批量）
       * @date         : 2018/12/14 21:43
       */
      deleteLocationInit: function () {
        if (this.multipleSelection.length == 0) {
          this.$message({
            type: 'warning',
            message: '请至少选择一条信息进行删除！ ',
            duration: 10000,
            showClose: true,
          })
          return;
        } else {
          this.deleteList = []
          for (var i = 0; i < this.multipleSelection.length; i++) {
            // this.deleteList.push(this.multipleSelection[i]['locationKey']);
            var obj = {'locationKey': this.multipleSelection[i]['locationKey']}
            this.deleteList.push(obj)
          }
          console.log(this.deleteList)
          this.deleteLocationCommand.execute();
        }
      },

      queryLocationByCondition: function () {

        let _this = this;
        _this.selectList = this.handleQueryCondition();
        console.log(this.selectList)
        let loadingInstance = _this.Loading.openLoading();
        LocationService.conditionQueryLocation(_this.selectList).then(result => {
          _this.locationList = Object.values(result);
          _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);
        })
      },

      importToExcelInit: function () {
        this.importLocationCommand.execute()
      },

      exportToExcelInit: function () {
        let _this = this;
        _this.selectList = this.handleQueryCondition();
        let loadingInstance = loading.openLoading();
        LocationService.downloadLocation(_this.selectList).then(result => {
          loadingInstance.close();
        }).catch(err => {
          loadingInstance.close();
          this.InfoTip.errorTip(this, err);
        });
      },

      handleQueryCondition: function () {
        let selectList = new Array();
        if (this.querySelectName != '') {
          selectList.push({
            quaryAttribute: 'locationName',
            compareSymbol: "like",
            compareValue: this.querySelectName,
          })
        }
        if (this.querySelectLine != '') {
          selectList.push({
            quaryAttribute: 'line',
            compareSymbol: "like",
            compareValue: this.querySelectLine,
          })
        }
        if (this.querySelectSite != '') {
          selectList.push({
            quaryAttribute: 'site',
            compareSymbol: "like",
            compareValue: this.querySelectSite,
          })
        }
        return selectList;
      },
    },

  }
</script>

<style scoped>
</style>
