<template>
  <div class="app-container">
    <Form :formList="formList" :ruleFormData="ruleForm" :config="this.paramsData && this.paramsData.readonly ? {labelWidth: '140px', buttonGroup: []} : {labelWidth: '140px'}" @fnClick="callback">
      <template #tempVirtualNetCard="{ field, model, formModel }">
        <span style="color: rgb(96, 98, 102);font-weight: 700;padding: 0 15px;overflow-wrap: break-word;line-height: 25px;margin-top: 5px;">
          {{model}}
        </span>
        <button v-if="formModel && formModel[field.estimate]" @click="virtualNetCard(field, model)">虚拟网卡信息</button>
      </template>
    </Form>
    <el-button v-if="this.paramsData && this.paramsData.readonly" style="float: right;margin-top: 12px;margin-left: 10px;" @click="callback({fnCode: 'cancel'})">返回</el-button>
    <!--  虚拟网卡信息  -->
    <el-dialog :title="title" :visible.sync="virtualOpen" width="800px" append-to-body>
      <el-collapse v-model="activeList">
        <template v-for="(val,key, index) of virtualList">
          <el-collapse-item :title="`【${val && val.title || ''}】${val && val.serverIp || ''}`" :name="val && val.title || index">
            <div class="mt10 w100">
              <div class="w100 plr-20" style="font-size: 14px">
                <div v-for="(item,key,index) of virtualFormList"  class="w50 disInlineBlock p10">
                  <div class="disInlineBlock" style="width: 120px;color: #C0C4CC;">{{item}}</div>
                  <div style="width: calc(100% - 120px);vertical-align: top;" class="disInlineBlock">{{val && val.formModel[key] || '-'}}</div>
                </div>
              </div>
            </div>
          </el-collapse-item>
        </template>
      </el-collapse>
      <div style="text-align: right;margin-top: 12px;margin-left: 10px;">
        <el-button @click="virtualOpen = false">返回</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
  import Form from '@/components/form/index.vue';
  import {addMachine, getHandle, updateTopology, getRegistList, bindBusByClient, getAlarmLogServerMsg, virNetInterfaceChild} from "@/api/disRevenue/resource";
  import {listAllBusinessList} from "@/api/disRevenue/earnManage";
  export default {
    name: 'serverRegister_Edit',
    components: {Form},
    dicts: ['rm_register_status','rm_register_online_state'],
    data() {
      return {
        loading: false,
        virtualOpen: false,
        title: '',
        activeList: [],
        virtualFormList: {interfaceName:'接口名称', interfaceType:'接口类型', macAddress:'MAC地址', publicIp:'公网地址', isp:'运营商', province:'省', city:'市', ipv4Address:'IPv4地址', gateway:'IPv4网关', ipv6Address:'IPv6全球单播地址'},
        virtualList: {},
        ruleForm: {},
        formList: [],
        paramsData: {},
        switchNameList: [],
        serverNameList: [],
        serverPortList: [],
        interfaceNameList: [],
        busNameList: {},
      }
    },
    created() {
      this.paramsData = this.$route && this.$route.query;
      if (this.paramsData && this.paramsData.id) {
        this.getFormDataList(this.paramsData.id);
      }
      if (this.paramsData && this.paramsData.type && this.paramsData.type === 'edit') {
        this.fnBusNameList();
      }
      this.registList();
      this.fnFormList();
    },
    methods: {
      // formList集合
      fnFormList(objVal) {
        if (this.paramsData && this.paramsData.type && this.paramsData.type === 'edit') {
          this.$set(this.ruleForm, 'deployDevice', this.paramsData.clientIdList);
          this.formList = [{
            config: {title: '基本信息',labelWidth: '140px', colSpan: 'disBlock'},
            controls: {
              id: {label: 'ID',hidden: true},
              businessName: {label: '业务名称', span: 12, type: 'select', options:[], required: true},
              deployDevice: {label: '服务器列表', span: 12, type: 'textarea', rows: 15, required: true},
            }
          }];
        } else if (this.paramsData && this.paramsData.readonly) {
          this.formList = [{
            config: {title: '基本信息',labelWidth: '140px', readonly: true},
            controls: {
              id: {label: 'ID',hidden: true},
              clientId: {label: 'ClientID', span: 12, type: 'select', options:[]},
              hardwareSn: {label: '设备SN', span: 12, type: 'input'},
              ip1Isp: {label: 'IP1-运营商', span: 12, type: 'input'},
              ip1Province: {label: 'IP1-省', span: 12, type: 'input'},
              ip1City: {label: 'IP1-市', span: 12, type: 'input'},
              ip1PublicIp: {label: 'IP1-业务公网', span: 12, type: 'input'},
              ip1InterfaceName: {label: 'IP1-接口名称', span: 12, slotName: 'tempVirtualNetCard', estimate: 'ip1IsVirth'},
              ip1MacAddress: {label: 'IP1-mac地址', span: 12, type: 'input'},
              ip1InterfaceType: {label: 'IP1-接口类型', span: 12, type: 'input'},
              ip1Ipv4Address: {label: 'IP1-IPv4地址', span: 12, type: 'input'},
              ip1Gateway: {label: 'IP1-网关', span: 12, type: 'input'},
              ip1Ipv6Address: { label: `IP1-IPv6全球单播地址`, span: 12, type: 'input'},
              ip2Isp: {label: 'IP2-运营商', span: 12, type: 'input'},
              ip2Province: {label: 'IP2-省', span: 12, type: 'input'},
              ip2City: {label: 'IP2-市', span: 12, type: 'input'},
              ip2PublicIp: {label: 'IP2-业务公网', span: 12, type: 'input'},
              ip2InterfaceName: {label: 'IP2-接口名称', span: 12, slotName: 'tempVirtualNetCard', estimate: 'ip2IsVirth'},
              ip2MacAddress: {label: 'IP2-mac地址', span: 12, type: 'input'},
              ip2InterfaceType: {label: 'IP2-接口类型', span: 12, type: 'input'},
              ip2Ipv4Address: {label: 'IP2-IPv4地址', span: 12, type: 'input'},
              ip2Gateway: {label: 'IP2-网关', span: 12, type: 'input'},
              ip2Ipv6Address: { label: `IP2-IPv6全球单播地址`, span: 12, type: 'input'},
              ip3Isp: {label: 'IP3-运营商', span: 12, type: 'input'},
              ip3Province: {label: 'IP3-省', span: 12, type: 'input'},
              ip3City: {label: 'IP3-市', span: 12, type: 'input'},
              ip3PublicIp: {label: 'IP3-业务公网', span: 12, type: 'input'},
              ip3InterfaceName: {label: 'IP3-接口名称', span: 12, slotName: 'tempVirtualNetCard', estimate: 'ip3IsVirth'},
              ip3MacAddress: {label: 'IP3-mac地址', span: 12, type: 'input'},
              ip3InterfaceType: {label: 'IP3-接口类型', span: 12, type: 'input'},
              ip3Ipv4Address: {label: 'IP3-IPv4地址', span: 12, type: 'input'},
              ip3Gateway: {label: 'IP3-网关', span: 12, type: 'input'},
              ip3Ipv6Address: { label: `IP3-IPv6全球单播地址`, span: 12, type: 'input'},
              mgmtIsp: {label: '管理网-运营商', span: 12, type: 'input'},
              mgmtProvince: {label: '管理网-省', span: 12, type: 'input'},
              mgmtCity: {label: '管理网-市', span: 12, type: 'input'},
              mgmtPublicIp: {label: '管理网-公网IP', span: 12, type: 'input'},
              mgmtInterfaceName: {label: '管理网-接口名称', span: 12, slotName: 'tempVirtualNetCard', estimate: 'mgmIsVirth'},
              mgmtMacAddress: {label: '管理网-mac地址', span: 12, type: 'input'},
              mgmtInterfaceType: {label: '管理网-接口类型', span: 12, type: 'input'},
              mgmtIpv4Address: {label: '管理网-IPv4地址', span: 12, type: 'input'},
              mgmtGateway: {label: '管理网-网关', span: 12, type: 'input'},
              mgmtIpv6Address: { label: `管理网-IPv6全球单播地址`, span: 12, type: 'input'},
              heartbeatInterval: {label: '心跳时间间隔', span: 12, type: 'input'},
              heartbeatCount: {label: '心跳次数', span: 12, type: 'input'},
              businessName: {label: '业务名称', span: 12, type: 'input'},
              bandwidthResult: { label: `昨日95值(Mbit)`, span: 12, type: 'input'},
              bandwidthRate: { label: `日95带宽值利用率`, span: 12, type: 'input'},
              reportedBandwidth: { label: `上报带宽值(Mbit)`, span: 12, type: 'input'},
              logicalNodeId: {label: '逻辑节点标识', span: 12, type: 'input'},
              onlineStatus: {label: '在线状态', span: 12, type: 'select', options: this.dict.type.rm_register_online_state},
              registrationStatus: {label: '注册状态', span: 12, type: 'select', options: this.dict.type.rm_register_status},
              createTime: {label: '注册时间', span: 12, type: 'input'},
              onboardTime: {label: '上机时间', span: 12, type: 'input'},
              agentVersion: {label: 'agent版本', span: 12, type: 'input'},
              machineCode: {label: '金山machineCode', span: 12, type: 'input'},
              remark: {label: '标签', span: 12, type: 'dynamicTags'},
              cpuUtil:{ label: `CPU使用率`,span: 12, type: 'input'},
              memUtil:{ label: `内存使用率`,span: 12, type: 'input'},
            }
          }];
        } else {
          this.formList = [{
            config: {title: '基本信息',labelWidth: '140px', colSpan: 'disBlock'},
            controls: {
              id: {label: 'ID',hidden: true},
              clientId: {label: 'ClientID', span: 12, type: 'select', options:[], required: true},
              machineCode: {label: '金山machineCode', span: 12, type: 'input', required: true},
            }
          }];
        }
      },
      // clientId
      registList() {
        this.clientIdList = {};
        getRegistList({resourceType: 1}).then(res => {
          this.formList[0].controls.clientId['options'] = res && res.data.map(item => {
            this.clientIdList[item.clientId] = item.clientId;
            return Object.assign({label: item.clientId, value: item.clientId});
          });
        });
      },
      // 业务名称
      fnBusNameList() {
        listAllBusinessList().then(res => {
          this.formList[0].controls.businessName['options'] = res && res.data.map(item => {
            this.busNameList[item.businessName] = item;
            return Object.assign({label: item.businessName, value: item.businessName});
          });
        });
      },
      // 获取详情
      getFormDataList(id) {
        let params = id;
        let fnName = getHandle;
        if (this.paramsData && this.paramsData.type === 'alarmLog') {
          params = {clientId: this.paramsData.id};
          fnName = getAlarmLogServerMsg;
        }
        fnName(params).then(val => {
          if (val && val.data) {
            val.data['remark'] = val.data && val.data['remark'] ? val.data['remark'].split(',') : null;
            this.ruleForm = val && val.data;
          }
        }).catch(() => {
          this.$modal.msgError("操作失败")
        });
      },
      virtualNetCard(res,model) {
        this.virtualOpen = true;
        this.title = model + '的虚拟网卡信息';
        virNetInterfaceChild({clientId: this.ruleForm.clientId, parentInterface: model}).then(resVal => {
          resVal && resVal.data.forEach(item => {
            this.activeList.push(item.interfaceName);
            this.virtualList[item.interfaceName] = {title: item.interfaceName,formModel: item};
          });
        });
      },
      // 监听事件
      callback(result, dataVal, formVal) {
        if (result && result.fnCode) {
          switch (result.fnCode) {
            case 'submit':
              if (this.paramsData && this.paramsData.type && this.paramsData.type === 'edit') {
                let unknownData = [];
                if (dataVal && dataVal.deployDevice) {
                  let deployList = JSON.parse(JSON.stringify(dataVal.deployDevice.trim())).split('\n');
                  deployList.forEach(item => {
                    if (!this.clientIdList[item]) {
                      unknownData.push(item);
                    }
                  });
                }
                if (unknownData && unknownData.length > 0) {
                  this.$modal.msgWarning(`存在未知的ClientID: ${unknownData.join('; ')}`);
                  return;
                }
                dataVal['businessCode'] = this.busNameList[dataVal.businessName].id;
                bindBusByClient(dataVal).then(res => {
                  this.$modal.msgSuccess(res.msg);
                  this.$router.push("/resource/serverRegister");
                });
              } else {
                let content = '<p style="font-size: 1rem;font-weight: 600;">确认添加machineCode</p>' +
                  '<p style="height: 0px;margin-bottom: 50px;">一旦添加machineCode后，将不能修改</p>';
                this.$modal.confirm(content, {submitTitle: '确认添加'}).then(() => {
                  let fnType = addMachine;
                  if (dataVal && dataVal.id) {
                    fnType = updateTopology;
                  }
                  if(this.loading) return;
                  this.loading = true;
                  fnType(dataVal).then(response => {
                    this.$modal.msgSuccess(response.msg);
                    this.$router.push("/resource/serverRegister");
                    this.loading = false;
                  }).catch(() => {
                    this.$modal.msgError("操作失败")
                  });
                }).catch(() => {});
              }
              break;
            case 'cancel':
              if (this.paramsData && this.paramsData.type === 'alarmLog') {
                // this.$router.push("/resource/alarmLog");
                history.go(-1);
              } else {
                this.$router.push("/resource/serverRegister");
              }
              break;
            default:
          }
        }
      }
    }
  }
</script>
<style scoped>
  ::v-deep .el-radio {
    margin-right: 15px!important;
  }
  ::v-deep .el-collapse-item__header {
    background-color: #d4e3fc!important;
    /*color: #fff!important;*/
    padding-left: 20px;
    font-size: 1rem;
  }
</style>
