<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-circle-plus-outline" type="primary" @click="createEveSubnetInit"
                     v-if="createAndCopyEthernetSubnetCommand.visible">
            {{$t('common.createBtn')}}
          </el-button>
          <el-button size='mini' icon="el-icon-document" type="primary" @click="copyEveSubnetInit"
                     v-if="createAndCopyEthernetSubnetCommand.visible">
            {{$t('common.copyBtn')}}
          </el-button>
          <el-button size='mini' icon="el-icon-edit" type="primary" @click="updateEveSubnetInit"
                     v-if="updateEthernetSubnetCommand.visible">
            {{$t('common.updateBtn')}}
          </el-button>
          <el-button size='mini' icon="el-icon-delete" type="primary" @click="deleteEveSubnetInit"
                     v-if="deleteEthernetSubnetCommand.visible">
            {{$t('common.deleteBtn')}}
          </el-button>
        </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="EveSubnetList"
          highlight-current-row
          @current-change="handleCurrentChange"
          @selection-change="handleSelectionChange">

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

          <el-table-column
            prop="serviceSubnetID"
            label="主键"
            v-if="false">
          </el-table-column>
          <el-table-column
            text-align="left"
            prop="serviceSubnetName"
            :label="$t('EthernetSubnetDialog.serviceSubnetName')"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="serviceSubnetTopo"
            :label="$t('EthernetSubnetDialog.serviceSubnetTopologyType')"
            :formatter="formatEveSubnetTopoType"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="serviceTypeID"
            :label="$t('EthernetSubnetDialog.serviceType')"
            :formatter="formatServerType"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            :label="$t('EthernetSubnetDialog.view')">
            <template slot-scope="scope">
              <el-row type="flex">
                <el-button
                  style="margin-top:-3.8px"
                  size="mini"
                  type="text"
                  @click="handleOperateDevice(scope.$index, scope.row,scope.row.subnetDevices)">
                  {{$t('EthernetSubnetDialog.device')}}
                </el-button>
              </el-row>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>
    <CommandExecuteContext v-bind:commands="commandContext"></CommandExecuteContext>
    <!-- 附属设备列表对话框 -->
    <el-dialog v-dialogDrag width='600px' :title="$t('EthernetSubnetDialog.affiliateDevices')"
               :visible.sync="dialog_foreignDevice">

      <el-main style="padding: 0">
        <el-table
          tooltip-effect="dark"
          stripe
          header-row-class-name="table-header"
          cell-class-name="table-cell"
          ref="singleTable"
          height="400px"
          :data="currentDeviceList"
          highlight-current-row
          @current-change=""
          @selection-change="">

          <el-table-column
            type="selection"
            v-if="false"
            width="28">
          <!--v-if="false">-->
          </el-table-column>

          <!--<el-table-column-->
            <!--prop="deviceKey"-->
            <!--label="主键"-->
            <!--v-if="false">-->
          <!--</el-table-column>-->
          <el-table-column
            text-align="left"
            prop="deviceKey"
            :label="$t('EthernetSubnetDialog.networkElementName')"
            :formatter="formatEndDeviceKey"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="port"
            :label="$t('EthernetSubnetDialog.ports')"
            :show-overflow-tooltip="true">
          </el-table-column>
        </el-table>
      </el-main>
    </el-dialog>

  </div>
</template>

<script>
  import CommandExecuteContext from '../../commands/CommandExecuteContext.vue'
  import EthernetSubnetCommands from '../../commands/EthernetSubnetCommands';
  import ServiceSubnetService from '@/domain/services/Business/ServiceSubnetService.js'
  import ServiceTypeService from '@/domain/services/Business/ServiceTypeService.js'
  import DeviceService from '@/domain/services/DeviceService'
  import HelperUtil from "@/utils/HelperUtil.js";
  export default {
    name: 'EveSubnetConfigurationManagementFather',

    components: {
      CommandExecuteContext
    },

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

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

        //删除相关
        deleteList: [],

        //为修改传参数
        updateInitList: [],
        /** *********************************下面是以前的data ***********************************/
        fullscreenLoading: false,

        //Btn按钮text域
        createEveSubnetBtn: "创建",
        updateEveSubnetBtn: "修改",
        copyEveSubnetBtn: "复制",
        deleteEveSubnetBtn: "删除",

        dialog_foreignDevice:false,

        formLabelWidth: '150px',

        deviceKey0: '',

        deviceList: [],// [{"deviceKey": '1',"port": '1,2'},{"deviceKey": '2',"port": '1'}],//"port": ''}],


        lineType: '',
        currentDeviceList: [],
        //服务器类型下拉列表
        EveSubnetTopoList: [
          {
            value: '0',
            label: this.$t("EthernetSubnetDialog.singlePoint")
          }, {
            value: '1',
            label: this.$t("EthernetSubnetDialog.bus")
          }, {
            value: '2',
            label: this.$t("EthernetSubnetDialog.ring")
          }, {
            value: '3',
            label: this.$t("EthernetSubnetDialog.mesh")
          }, {
            value: '4',
            label: this.$t("EthernetSubnetDialog.hybrid")
          }],
        SelectEveSubnetTopo: '',

        //业务类型下拉列表
        serviceTypeList: [
//          {
//            serviceTypeID: '0',
//            serviceTypeName: 'serverType1'
//          },
//          {
//            serviceTypeID: '1',
//            serviceTypeName: 'serverType2'
//          },
//          {
//            serviceTypeID: '2',
//            serviceTypeName: 'serverType3'
//          }
        ],

        //双向绑定弹出窗口input域
        form: {
          serviceSubnetID: "",
          serviceSubnetName: "",
          serviceSubnetTopo: "",
          serviceTypeID: "",

          deviceKey: '',
          port: '',


        },


        SubnetDeviceForCreate: [],

        //为了修改
        serviceSubnetIDForUpdate: '',
        serviceSubnetNameForUpdate: '',

        //双向绑定展示数据

        EveSubnetList:[],
        //保存当前行数据
        currentRow: null,
        //保存多选行数据
        multipleSelection: [],
        multipleSelectionCreate: [],
        multipleSelectionCopy: [],
        multipleSelectionUpdate: [],

        //保存附属设备表当前行数据
        currentRowDevice: null,
        //保存附属设备表多选行数据
        multipleSelectionDevice: [],

      }
    },
    //vue加载初始化函数，加载数据
    created: function () {
      console.log('业务子网管理界面初始化：')


      this.getAllEveSubnetInit()
      //额外获取所有关联机房信息
      this.getAllEvc()

      this.getAllDevice()
    },
    computed: {
      openTab() {
        return this.$store.state.openTab;
      },
      activeIndex: {
        get() {
          return this.$store.state.activeIndex;
        },
        set(val) {
          this.$store.commit('set_active_index', val);
        }
      },
      createAndCopyEthernetSubnetCommand() {
        return EthernetSubnetCommands.createAndCopyEthernetSubnetCommand(this.createAndCopyTitle, this.createAndCopyInitList, this.commandContext)
      },
      deleteEthernetSubnetCommand() {
        return EthernetSubnetCommands.deleteEthernetSubnetCommand(this.deleteList, this.commandContext)
      },
      updateEthernetSubnetCommand() {
        return EthernetSubnetCommands.updateEthernetSubnetCommand(this.updateInitList, this.commandContext)
      },
      a() {
        this.lineType = this.$t('EthernetSubnetDialog.lineType')
      }
    },
    methods: {


      //对input输入内容进行校验
      /**
       * @Description  ：业务子网名称非空校验
       * @author       :
       * @param        :
       * @return       :
       * @exception    :
       * @date         : 2019/3/13
       */
      serviceSubnetNameCheck: function () {
        const _this = this;
        if (_this.form.serviceSubnetName == '' || _this.form.serviceSubnetName == null) {
          _this.InfoTip.warningTip(_this, HelperUtil.getCheckStatusCodeObjectByCode(_this.successCode.SERVICE_SUBNET_NAME_CANNOT_BE_EMPTY))
          return false
        }
        return true
      },


      /**
       * @Description  ：单选一行，将所选行进行保存
       */
      handleCurrentChange(val) {
        this.currentRow = val;
      },

      /**
       * @Description  ：创建业务子网，表格多选框改变时，将所选行进行保存
       */
      handleSelectionChangeCreate(val) {
        this.SubnetDeviceForCreate = new Array()
        this.multipleSelectionCreate = val

        for (var i = 0; i < this.multipleSelectionCreate.length; i++) {
          this.SubnetDeviceForCreate.push({
            deviceKey: this.multipleSelectionCreate[i].deviceKey,
            port: this.multipleSelectionCreate[i].port,
          })
//          }
        }
        console.log("device", this.SubnetDeviceForCreate)
      },



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

      getAllDevice() {
        //获取设备信息
        let _this = this
        console.log("执行获取设备")
        console.log('获取全部网元信息:')
        DeviceService.getAllDeviceCollection().then(result => {
          //成功
          _this.deviceList = Object.values(result)


//          console.log(this.deviceList)
        }).catch(err => {
          //失败
          _this.InfoTip.errorTip(_this, err);
        })
      },

      /**
       * @Description  :业务类型过滤
       */
      formatServerType: function (row, column) {


        for (var j = 0; j < this.serviceTypeList.length; j++) {
          if (row.serviceTypeID == this.serviceTypeList[j]['serviceTypeID']) {
            return this.serviceTypeList[j]['serviceTypeName']
          }
        }
//
//        if (this.serviceTypeList[row.serviceTypeID] != undefined) {
//          return this.serviceTypeList[row.serviceTypeID].serviceTypeName
//        }
//        else {
//          return row.serviceTypeID
//        }
      },

      /**
       * @Description  ：子网拓扑类型过滤
       */
      formatEveSubnetTopoType: function (row, column) {
        for (var i = 0; i < this.EveSubnetTopoList.length; i++) {
          if (this.EveSubnetTopoList[i]['value'] == row.serviceSubnetTopo) {
            return this.EveSubnetTopoList[i]['label']
            break;
          }
        }
      },

      /**
       * @Description  ：查看单选行的设备列表
       */
      handleOperateDevice(index, row, subnetDevices) {
        console.log(index, row);
        console.log('查看设备列表：')
        this.currentDeviceList = subnetDevices
        //弹出设备列表对话框
        if (this.currentDeviceList.length == 0) {
          // var message = '没有附属设备！'
          this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.HAVE_NO_AFFILIATD_DEVICE))

//          this.$message({
//            type: 'waring',
//            message: '没有附属设备！ ',
//            duration: 10000,
//            showClose: true,
//          });
        } else {

          this.dialog_foreignDevice = true;
        }

      },

      formatEndDeviceKey: function (row, column) {
        console.log("过滤设备名称")
        for (var j = 0; j < this.deviceList.length; j++) {
          if (row.deviceKey === this.deviceList[j]['deviceKey']) {
            return this.deviceList[j]['deviceName']
          }
//          else{
//            return this.deviceList[j]['deviceKey']
//          }
        }
        return row.deviceKey
      },

      /**
       * @Description  ：获取业务类型
       */
      getAllEvc: function () {
        console.log('获取全部业务信息：')
        let _this = this
        ServiceTypeService.getAllServiceTypeCollection().then(result => {
          //成功
          _this.serviceTypeList = Object.values(result)
        }).catch(err => {
          //失败
          _this.InfoTip.errorTip(_this, err);
        })

      },

      /**
       * @Description  ：获取业务子网信息
       */
      getAllEveSubnetInit: function () {
        console.log('获取全部业务子网信息：')
        let _this = this
        ServiceSubnetService.getAllEveSubnetCollection().then(result => {
          //成功
          _this.EveSubnetList = Object.values(result)
        }).catch(err => {
          //失败
          _this.InfoTip.errorTip(_this, err);

        });

      },

      /**
       * @Description  ：增删改后调用，重新加载table
       */
      getAllEveSubnet: function (vue) {
        console.log('获取全部业务子网信息：')

        ServiceSubnetService.getAllEveSubnetCollection().then(result => {
          //成功
          vue.EveSubnetList = Object.values(result)
          console.log("刷新成功")

        }).catch(err => {
          //失败
          vue.InfoTip.errorTip(vue, err);
        });

      },


      /**
       * @Description  ：创建初始化
       */
      createEveSubnetInit: function () {
        var idList = new Array();
        for (var i = 0; i < this.EveSubnetList.length; i++) {
          idList[i] = parseInt(this.EveSubnetList[i]['serviceSubnetID']);
        }
        var tempid = 0
        for (var j = 0; j < idList.length; j++) {
          if (idList[j] > tempid) {
            tempid = idList[j]
          }
        }
        tempid += 1
        this.createAndCopyTitle = this.$t('EthernetSubnetDialog.serviceSubnetCreation');
        this.createAndCopyInitList = {
          'serviceSubnetID': tempid,
          'serviceSubnetName': "",
          'serviceSubnetTopo': "",
          'serviceTypeID': "",
          'deviceKey': '',
          'port': '',
          'subnetDevices': [],
        };
        console.log(this.createAndCopyInitList.serviceSubnetID)
        this.createAndCopyEthernetSubnetCommand.execute();
      },


      /**
       * @Description  ：修改业务子网信息初始化
       */
      updateEveSubnetInit: function () {
        if (this.multipleSelection.length === 0) {
          this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.PLEASE_SELECT_ONLY_ONE_RECORD_TO_MODIFY))
          return;
        } else if (this.multipleSelection.length > 1) {
          this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.PLEASE_SELECT_ONLY_ONE_RECORD_TO_MODIFY))
          return;
        } else {
          this.currentRow = this.multipleSelection[0];
          this.updateInitList = {
            'serviceSubnetID': this.currentRow.serviceSubnetID,
            'serviceSubnetName': this.currentRow.serviceSubnetName,
            'serviceSubnetTopo': this.currentRow.serviceSubnetTopo,
            'serviceTypeID': this.currentRow.serviceTypeID,
            'currentDeviceList': this.currentRow.subnetDevices,
            'serviceSubnetIDForUpdate': this.currentRow.serviceSubnetID,
            'serviceSubnetNameForUpdate': this.currentRow.serviceSubnetName,
          };
          this.updateEthernetSubnetCommand.execute();
        }
      },


      /**
       * @Description  ：复制业务子网信息初始化
       */
      copyEveSubnetInit: function () {
        this.currentDeviceList = new Array()
        if (this.multipleSelection.length == 0) {
          this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.PLEASE_SELECT_ONE_RECORD_TO_DUPLICATE))
          return;
        } else if (this.multipleSelection.length > 1) {
          this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.PLEASE_SELECT_ONLY_ONE_RECORD_TO_DUPLICATE))
          return;
        }
        else {

          var idList = new Array();
          for (var i = 0; i < this.EveSubnetList.length; i++) {
            idList[i] = parseInt(this.EveSubnetList[i]['serviceSubnetID']);
          }
          console.log('-------------------------------------------------------------------------------------------------------------------------------')
          var tempid = 0
          for (var j = 0; j < idList.length; j++) {
            console.log(idList[j])
            if (idList[j] > tempid) {
              tempid = idList[j]
            }
          }

          this.createAndCopyTitle = this.$t('EthernetSubnetDialog.duplicateServiceSubnet');
          this.currentRow = this.multipleSelection[0];
          this.createAndCopyInitList = {
            'serviceSubnetID': tempid + 1,
            'serviceSubnetName': this.currentRow.serviceSubnetName,
            'serviceSubnetTopo': this.currentRow.serviceSubnetTopo,
            'serviceTypeID': this.currentRow.serviceTypeID,
            'deviceKey': '',
            'port': '',
            'currentDeviceList': this.currentRow.subnetDevices,
            'serviceSubnetIDForCopy': this.currentRow.serviceSubnetID,
//            'serviceSubnetNameForCopy': this.currentRow.serviceSubnetName,


          };


          console.log(this.currentRow.subnetDevices)
          this.createAndCopyEthernetSubnetCommand.execute();
        }
      },


      /**
       * @Description  ：删除业务子网信息初始化（支持批量）
       */
      deleteEveSubnetInit: function () {

        if (this.multipleSelection.length == 0) {
          this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.PLEASE_SELECT_ONE_RECORD_TO_DELETE))
          return;
        } else if (this.multipleSelection.length > 1) {
          this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.PLEASE_SELECT_ONLY_ONE_RECORD_TO_DELETE))
          return;
        }

        this.deleteList = []
        for (var i = 0; i < this.multipleSelection.length; i++) {
          this.deleteList.push(this.multipleSelection[i]['serviceSubnetID']);
        }
        this.deleteEthernetSubnetCommand.execute()

      },


    },
    watch: {
      commandContext(newVal, oldVal) {
        if (JSON.stringify(newVal) === '{}') {
          this.getAllEveSubnet(this)
          this.$refs.singleTable.clearSelection();
        }
        deep: true
      },
    },
  }
</script>

<style scoped>
</style>
