<script lang="ts" setup>
import { ref, PropType, onMounted, watch } from 'vue';
import { traduction } from '@/utils/language';
import { editNetworkData } from '../network.server';
import { showElMessage, deepClone } from '@/utils/utils';
import GlobalStoreService from '@/services/gloabal-store-service';

const globalStoreService = new GlobalStoreService();
const emits = defineEmits(['getData']);
const props = defineProps({
  data: {
    type: Array as PropType<any[]>,
    required: true,
    default: () => {
      return [];
    },
  },
  address: {
    type: String,
    default: '',
    required: false,
  },
  multiSupported: {
    type: Boolean,
    default: false,
    required: true,
  },
});

const saveBtnState = ref(true);
const networkPortMap: any = {
  Aggregation: traduction('IBMC_DEDICATED_NETWORK01'),
  LOM: traduction('IBMC_DEDICATED_NETWORK02'),
  FlexIO: traduction('IBMC_DEDICATED_NETWORK03'),
  ExternalPCIe: traduction('IBMC_DEDICATED_NETWORK04'),
  OCP: traduction('IBMC_DEDICATED_NETWORK05'),
  OCP2: traduction('IBMC_DEDICATED_NETWORK06'),
};

let baseNetPort: any = ref([]);

// 数据初始化
function portInit(networkPort: any) {
  baseNetPort.value = networkPort;
}

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

onMounted(() => {
  portInit(deepClone(props.data));
});

function comparePortNumbers(newArr: any, oldArr: any) {
  // 不选中网口时，按钮置灰
  if (!newArr.length) {
    showElMessage('error', traduction('IBMC_NETWORK_NOT_ALLOW'));
    return false;
  }
  // 已选择网口不支持取消选择
  let flag = true;
  oldArr.forEach((oldItem: any, index: number) => {
    const newItem = newArr[index];
    if (oldItem.checked && !newItem.checked) {
      showElMessage('error', traduction('IBMC_NETWORK_PORT_ISCANCEL'));
      flag = false;
    }
  });
  let keyA = new Set(newArr.map((item: any) => `${item.PortNumber}-${item.checked}`));
  let keyB = new Set(oldArr.map((item: any) => `${item.PortNumber}-${item.checked}`));
  let areEqual = keyA.size === keyB.size && [...keyA].every(key => keyB.has(key));
  return !areEqual && flag;
}

// 修改保存按钮的状态
function setSaveBtnState() {
  let flag = comparePortNumbers(baseNetPort.value, props.data);
  // 设置按钮的灰化和正常状态
  if (flag) {
    saveBtnState.value = false;
  } else {
    saveBtnState.value = true;
  }
}

// 点击确认
function sureSetting() {
  const queryParams = {
    NetworkPort: {
      ManagementNetworkPorts: [],
    },
    PermanentMACAddress: '',
  };
  if (props.multiSupported) {
    queryParams.PermanentMACAddress = props.address;
  }
  queryParams.NetworkPort.ManagementNetworkPorts = baseNetPort.value
    .filter((v: any) => v.checked)
    .map((item: any) => ({
      Type: item.Type,
      PortNumber: item.PortNumber,
    }));
  globalStoreService.setValue('isLoading', true);
  editNetworkData(queryParams)
    .then(data => {
      emits('getData');
      saveBtnState.value = true;
      showElMessage('success', traduction('COMMON_SUCCESS'));
      globalStoreService.setValue('isLoading', false);
    })
    .catch(err => {
      showElMessage('error', traduction('COMMON_FAILED'));
      globalStoreService.setValue('isLoading', false);
    });
}
</script>

<template>
  <div id="netwotkSelect" class="box">
    <div class="part-title">{{ $t('IBMC_NETWORK_PORT_SELECT') }}</div>
    <div class="row">
      <span class="key check-mode network-page-label">{{ $t('IBMC_NETWORK_PORT_SELECT') }}</span>
      <div class="content">
        <div class="check-box">
          <el-checkbox
            v-for="(item, index) in baseNetPort"
            :key="index"
            v-model="item.checked"
            size="large"
            @change="setSaveBtnState"
          >
            <span class="item-title">
              {{ item.Type === 'Dedicated' ? item.PortName : networkPortMap[item.PortName] }}
            </span>
          </el-checkbox>
        </div>
        <el-button id="selectButton" :disabled="saveBtnState" type="primary" @click="sureSetting">
          {{ $t('COMMON_SAVE') }}
        </el-button>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.box {
  margin-top: 16px;
  padding: 16px;
  border: 1px solid #dfe5ef;
  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;
    }
    .check-mode {
      margin-right: 24px;
    }
    .content {
      flex: 1;
      .check-box {
        margin-top: -10px;
        margin-bottom: 16px;
        .el-checkbox {
          min-width: 70px;
        }
      }
    }
  }
}
</style>
