<script lang="ts" setup>
import { reactive, ref, watch } from 'vue';
import { IconAlarm } from '@computing/opendesign-icons';
import { traduction } from '@/utils/language';
import { editNetworkData } from '../network.server';
import { showElMessage, deepClone } from '@/utils/utils';
import {
  protocolEnabledEN,
  addLabelId,
  compareArray,
} from './NetWorkPortMode/NetworkPortModeFunctions';

import GlobalStoreService from '@/services/gloabal-store-service';
import NetWorkPortList from './NetWorkPortMode/NetWorkPortList.vue';
import NetworkPortModeHelpPopperContent from './NetWorkPortMode/NetworkPortModeHelpPopperContent.vue';
import { getStoreData } from '@/utils/composition';

const globalStoreService = new GlobalStoreService();
const sn = getStoreData('loct', 'sn');
const props = defineProps({
  data: {
    type: Object,
    default: () => {
      return {};
    },
    required: true,
  },
  lock: {
    type: Boolean,
    default: false,
    required: false,
  },
  permission: {
    type: Boolean,
    default: false,
    required: false,
  },
});

const emits = defineEmits(['initShowData']);

watch(
  () => props.data,
  (val: any) => {
    portInit(deepClone(val));
  },
  {
    deep: true,
  },
);

const mode = ref('');
const saveBtnState = ref(true);
const dialogVisible = ref(false);

let baseNetPort: any = reactive({
  Type: null,
  PortNumber: null,
});

// 初始化的时候保存的数据，方便进行保存按钮的状态判断
let backDedicatedCheckbox: any[] = [];
let backAggregationCheckbox: any[] = [];
let backLomCheckbox: any[] = [];
let backLom2Checkbox: any[] = [];
let backPcieCheckbox: any[] = [];
let backOcpCheckbox: any[] = [];
let backOcpCheckbox2: any[] = [];

// 展示数据
let networkConfigObj = reactive({
  // 专用网口
  dedicatedInternetAc: {
    option: [],
    value: '',
    disabledNum: null,
    checkList: [],
  },
  onboardInternetAc: {
    option: [],
    value: '',
    disabledNum: null,
    checkList: [],
  },
  extendInternetAc: {
    option: [],
    value: '',
    disabledNum: null,
    checkList: [],
  },
  extendInternetAc2: {
    option: [],
    value: '',
    disabledNum: null,
    checkList: [],
  },
  pcieInternetAc: {
    option: [],
    value: '',
    disabledNum: null,
    checkList: [],
  },
  ocpInternetAc: {
    option: [],
    value: '',
    disabledNum: null,
    checkList: [],
  },
  ocpInternetAc2: {
    option: [],
    value: '',
    disabledNum: null,
    checkList: [],
  },
});

let networkPortType = reactive({
  Type: '',
  PortNumber: '',
});

let portParams = {};

function clearOcpInternetAc() {
  networkConfigObj.dedicatedInternetAc.value = '';
  networkConfigObj.onboardInternetAc.value = '';
  networkConfigObj.extendInternetAc.value = '';
  networkConfigObj.extendInternetAc2.value = '';
  networkConfigObj.pcieInternetAc.value = '';
  networkConfigObj.ocpInternetAc.value = '';
  networkConfigObj.ocpInternetAc2.value = '';
}

function getRelationRadio(networkPort: any) {
  return {
    Dedicated: {
      origin: networkPort.tempDedicated,
      target: networkConfigObj.dedicatedInternetAc,
    },
    Aggregation: {
      origin: networkPort.tempAggregation,
      target: networkConfigObj.onboardInternetAc,
    },
    LOM: {
      origin: networkPort.tempExtend,
      target: networkConfigObj.extendInternetAc,
    },
    FlexIO: {
      origin: networkPort.tempExtend2,
      target: networkConfigObj.extendInternetAc2,
    },
    ExternalPCIe: {
      origin: networkPort.tempPcie,
      target: networkConfigObj.pcieInternetAc,
    },
    OCP: {
      origin: networkPort.tempOcp,
      target: networkConfigObj.ocpInternetAc,
    },
    OCP2: {
      origin: networkPort.tempOcp2,
      target: networkConfigObj.ocpInternetAc2,
    },
  };
}

function objectAssignData(
  networkPort: any,
  key1: string,
  key2: string,
  key3: string,
  key4: string,
) {
  Object.assign(networkConfigObj[key1], {
    option: networkPort[key2],
    disabledNum: networkPort[key3],
    checkList: networkPort[key4],
  });
}

// 数据赋值与备份
function setAndCopy(networkPort: any) {
  // 专用网口
  objectAssignData(
    networkPort,
    'dedicatedInternetAc',
    'tempDedicated',
    'countDedicated',
    'tempCheckDedicated',
  );
  backDedicatedCheckbox = deepClone(networkPort.tempCheckDedicated);

  // 汇聚网口
  objectAssignData(
    networkPort,
    'onboardInternetAc',
    'tempAggregation',
    'countAggregation',
    'tempCheckAggregation',
  );
  backAggregationCheckbox = deepClone(networkPort.tempCheckAggregation);

  // 板载网口
  objectAssignData(networkPort, 'extendInternetAc', 'tempExtend', 'countExtend', 'tempCheckExtend');
  backLomCheckbox = deepClone(networkPort.tempCheckExtend);

  // 板载网口2
  objectAssignData(
    networkPort,
    'extendInternetAc2',
    'tempExtend2',
    'countExtend2',
    'tempCheckExtend2',
  );
  backLom2Checkbox = deepClone(networkPort.tempCheckExtend2);

  // PCIE扩展网口
  objectAssignData(networkPort, 'pcieInternetAc', 'tempPcie', 'countPcie', 'tempCheckPcie');
  backPcieCheckbox = deepClone(networkPort.tempCheckPcie);

  // OCP扩展网口
  objectAssignData(networkPort, 'ocpInternetAc', 'tempOcp', 'countOcp', 'tempCheckOcp');
  backOcpCheckbox = deepClone(networkPort.tempCheckOcp);

  // OCP2扩展网口
  objectAssignData(networkPort, 'ocpInternetAc2', 'tempOcp2', 'countOcp2', 'tempCheckOcp2');
  backOcpCheckbox2 = deepClone(networkPort.tempCheckOcp2);
}

// 数据初始化
function portInit(networkPort: any) {
  clearOcpInternetAc();

  if (JSON.stringify(networkPort) === '{}') {
    return;
  }
  // 选择模式
  portParams['schemaRadio'] = networkPort.schemaRadio;
  mode.value = portParams['schemaRadio'];
  // 管理网口
  networkPortType = networkPort.networkPortType;
  // 作为基础管理网口的数据
  baseNetPort = deepClone(networkPortType);

  // Radio 根据接口的管理网口字段，来选中固定设置具体的网口和端口
  const relationRadio = getRelationRadio(networkPort);

  if (baseNetPort.Type) {
    const tarRadio: any = relationRadio[baseNetPort.Type] || {};
    if (tarRadio.origin) {
      tarRadio.origin.forEach((itemData: any) => {
        if (itemData.id === baseNetPort.PortNumber) {
          tarRadio.target.value = itemData.id;
        }
      });
    }
  }

  setAndCopy(networkPort);
}

portInit(deepClone(props.data));

// 固定模式-单选框发生change事件
function networkInternetChange(part: any, data: { checkRadioItem: any; value: string }) {
  networkConfigObj.dedicatedInternetAc.value = '';
  networkConfigObj.onboardInternetAc.value = '';
  networkConfigObj.extendInternetAc.value = '';
  networkConfigObj.extendInternetAc2.value = '';
  networkConfigObj.pcieInternetAc.value = '';
  networkConfigObj.ocpInternetAc.value = '';
  networkConfigObj.ocpInternetAc2.value = '';
  const { checkRadioItem, value } = data;
  part.value = value;
  // 当前选中的网口模式;
  networkPortType.Type = checkRadioItem.Type;
  networkPortType.PortNumber = checkRadioItem.id;
  setSaveBtnState();
}

// 修改保存按钮的状态
function setSaveBtnState() {
  let flag1 = false;
  // 首先判断网口模式的选择
  if (mode.value !== portParams['schemaRadio']) {
    flag1 = true;
  }
  // 其次，当时固定模式时，校验radioList数据是否变化，否则校验checkList值是否变化
  let flag2 = false;
  if (mode.value === 'Fixed') {
    // 固定模式下的对比是按照，当前选中的
    if (
      baseNetPort.Type !== networkPortType.Type ||
      baseNetPort.PortNumber !== networkPortType.PortNumber
    ) {
      flag2 = true;
    }
  } else {
    flag2 = compareArray(backDedicatedCheckbox, networkConfigObj.dedicatedInternetAc.checkList);
    if (!flag2) {
      flag2 = compareArray(backAggregationCheckbox, networkConfigObj.onboardInternetAc.checkList);
    }
    if (!flag2) {
      flag2 = compareArray(backLomCheckbox, networkConfigObj.extendInternetAc.checkList);
    }
    if (!flag2) {
      flag2 = compareArray(backLom2Checkbox, networkConfigObj.extendInternetAc2.checkList);
    }
    if (!flag2) {
      flag2 = compareArray(backPcieCheckbox, networkConfigObj.pcieInternetAc.checkList);
    }
    if (!flag2) {
      flag2 = compareArray(backOcpCheckbox, networkConfigObj.ocpInternetAc.checkList);
    }
    if (!flag2) {
      flag2 = compareArray(backOcpCheckbox2, networkConfigObj.ocpInternetAc2.checkList);
    }
  }
  // 设置按钮的灰化和正常状态
  if (flag1 || flag2) {
    saveBtnState.value = false;
  } else {
    saveBtnState.value = true;
  }
  addLabelId();
}

// 点击确认
function sureSetting() {
  const queryParams = protocolEnabledEN(mode, networkPortType, networkConfigObj);
  globalStoreService.setValue('isLoading', true);
  editNetworkData(queryParams)
    .then(data => {
      emits('initShowData', data);
      saveBtnState.value = true;
      dialogVisible.value = false;
      showElMessage('success', traduction('COMMON_SUCCESS'));
      globalStoreService.setValue('isLoading', false);
    })
    .catch(err => {
      dialogVisible.value = false;
      showElMessage('error', traduction('COMMON_FAILED'));
      globalStoreService.setValue('isLoading', false);
    });
}
</script>

<template>
  <!-- 网口模式 -->
  <div id="netwotkPort" class="box">
    <div class="part-title">{{ $t('IBMC_NETWORK_PORT_MODE') }}</div>
    <div class="row">
      <span class="key check-mode network-page-label">{{ $t('IBMC_SELECTION_MODE') }}</span>

      <div class="content">
        <!--  固定设置 - 自动选择 -->
        <div class="radio-box">
          <el-popover
            placement="top"
            trigger="hover"
            popper-class="no-wrap-popover"
            :content="$t('IBMC_SELECT_MODE_TIPS1', { softwareName: sn })"
            trigger-keys
          >
            <template #reference>
              <el-radio
                v-model="mode"
                v-addId.radio="'portFixed'"
                label="Fixed"
                size="large"
                :disabled="!permission || lock"
                @change="setSaveBtnState"
              >
                {{ $t('IBMC_SETTING01') }}
              </el-radio>
            </template>
          </el-popover>

          <el-popover
            placement="top"
            trigger="hover"
            popper-class="no-wrap-popover"
            :content="$t('IBMC_SELECT_MODE_TIPS2', { softwareName: sn })"
            trigger-keys
          >
            <template #reference>
              <el-radio
                v-model="mode"
                v-addId.radio="'portAutomatic'"
                label="Automatic"
                size="large"
                :disabled="!permission || lock"
                @change="setSaveBtnState"
              >
                {{ $t('IBMC_SETTING02') }}
              </el-radio>
            </template>
          </el-popover>
        </div>

        <div class="bg-box">
          <!-- 指定物理网口 -->
          <div class="key">
            <span class="text">{{ $t('IBMC_NETWORK_PORT01') }}</span>

            <el-popover
              placement="right-start"
              popper-class="port-mode-popper"
              :teleported="false"
              trigger="hover"
              trigger-keys
            >
              <template #reference>
                <el-icon class="help-icon">
                  <span class="icon-help"></span>
                </el-icon>
              </template>
              <NetworkPortModeHelpPopperContent />
            </el-popover>
          </div>

          <div v-if="mode" class="table-box">
            <!-- 专用网口 -->
            <div
              v-if="
                networkConfigObj.dedicatedInternetAc.option.length &&
                  networkConfigObj.dedicatedInternetAc.disabledNum !==
                  networkConfigObj.dedicatedInternetAc.option.length
              "
              class="tr"
            >
              <div class="td key">{{ $t('IBMC_DEDICATED_NETWORK') }}</div>
              <NetWorkPortList
                :mode="mode"
                :data="networkConfigObj.dedicatedInternetAc"
                :fixed-item-id="'dedicatedRadio'"
                :automatic-item-id="'dedicatedCheck'"
                :lock="lock"
                :permission="permission"
                :base-net-port="baseNetPort"
                @set-save-btn-state="setSaveBtnState"
                @network-internet-change="
                  networkInternetChange(networkConfigObj.dedicatedInternetAc, $event)
                "
              />
            </div>

            <!-- 汇聚网口 -->
            <div
              v-if="
                networkConfigObj.onboardInternetAc.option.length &&
                  networkConfigObj.onboardInternetAc.disabledNum !==
                  networkConfigObj.onboardInternetAc.option.length
              "
              class="tr"
            >
              <div class="td key">{{ $t('IBMC_DEDICATED_NETWORK01') }}</div>
              <NetWorkPortList
                :mode="mode"
                :data="networkConfigObj.onboardInternetAc"
                :fixed-item-id="'onboardRadio'"
                :automatic-item-id="'onboardCheck'"
                :lock="lock"
                :permission="permission"
                :base-net-port="baseNetPort"
                @set-save-btn-state="setSaveBtnState"
                @network-internet-change="
                  networkInternetChange(networkConfigObj.onboardInternetAc, $event)
                "
              />
            </div>

            <!-- 板载网口 -->
            <div
              v-if="
                networkConfigObj.extendInternetAc.option.length &&
                  networkConfigObj.extendInternetAc.disabledNum !==
                  networkConfigObj.extendInternetAc.option.length
              "
              class="tr"
            >
              <div class="td key">{{ $t('IBMC_DEDICATED_NETWORK02') }}</div>
              <NetWorkPortList
                :mode="mode"
                :data="networkConfigObj.extendInternetAc"
                :fixed-item-id="'extendRadio'"
                :automatic-item-id="'extendCheck'"
                :lock="lock"
                :permission="permission"
                :base-net-port="baseNetPort"
                @set-save-btn-state="setSaveBtnState"
                @network-internet-change="
                  networkInternetChange(networkConfigObj.extendInternetAc, $event)
                "
              />
            </div>

            <!-- 板载网口2 -->
            <div
              v-if="
                networkConfigObj.extendInternetAc2.option.length &&
                  networkConfigObj.extendInternetAc2.disabledNum !==
                  networkConfigObj.extendInternetAc2.option.length
              "
              class="tr"
            >
              <div class="td key">{{ $t('IBMC_DEDICATED_NETWORK03') }}</div>
              <NetWorkPortList
                :mode="mode"
                :data="networkConfigObj.extendInternetAc2"
                :fixed-item-id="'extendAcRadio'"
                :automatic-item-id="'extendAcCheck'"
                :lock="lock"
                :permission="permission"
                :base-net-port="baseNetPort"
                @set-save-btn-state="setSaveBtnState"
                @network-internet-change="
                  networkInternetChange(networkConfigObj.extendInternetAc2, $event)
                "
              />
            </div>

            <!-- PCIE扩展网口 -->
            <div
              v-if="
                networkConfigObj.pcieInternetAc.option.length &&
                  networkConfigObj.pcieInternetAc.disabledNum !==
                  networkConfigObj.pcieInternetAc.option.length
              "
              class="tr"
            >
              <div class="td key">{{ $t('IBMC_DEDICATED_NETWORK04') }}</div>
              <NetWorkPortList
                :mode="mode"
                :data="networkConfigObj.pcieInternetAc"
                :fixed-item-id="'pcieRadio'"
                :automatic-item-id="'pcieCheck'"
                :lock="lock"
                :permission="permission"
                :base-net-port="baseNetPort"
                @set-save-btn-state="setSaveBtnState"
                @network-internet-change="
                  networkInternetChange(networkConfigObj.pcieInternetAc, $event)
                "
              />
            </div>

            <!-- OCP扩展网口 -->
            <div
              v-if="
                networkConfigObj.ocpInternetAc.option.length &&
                  networkConfigObj.ocpInternetAc.disabledNum !==
                  networkConfigObj.ocpInternetAc.option.length
              "
              class="tr"
            >
              <div class="td key">{{ $t('IBMC_DEDICATED_NETWORK05') }}</div>
              <NetWorkPortList
                :mode="mode"
                :data="networkConfigObj.ocpInternetAc"
                :fixed-item-id="'ocpRadio'"
                :automatic-item-id="'ocpCheck'"
                :lock="lock"
                :permission="permission"
                :base-net-port="baseNetPort"
                @set-save-btn-state="setSaveBtnState"
                @network-internet-change="
                  networkInternetChange(networkConfigObj.ocpInternetAc, $event)
                "
              />
            </div>

            <!-- OCP2扩展网口 -->
            <div
              v-if="
                networkConfigObj.ocpInternetAc2.option.length &&
                  networkConfigObj.ocpInternetAc2.disabledNum !==
                  networkConfigObj.ocpInternetAc2.option.length
              "
              class="tr"
            >
              <div class="td key">{{ $t('IBMC_DEDICATED_NETWORK06') }}</div>

              <NetWorkPortList
                :mode="mode"
                :data="networkConfigObj.ocpInternetAc2"
                :fixed-item-id="'ocpRadio2'"
                :automatic-item-id="'ocpCheck2'"
                :lock="lock"
                :permission="permission"
                :base-net-port="baseNetPort"
                @set-save-btn-state="setSaveBtnState"
                @network-internet-change="
                  networkInternetChange(networkConfigObj.ocpInternetAc2, $event)
                "
              />
            </div>
          </div>
        </div>

        <el-button
          v-if="permission"
          id="modeButton"
          :disabled="saveBtnState"
          type="primary"
          @click="dialogVisible = true"
        >
          {{ $t('COMMON_SAVE') }}
        </el-button>
      </div>
    </div>

    <!-- 点击保存的弹窗 -->
    <div v-if="dialogVisible" v-reqKeepAlive.dialog>
      <el-dialog v-model="dialogVisible" :title="$t('ALARM_OK')" :close-on-click-modal="false">
        <div class="content">
          <el-icon>
            <IconAlarm />
          </el-icon>
          <span id="networkPortModeTipText" class="text">{{ $t('NETWORK_PORT_CHANGE_TIP') }}</span>
        </div>

        <template #footer>
          <span class="dialog-footer">
            <el-button id="networkPortModeSave" size="small" type="primary" @click="sureSetting">
              {{ $t('NETWORK_PORT_CHANGE_OK') }}
            </el-button>
            <el-button id="networkPortModeCancel" size="small" @click="dialogVisible = false">
              {{ $t('COMMON_CANCEL') }}
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.box {
  margin-top: 8px;
  padding: 24px;
  background-color: var(--o-bg-color-base);
  border-radius: 4px;

  .part-title {
    font-size: 16px;
    font-weight: bold;
    color: var(--o-text-color-primary);
    line-height: 24px;
    margin-bottom: 16px;
  }

  .row {
    display: flex;
    align-items: flex-start;

    .check-mode {
      width: 135px;
    }

    .key {
      color: var(--o-text-color-secondary);
      font-size: 12px;
      display: flex;
      align-items: center;
      position: relative;

      .help-icon {
        margin-left: 5px;
        font-size: 16px;
        cursor: pointer;
        &:hover {
          .icon-help::before {
            color: var(--o-color-primary-secondary);
          }
        }
      }

      :deep(.port-mode-popper) {
        max-width: 382px !important;
        margin-top: -8px !important;

        .el-popper__arrow {
          top: 6px !important;
        }
      }
    }

    .check-mode {
      margin-right: 24px;
    }

    .content {
      flex: 1;

      .radio-box {
        .el-radio.el-radio--large {
          height: auto;
        }
      }

      .bg-box {
        margin: 8px 0 24px;
        padding: 24px 24px 16px;
        border-radius: 4px;
        background-color: var(--o-bg-color-light);

        .key .text {
          color: var(--o-text-color-primary);
          font-weight: 600;
        }

        .table-box {
          margin-top: 8px;
          display: table;

          :deep(.tr) {
            display: table-row;

            .td {
              display: table-cell;
              padding: 8px 0;

              .checks {
                display: flex;

                .el-checkbox.el-checkbox--large,
                .el-radio.el-radio--large {
                  height: auto;
                }

                .el-checkbox,
                .el-radio {
                  display: flex;
                  align-items: center;

                  .el-checkbox__input {
                    width: 14px;

                    .el-checkbox__inner::after {
                      top: 2px;
                      left: 4px;
                    }
                  }

                  .el-checkbox__label,
                  .el-radio__label {
                    display: flex;
                    align-items: center;

                    .item-title {
                      margin-right: 8px;
                    }

                    .circle {
                      display: inline-block;
                      width: 14px;
                      height: 14px;
                      border-radius: 50%;
                      background-color: rgba(36, 171, 54, 1);
                    }

                    .bg2 {
                      background-color: rgba(191, 199, 215, 1);
                    }

                    .success-icon {
                      font-size: 16px;
                    }
                  }
                }
              }
            }

            .key {
              line-height: 16px;
              padding-right: 24px;
            }

            .value {
              vertical-align: top;
            }
          }
        }
      }
    }
  }

  :deep(.el-dialog) {
    width: 432px;

    .content {
      display: flex;

      .el-icon {
        margin-right: 16px;
        font-size: 28px;
      }

      .text {
        padding-top: 5px;
      }
    }
  }
}
</style>
