<template>
  <!-- 业务子网修改对话框 -->
  <el-dialog v-dialogDrag
             v-if="UpdateSubnetVisible"
             style="font-size: 10px;" width='800px'
             :title="$t('EthernetSubnetDialog.modificationOfServiceSubnet')"
             :visible.sync="UpdateSubnetVisible"
             @opened="checked"
             @close="close">

    <el-form :model="form" inline="true" ref="form">
      <el-row>
        <el-form-item :label="'*'+$t('EthernetSubnetDialog.serviceSubnetId')+':'" :label-width="formLabelWidth" style="margin-bottom: -10px;">
          <el-input size='mini' :placeholder="$t('common.placeholder')" v-model="form.serviceSubnetID "
                    style="width:200px" disabled="true"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item :label="'*'+$t('EthernetSubnetDialog.serviceSubnetName')+':'" :label-width="formLabelWidth" style="margin-bottom: -10px;">
          <el-input size='mini' :placeholder="$t('common.placeholder')" v-model="form.serviceSubnetName"
                    v-on:blur="serviceSubnetNameCheck"
                    style="width:200px"
                    autocomplete="off"></el-input>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item :label="'*'+$t('EthernetSubnetDialog.serviceSubnetTopologyType')+':'" :label-width="formLabelWidth" style="margin-bottom: -10px;">
          <el-select disabled="true" v-model="form.serviceSubnetTopo" size="mini"
                     :placeholder="$t('common.selectOption')"
                     clearable="true"
                     style="width: 200px">
            <el-option
              v-for="item in EveSubnetTopoList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item :label="'*'+$t('EthernetSubnetDialog.serviceType')+':'" :label-width="formLabelWidth" style="margin-bottom: -10px;">
          <el-select disabled="true" size='mini' v-model="form.serviceTypeID" :placeholder="$t('common.selectOption')"
                     clearable="true"
                     style="width:200px">
            <el-option
              v-for="item in SeverTypeList"
              :key="item.serviceTypeID"
              :label="item.serviceTypeName"
              :value="item.serviceTypeID">
            </el-option>
          </el-select>
        </el-form-item>
      </el-row>

      <el-form-item label="" style="margin-bottom: -10px;"></el-form-item>
      <el-form-item :label="$t('EthernetSubnetDialog.addAffiliateDevices')" style="margin-bottom: -10px;"></el-form-item>
      <el-form-item label="" style="margin-bottom: -10px;"></el-form-item>


      <el-table
        ref="table"
        tooltip-effect="dark"
        header-row-class-name="table-header"
        cell-class-name="table-cell"
        fit="true"
        height="250"
        :data="deviceList"
        align="center"
        highlight-current-row
        @current-change="handleCurrentChange"
        @selection-change="handleSelectionChangeCopy">

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

        <el-table-column
          prop="deviceKey"
          :formatter="formatEndDeviceKey"
          :label="$t('EthernetSubnetDialog.networkElementName')"
          width="250px"
          height="30px"
        >
        </el-table-column>


        <el-table-column
          :label="$t('EthernetSubnetDialog.ports')"
          height="30px"
          visEdit="true"
        >
          <template slot-scope="scope">
            <el-input size='mini' :placeholder="$t('common.placeholder')" v-model="scope.row.port"
                      style="width:200px;height: 35px;margin-top:5px"
                      v-on:blur="portCheck(scope.row.deviceKey,scope.row.port,2)"
                      v-on:change="selectDevice(scope.row.deviceKey,scope.row.port)"
                      autocomplete="off"></el-input>
            <small style="font-size: 9px">
              {{$t('EthernetSubnetDialog.inputNumber')}}
            </small>
          </template>

        </el-table-column>

      </el-table>


    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button size='mini' type="primary" @click="updateEveSubnet" v-loading.fullscreen.lock="fullscreenLoading">
        {{$t('common.updateBtn')}}
      </el-button>
      <el-button size='mini' @click="close">{{$t("common.cancel")}}</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import ServiceSubnetService from '@/domain/services/Business/ServiceSubnetService.js'
  import legitimacyCheck from "../../../utils/legitimacyCheck";
  import ServiceTypeService from '@/domain/services/Business/ServiceTypeService.js'
  import DeviceService from '@/domain/services/DeviceService.js'
  import HelperUtil from "@/utils/HelperUtil.js";
  import DeviceManager from "../../../domain/models/DeviceManager";

  export default {
    name: 'UpdateEthernetSubnet',
    props: ['command'],


    data: function () {
      return {
        selectFlag:false,

        UpdateSubnetVisible: false,
        initList: this.command.target,

        formLabelWidth: '160px',
        //双向绑定弹出窗口input域
        form: {
          serviceSubnetID: "",
          serviceSubnetName: "",
          serviceSubnetTopo: "",
          serviceTypeID: "",
          deviceKey: '',
          port: '',
          subnetDevice:''
        },
        isPortTrue: true,
        SubnetDeviceForCopy:[],
        multipleSelectionCopy: [],
        currentDeviceList: [],
        deviceList: [],//[],//
        deviceListInit: [],
        deviceArray:[],
//         [{"deviceKey": '1',"port": '1,2'},{"deviceKey": '2',"port": '1'}],//"port": ''}],
//        //服务器类型下拉列表
        EveSubnetTopoList: [
          {
            value: '0',
            label: '单设备型'
          }, {
            value: '1',
            label: '线型'
          }, {
            value: '2',
            label: '环型'
          }, {
            value: '3',
            label: '网孔型'
          }, {
            value: '4',
            label: '混合结构型'
          }],
        //业务类型下拉列表
        SeverTypeList: [
//          {
//            serviceTypeID: '0',
//            serviceTypeName: 'serverType1'
//          },
//          {
//            serviceTypeID: '1',
//            serviceTypeName: 'serverType2'
//          },
//          {
//            serviceTypeID: '2',
//            serviceTypeName: 'serverType3'
//          }
        ],
        //为了修改
        serviceSubnetIDForUpdate: '',
        serviceSubnetNameForUpdate: '',
      }
    },
    methods: {
      close() {
        this.command.done();
      },

      /**
       * @Description  ：复制业务子网，表格多选框改变时，将所选行进行保存
       */
      handleSelectionChangeCopy(val) {
        if(this.selectFlag&&val.length===0){
          val = this.multipleSelectionCopy
          this.selectFlag = false
        }

        this.SubnetDeviceForCopy = new Array()
        this.multipleSelectionCopy = val

        for (var i = 0; i < this.multipleSelectionCopy.length; i++) {
          this.SubnetDeviceForCopy.push({
            deviceKey: this.multipleSelectionCopy[i].deviceKey,
            port: this.multipleSelectionCopy[i].port,
          })
        }
        for (var i = 0; i < this.deviceList.length; i++) {
          let foundFlag = false;
          for (var j = 0; j < this.multipleSelectionCopy.length; j++) {
            if (this.deviceList[i].deviceKey === this.multipleSelectionCopy[j].deviceKey) {
              this.multipleSelectionCopy[j].port = this.deviceList[i].port
              foundFlag = true;
              break;
            }
          }
          if (!foundFlag) {

            this.deviceList[i].port = ''

          }
        }

      },

      checked: function () {


        console.log("执行默认选中")
        //初始化选中状态
        //首先el-table添加ref="tableCopy"引用标识
        for (var i = 0; i < this.currentDeviceList.length; i++) {
          for (var j = 0; j < this.deviceList.length; j++) {
            if (this.currentDeviceList[i].deviceKey == this.deviceList[j].deviceKey) {
              this.$refs.table.toggleRowSelection(this.deviceList[j], true);
              console.log("选中")
            }
          }
        }
        let tempDeviceList = this.deviceList

        //初始化时修改当前附属设备的port的值"复制，删除使用"
        for (var i = 0; i < this.currentDeviceList.length; i++) {
          for (var j = 0; j < this.deviceList.length; j++) {
            if (this.deviceList[j].deviceKey == this.currentDeviceList[i].deviceKey) {
              tempDeviceList[j].port = this.currentDeviceList[i].port
            }
          }
        }

        this.deviceList = tempDeviceList
        this.selectFlag = true

        console.log("执行默认选中完成")

//        console.log("输出输出")
//        console.log(tempDeviceList)
//        console.log(this.deviceList)

      },

      selectDevice: function (tempDeviceKey, tempPort) {
        for (var j = 0; j < this.deviceList.length; j++) {
          if (tempDeviceKey == this.deviceList[j].deviceKey) {
            if (tempPort != null && tempPort != '') {
              this.$refs.table.toggleRowSelection(this.deviceList[j], true);
              console.log("选中")
            }

          }
        }
        let tempDeviceList = this.deviceList


//        for (var i = 0; i < this.currentDeviceList.length; i++) {
//          for (var j = 0; j < this.deviceList.length; j++) {
//            if (this.deviceList[j].deviceKey == this.currentDeviceList[i].deviceKey) {
//              tempDeviceList[j].port = this.currentDeviceList[i].port
//            }
//          }
//        }

        this.deviceList = tempDeviceList
        this.selectFlag = true
//        alert("8888888888888888")
      },

      // 验证附属设备portID合法性
      portCheck: function (tempDeviceKey, tempPort, flag) {
        let _this = this
        this.isPortTrue = true
        if (flag == 2) {
          this.SubnetDeviceForCopy = new Array()
          for (var i = 0; i < _this.multipleSelectionCopy.length; i++) {
            if (tempDeviceKey == this.multipleSelectionCopy[i].deviceKey) {
              console.log('device 不同')
              this.multipleSelectionCopy[i].port = tempPort
            }
          }
          for (var i = 0; i < this.multipleSelectionCopy.length; i++) {
            this.SubnetDeviceForCopy.push({
              deviceKey: this.multipleSelectionCopy[i].deviceKey,
              port: this.multipleSelectionCopy[i].port,
            })
          }

          console.log("device", this.SubnetDeviceForCopy)

        }
        //注释掉
//        if (tempPort == '' || tempPort == null) {
//          this.isPortTrue = true
////          return
//          for(var m=0;m<this.multipleSelectionCopy.length;m++){
//            if(tempDeviceKey===this.multipleSelectionCopy[m]["deviceKey"]){
//              if(tempPort===''||tempPort===null){
//                this.isPortTrue = false
//                console.log(this.isPortTrue)
//              }
//
//            }
//          }
//        }
//
//        else {
//
//          //判断“，”合法性，防止多个‘，’连接
//          var tempPortList0 = new Array()
//          tempPortList0 = tempPort.split('')
//          for (var i = 0; i < tempPortList0.length; i++) {
//            if (tempPortList0[i] == ',' && tempPortList0[i + 1] == ',') {
//              this.isPortTrue = false
//              let message = '请输入有效的portID'
//              this.InfoTip.warningTip(this, {message: message})
//
//              return false
//            }
//          }
//
//          var tempPortList = new Array()
//          tempPortList = tempPort.split(',')
//          var numReg = /^-?[0-9]\d*$/
//          var numRe = new RegExp(numReg)
//          for (var j = 0; j < tempPortList.length; j++) {
//            if (!numRe.test(tempPortList[j])) {
//              this.isPortTrue = false
//            }
//            for (var k = 0; k < tempPortList.length; k++) {
//              if (tempPortList[j] == tempPortList[k]) {
//                if (j != k) {
//                  this.isPortTrue = false
//                  let message = '请勿输入重复的portID'
//                  this.InfoTip.warningTip(this, {message: message})
//                  return false
//                }
//              }
//            }
//
//          }
//          if (tempPortList0[tempPortList0.length - 1] == ',') {
//            this.isPortTrue = false
//          }
//
//
//        }
//        if (this.isPortTrue == false) {
//          let message = '请输入有效的portID'
//          this.InfoTip.warningTip(this, {message: message})
//          return false
//        }
//        else {
//          return true
//        }
        //注释结束，不能删除

        for (var m = 0; m < this.multipleSelectionCopy.length; m++) {
          if (tempDeviceKey === this.multipleSelectionCopy[m]["deviceKey"]) {
            if (tempPort === '' || tempPort === null) {
              this.isPortTrue = false
              console.log(this.isPortTrue)
            }

            //判断“，”合法性，防止多个‘，’连接
            var tempPortList0 = new Array()
            tempPortList0 = tempPort.split('')
            for (var i = 0; i < tempPortList0.length; i++) {
              if (tempPortList0[i] == ',' && tempPortList0[i + 1] == ',') {
                this.isPortTrue = false
                // let message = '请输入有效的portID'
                this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.PLEASE_ENTER_A_VALID_PORT_ID))

                return false
              }
            }

            var tempPortList = new Array()
            tempPortList = tempPort.split(',')
            var numReg = /^-?[0-9]\d*$/
            var numRe = new RegExp(numReg)
            for (var j = 0; j < tempPortList.length; j++) {
              if (!numRe.test(tempPortList[j])) {
                this.isPortTrue = false
              }
              for (var k = 0; k < tempPortList.length; k++) {
                if (tempPortList[j] == tempPortList[k]) {
                  if (j != k) {
                    this.isPortTrue = false
                    // let message = '请勿输入重复的portID'
                    this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.PLEASE_DO_NOT_ENTER_A_DUPLICATE_PORT_ID))
                    return false
                  }
                }
              }

            }
            if (tempPortList0[tempPortList0.length - 1] == ',') {
              this.isPortTrue = false
            }


          }
          else {
            this.isPortTrue = true
          }


        }

        if (this.isPortTrue == false) {
          // let message = '请输入有效的portID'
          this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.PLEASE_ENTER_A_VALID_PORT_ID))
          return false
        }
        else {
//          for (var j = 0; j < this.deviceList.length; j++) {
//            if (tempDeviceKey == this.deviceList[j].deviceKey) {
//              if (tempPort != null && tempPort != '') {
//                this.$refs.table.toggleRowSelection(this.deviceList[j], true);
//                console.log("选中")
//              }
//
//            }
//          }
//          return true
        }


      },


      /**
       * @Description  ：获取业务类型
       */
      getAllEvc: function () {
        console.log('获取全部业务信息：')
        let _this = this
        ServiceTypeService.getAllServiceTypeCollection().then(result => {
          //成功
          _this.SeverTypeList = Object.values(result)


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

      },


      async getAllDevice() {
        console.log("执行获取设备")
        console.log('获取全部网元信息:')
        let _this = this
        let getAll = DeviceService.getAllDeviceCollection().then(result => {
          //成功
          _this.deviceList = Object.values(result)
          _this.deviceListInit = this.deviceList
          _this.deviceArray= result
        }).catch(err => {
          //失败
          _this.InfoTip.errorTip(_this, err);
        })
        await getAll;
        let deviceMgr = DeviceManager(_this.deviceArray)
        this.deviceList = deviceMgr.createNewDeviceListWithPortNameAndKey()

//初始化
        this.form.serviceSubnetID = this.initList.serviceSubnetID;
        this.form.serviceSubnetName = this.initList.serviceSubnetName;
        this.form.serviceSubnetTopo = this.initList.serviceSubnetTopo;
        this.form.serviceTypeID = this.initList.serviceTypeID;

        this.currentDeviceList = this.initList.currentDeviceList;
        this.serviceSubnetIDForUpdate = this.initList.serviceSubnetIDForUpdate;
        this.serviceSubnetNameForUpdate = this.initList.serviceSubnetNameForUpdate;
        if (!this.initList.currentDeviceList.length) {
          return
        }
        this.checked()
//        let tempDeviceList = this.deviceList
//        //初始化时修改当前附属设备的port的值"复制，删除使用"
//        for (var i = 0; i < this.currentDeviceList.length; i++) {
//          for (var j = 0; j < this.deviceList.length; j++) {
//            if (this.deviceList[j].deviceKey == this.currentDeviceList[i].deviceKey) {
//              tempDeviceList[j].port = this.currentDeviceList[i].port
//            }
//          }
//        }
//        this.deviceList = tempDeviceList
//
//        console.log("输出1")
//        console.log(this.deviceList)
//        console.log("输出2")
//        console.log(this.currentDeviceList)
//        console.log("输出3")
//        console.log(this.deviceArray)

      },


      formatEndDeviceKey: function (row, column) {
        console.log("过滤设备名称")

        for (var j = 0; j < this.deviceListInit.length; j++) {
          if (row.deviceKey == this.deviceListInit[j]['deviceKey']) {
            return this.deviceListInit  [j]['deviceName']
          }
        }

      },
      //------------------------------------修改开始-------------------------------------------------------------------


      updateEveSubnet() {
        let _this = this;
        if (!(_this.totalCheck())) {
          return
        }
//        else if (this.isPortTrue == false) {
//          let message = '请输入有效的portID'
//          this.InfoTip.warningTip(this, {message: message})
//
//          return
//        }
        else {
          let ethernetSubnet = {};

          ethernetSubnet.serviceSubnetID = this.form.serviceSubnetID;
          ethernetSubnet.serviceSubnetName = this.form.serviceSubnetName;
          ethernetSubnet.serviceSubnetTopo = this.form.serviceSubnetTopo;
          ethernetSubnet.serviceTypeID = this.form.serviceTypeID;
          ethernetSubnet.subnetDevices = this.SubnetDeviceForCopy;

          console.log(ethernetSubnet)

//           let loadingInstance = _this.Loading.openLoading();
//           //TODO：调用service 实现子网名称的修改
//           ServiceSubnetService.modifyEveSubnet(ethernetSubnet,
//             ethernetSubnet.serviceSubnetID,
//             ethernetSubnet.serviceSubnetName).then(result => {
//             //成功
//             _this.Loading.closeLoading(loadingInstance);
// //            _this.InfoTip.successTip(_this, HelperUtil.getStatusCodeObjectByCode(_this.successCode.MODIFY_CODE));
// //            _this.close()
//           }).catch(err => {
//             //失败
//             _this.Loading.closeLoading(loadingInstance);
//             _this.InfoTip.errorTip(_this, err);
//             return
//           });
          let loadingInstance1 = _this.Loading.openLoading();
          ServiceSubnetService.modifySubnetDevices(ethernetSubnet).then(result => {
            //成功
            _this.Loading.closeLoading(loadingInstance1);
            _this.InfoTip.successTip(_this, HelperUtil.getStatusCodeObjectByCode(_this.successCode.MODIFY_CODE));
            _this.close()
          }).catch(err => {
            //失败
            _this.Loading.closeLoading(loadingInstance1);
            _this.InfoTip.errorTip(_this, err);
          });
        }
      },

      //------------------------------------创建结束-------------------------------------------------------------------

      //------------------------------------验证开始-------------------------------------------------------------------

      totalCheck() {
        this.SubnetDeviceForCopy = new Array()
        for (var i = 0; i < this.multipleSelectionCopy.length; i++) {
          this.SubnetDeviceForCopy.push({
            deviceKey: this.multipleSelectionCopy[i].deviceKey,
            port: this.multipleSelectionCopy[i].port,
          })
//          }
        }
        if (!this.serviceSubnetNameCheck()) {
          return false
        }
        if (!this.serviceSubnetIDCheck()) {
          return false
        }
        if (this.SubnetDeviceForCopy.length === 0) {
//          let message = '请输入有效的portID'
//          this.InfoTip.warningTip(this, {message: message})
//           let message = '请至少选择一条设备'
          this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.PLEASE_SELECT_AT_LEAST_ONE_DEVICE))
          return false
        }
        if (this.isPortTrue == false) {
          // let message = '请输入有效的portID'
          this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.PLEASE_ENTER_A_VALID_PORT_ID))
          return false
        }
        for (var i = 0; i < this.SubnetDeviceForCopy.length; i++) {


          if (this.SubnetDeviceForCopy[i].port === '' || this.SubnetDeviceForCopy[i].port === null) {
            // let message = '请输入有效的portID'
            this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.PLEASE_ENTER_A_VALID_PORT_ID))
            return false
          }
        }

        return true
      },
      /**
       * @Description  ：业务子网ID非空校验
       * @author       :
       * @param        :
       * @return       :
       * @exception    :
       * @date         : 2019/3/13
       */
      serviceSubnetIDCheck: function () {

        let serviceSubnetIDCheck = legitimacyCheck()
        if (!serviceSubnetIDCheck.textNullCheck(this.form.serviceSubnetID)) {
          // let message = '业务子网编号不可为空！ '
          this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.SERVICE_SUBNET_ID_CANNOT_BE_EMPTY))
//          this.$message({
//            type: 'warning',
//            message: '业务类型编号不可为空！ ',
//            duration: 10000,
//            showClose: true,
//          });
          return false
        } else if (!this.numCheck(this.form.serviceSubnetID)) {
          return false
        }
        else if (!this.textLengthCheck(this.form.serviceSubnetID)) {
          return false
        }
        return true
      },


      /**
       * @Description  ：输入数字
       * @author       : bjh
       * @param        :
       * @return       :
       * @exception    :
       * @date         : 2019/1/15 16:09
       */
      numCheck: function (checkNumber) {
        let _this = this
        let serviceSubnetIDCheck = legitimacyCheck()
        if (!serviceSubnetIDCheck.numberCheck(checkNumber)) {
          // let message = '请输入有效的数字'
          this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.PLEASE_ENTER_A_VALID_NUMBER))
//          this.$message({
//            type: 'warning',
//            message: '请输入有效的数字！ ',
//            duration: 10000,
//            showClose: true,
//          });
          return false
        }
        return true
      },

      /**
       * @Description  ：子网名称校验： 不能为空
       * @author       :
       * @param        :
       * @return       :
       * @exception    :
       * @date         :
       */
      serviceSubnetNameCheck: function () {
        let eveSubnetCheck = legitimacyCheck()
        if (!eveSubnetCheck.textNullCheck(this.form.serviceSubnetName)) {
          // let message = '业务子网名称不可为空'
          this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.SERVICE_SUBNET_NAME_CANNOT_BE_EMPTY))
//          this.$message({
//            type: 'warning',
//            message: '业务子网名称不可为空！ ',
//            duration: 10000,
//            showClose: true,
//          });
          return false
        }
        this.textLengthCheck(this.form.serviceSubnetName)
        return true
      },


      /**
       * @Description  ：文本框所输入的字符长度校验： 控制在20之内
       * @author       : bjh
       * @param        :
       * @return       :
       * @exception    :
       * @date         : 2019/1/15 16:09
       */
      textLengthCheck: function (checkString) {
        let subnetCheck = legitimacyCheck()
        if (!subnetCheck.textLengthCheck(checkString)) {
          let message = '所输文本长度必须控制在20之内'
          this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.LENGTH_CODE))
//          this.$message({
//            type: 'warning',
//            message: '所输文本长度必须控制在20之内！ ',
//            duration: 10000,
//            showClose: true,
//          });
          return false
        }
        return true
      },
      //------------------------------------验证结束-------------------------------------------------------------------

    },
    created() {
      console.log('初始化加载数据')
      this.getAllEvc()

//      this.checked()
    },

    mounted() {
      this.getAllDevice()
      this.UpdateSubnetVisible = true

    },



  }
</script>
