<script lang="ts" setup>
import { reactive, ref, watch, nextTick, computed } from 'vue';
import { reqPath } from '@/api/reqPath';
import $http from '@/utils/http-service';
import { showElMessage, deepClone, compareObjectEqual } from '@/utils/utils';
import { traduction, getErrorTranslate } from '@/utils/language';
import { showFailedMessage } from '@/utils/composition';
import GlobalStoreService from '@/services/gloabal-store-service';
import { rangeVerification } from '@/validators/validation-functions';
import useStore from '@/stores';
import ErrorIcon from '@/components/ErrorIcon/ErrorIcon.vue';
import ClearableIcon from '@/components/ClearableIcon/ClearableIcon.vue';
const globalStoreService = new GlobalStoreService();

const props = defineProps({
  data: {
    type: Object,
    default: () => {
      return {};
    },
    required: true,
  },
  lock: {
    type: Boolean,
    default: false,
    required: false,
  },
  permission: {
    type: Boolean,
    default: false,
    required: false,
  },
  isNCSI: {	
    type: Boolean,	
    default: true,	
    required: false,	
  },
  address: {
    type: String,
    default: '',
    required: false,
  },
  multiSupported: {
    type: Boolean,
    default: false,
    required: true,
  },
  netType: {
    type: String,
    default: '',
    required: true,
  },
});

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

const store = useStore();
const productType = computed(() => {
  return store.state.glob.productType;
});

let vlanTitle = ref('');

// 记录原始数据
let preVlanData: any = {};

// 展示数据
let netVlanForm: any = reactive({});

// vlanId的状态值
let vlanIdState = ref(false);

// 保存按钮的状态值
const saveBtnState = ref(false);

const popoverVisible = reactive({
  vlanId: false,
});
const ruleFormRef = ref();

// 记录校验结果
let validateResult: any = {};

// 记录最终保存数据,保存按钮需要传的参数
let queryParams: any = {};

// vlanid校验规则 1.必填 2.数字 3.整型 4.范围1-4094
let rules = reactive({
  vlanId: {},
});

const min = ref(1);
const max = ref(4094);

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

// vlan开关
function vlanEnableChange(value: any) {
  if (!value) {
    netVlanForm.vlanId = 0;
    vlanIdState.value = true;
    ruleFormRef.value.clearValidate('vlanId');
  } else {
    netVlanForm.vlanId = preVlanData.vlanId;
    validateResult = rules.vlanId.validator(rules.vlanId, '0', () => {});
    vlanIdState.value = false;
  }
  setSaveBtnState();
}

// 输入框 发生input 事件
function input(value: string) {
  // 调用校验方法校验数据是否能通过，因为当前校验方式是blur，在input事件触发时不会触发校验，
  // 但是为了在输入的时候控制保存按钮的状态，需要手动去触发校验函数获取校验结果，进而控制保存按钮状态
  validateResult = rules.vlanId.validator(rules.vlanId, value, () => {});

  nextTick(() => {
    setSaveBtnState();
  });
}

// 表单校验发生时 - 控制保存按钮状态 state:校验结果
function validate(state: boolean) {
  validateResult = state;
}

// 设置保存按钮状态
function setSaveBtnState() {
  if (!validateResult) {
    saveBtnState.value = true;
    return;
  }
  const tempData = deepClone(preVlanData);
  if (tempData.vlanId) {
    tempData.vlanId = Number(tempData.vlanId);
  }
  // 校验成功后，进行初始值和修改值的对比，看是否发生修改
  saveBtnState.value = compareObjectEqual(tempData, netVlanForm);
}

// 保存
function vlanButton() {
  if (props.multiSupported) {
    if (props.data.type === 'Dedicated') {
      queryParams = { DedicatedVLAN: {}, PermanentMACAddress: '' };
      if (netVlanForm.vlanEnable !== preVlanData.vlanEnable) {
        queryParams.DedicatedVLAN['Enabled'] = netVlanForm.vlanEnable;
      }
      if (netVlanForm.vlanEnable && netVlanForm.vlanId !== preVlanData.vlanId) {
        queryParams.DedicatedVLAN['VLANId'] = Number(netVlanForm.vlanId);
      }
    } else {
      queryParams = { NcsiVLAN: {}, PermanentMACAddress: '' };
      if (netVlanForm.vlanEnable !== preVlanData.vlanEnable) {
        queryParams.NcsiVLAN['Enabled'] = netVlanForm.vlanEnable;
      }
      if (netVlanForm.vlanEnable && netVlanForm.vlanId !== preVlanData.vlanId) {
        queryParams.NcsiVLAN['VLANId'] = Number(netVlanForm.vlanId);
      }
    }
    queryParams.PermanentMACAddress = props.address;
  } else {
    if (props.isNCSI) {	
      queryParams = { NcsiVLAN: {} };	
      if (netVlanForm.vlanEnable !== preVlanData.vlanEnable) {	
        queryParams.NcsiVLAN['Enabled'] = netVlanForm.vlanEnable;	
      }	
      if (netVlanForm.vlanEnable && netVlanForm.vlanId !== preVlanData.vlanId) {	
        queryParams.NcsiVLAN['VLANId'] = Number(netVlanForm.vlanId);	
      }	
    } else {	
      queryParams = { DedicatedVLAN: {} };	
      if (netVlanForm.vlanEnable !== preVlanData.vlanEnable) {	
        queryParams.DedicatedVLAN['Enabled'] = netVlanForm.vlanEnable;	
      }	
      if (netVlanForm.vlanEnable && netVlanForm.vlanId !== preVlanData.vlanId) {	
        queryParams.DedicatedVLAN['VLANId'] = Number(netVlanForm.vlanId);	
      }	
    }
  }
  $http
    .patch(reqPath.manager.networkSettings, queryParams)
    .then((res: any) => {
      emits('initShowData', res.data);
      saveBtnState.value = true;
      showElMessage('success', traduction('COMMON_SUCCESS'));
    })
    .catch(error => {
      const errorCode = error?.data.error[0].code;
      showFailedMessage(getErrorTranslate(errorCode) || traduction('COMMON_FAILED'));
    });
}
// 获取标题————getVlanTitle
function getVlanTitle(res: any) {
  if (props.isNCSI) {
    switch (res) {
      case 'IBMC':
        vlanTitle.value = traduction('IBMC_VLAN');
        break;
      case 'IRM':
        vlanTitle.value = traduction('IRM_VLAN');
        break;
      case 'EMM':
        break;
      default:
        break;
    }
  } else {
    vlanTitle.value = 'Dedicated VLAN';
  }
}
// 数据初始化
function vlanInit(vlanData: any) {
  validateResult = {};
  if (JSON.stringify(vlanData) === '{}') {
    return;
  }

  if (vlanData.vlanId || vlanData.vlanId === 0) {
    vlanData.vlanId = vlanData.vlanId.toString();
  }

  // 保存原始数据
  preVlanData = deepClone(vlanData);
  // 初始化展示数据
  Object.assign(netVlanForm, deepClone(vlanData));
  getVlanTitle(productType.value);
  // 设置保存按钮和vlanId的状态
  saveBtnState.value = true;
  min.value = vlanData.minVlanId;
  max.value = vlanData.maxVlanId;
  rules.vlanId = {
    type: 'number',
    required: true,
    isInteger: true,
    min: min.value,
    max: max.value,
    message: traduction('VALID_VALUE_RANGE_TIP', [min.value, max.value]),
    validator: (rule: any, value: string, callback: any) => {
      return rangeVerification(rule, value, callback);
    },
    trigger: 'blur',
  };
  if (!netVlanForm.vlanEnable || props.lock || !props.permission) {
    vlanIdState.value = true;
  }
}

function focus(key: string) {
  popoverVisible[key] = true;
}

function blur(key: string) {
  popoverVisible[key] = false;
}

function clear(key: string) {
  // 如果没有focus，那么这个地方需要手动调用一次校验
  if (!popoverVisible[key]) {
    ruleFormRef.value.validateField(key);
  }
}

vlanInit(props.data);
</script>

<template>
  <!-- 内容区 -->
  <div :id="isNCSI ? 'netwotkVlan' : 'dedicatedVlan'" class="box">	
    <div v-if="!multiSupported" class="part-title">{{ vlanTitle }}</div>
    <div v-else class="part-title">{{ $t('IBMC_IP_CONFIG') }}</div>
    <el-form
      ref="ruleFormRef"
      :rules="rules"
      :model="netVlanForm"
      label-position="left"
      label-width="auto"
      :validate-on-rule-change="false"
      @validate="validate"
    >
      <!-- VLAN使能 -->
      <el-form-item :label="$t('IBMC_IP_ADDRESS08')" class="switch-item network-page-label">
        <el-switch
          v-model="netVlanForm.vlanEnable"
          :disabled="!permission || lock"
          @change="vlanEnableChange"
        ></el-switch>
      </el-form-item>
      <el-form-item
        :label="$t('IBMC_VLAN_ID')"
        prop="vlanId"
        class="have-right-text-item network-page-label"
      >
        <el-popover
          v-model:visible="popoverVisible.vlanId"
          popper-class="no-wrap-popover"
          placement="right"
          :teleported="false"
          :content="$t('VALID_VALUE_RANGE_TIP', [min, max])"
          trigger="focus"
          trigger-keys
        >
          <template #reference>
            <el-input
              v-model="netVlanForm.vlanId"
              v-addId.input="'vlanId'"
              v-clearable
              clearable
              :disabled="vlanIdState"
              type="text"
              @focus="focus('vlanId')"
              @blur="blur('vlanId')"
              @input="input($event)"
              @clear="clear('vlanId')"
            >
              <template #suffix>
                <ErrorIcon />
                <ClearableIcon />
              </template>
            </el-input>
          </template>
        </el-popover>
      </el-form-item>
      <el-form-item class="button-class network-page-label">
        <el-button
          id="vlanButton"
          v-privil.baseConfig
          :disabled="saveBtnState"
          type="primary"
          @click="vlanButton"
        >
          {{ $t('COMMON_SAVE') }}
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style lang="scss" scoped>
.box {
  margin-top: 8px;
  padding: 16px;
  border: 1px solid #dfe5ef;
  border-radius: 4px;
  :deep(.have-right-text-item) {
    .el-form-item__content {
      display: flex;
      align-items: center;
    }
  }
  :deep(.el-form-item__label) {
    text-align: left;
  }
  .buttonClass {
    margin-bottom: 0;
  }

  .part-title {
    font-size: 14px;
    font-weight: bold;
    color: var(--o-text-color-primary);
    line-height: 22px;
    margin-bottom: 16px;
  }
  :deep(.el-input) {
    width: 320px;
  }

  :deep(.el-form) {
    .el-form-item {
      margin-bottom: 24px;
    }

    .button-class {
      margin-bottom: 0;
    }

    .switch-item {
      height: 16px;
      .el-form-item__label-wrap {
        .el-form-item__label {
          padding: 0 24px 0 0;
        }
      }
    }
  }

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

    .content {
      display: flex;
      align-items: center;

      .el-icon {
        margin-right: 16px;
        font-size: 28px;
      }
    }
  }
  :deep(.el-form-item.is-required):not(.is-no-asterisk)
    > .el-form-item__label-wrap
    > .el-form-item__label:before {
    display: none;
  }
}
</style>
