//  Copyright (c) 2024 Huawei Technologies Co., Ltd.
//  openUBMC is licensed under Mulan PSL v2.
//  You can use this software according to the terms and conditions of the Mulan PSL v2.
//  You may obtain a copy of Mulan PSL v2 at:
//        #  http://license.coscl.org.cn/MulanPSL2
//  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
//  EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
//  MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
//  See the Mulan PSL v2 for more details.
import { traduction } from '@/utils/language';
import {
  DigitalWarrantyId,
  ISystemInfo,
  ISystemItem,
  productId,
  systemId,
  IUpdateBody,
} from './../product.datatype';
import { DEFAULT_DATA } from '@/model/base-enum';
import { VALID_PRODUCT_POSITION, VALID_PRODUCT_TAG } from '@/utils/regular';
import { updateProductInfo } from '../service/system.service';
import { getDataType } from '@/utils/utils';

export function parseValue(value: any) {
  if (value === null || value === undefined) {
    return DEFAULT_DATA.noDataStr;
  } else if (typeof value === 'string' && value.indexOf('(') > -1) {
    return value.replace('(', ' (');
  } else {
    return value;
  }
}

export function isOtherEmptyProperty(value: any, unit?: string): any {
  if (
    value === null ||
    value === undefined ||
    value === 'N/A' ||
    value === '' ||
    value === 'Unknown'
  ) {
    return DEFAULT_DATA.noDataStr;
  } else {
    return value;
  }
}
export function labelEditInfo(item: ISystemItem) {
  item.inputShow = true;
}

export function labelConfirm(item: ISystemItem) {
  item.inputShow = false;
  item.inputError = false;
  // 资产标签展示不显示换行，编辑显示换行
  if (item.id === 'assetTag') {
    item.tempContent = item.editContent !== '' ? (item.editContent as any) : DEFAULT_DATA.noDataStr;
  }
  item.content = item.editContent !== '' ? item.editContent : DEFAULT_DATA.noDataStr;
}

export function labelCancel(item: ISystemItem) {
  item.inputShow = false;
  item.inputError = false;
  // 资产标签展示不显示换行，编辑显示换行
  if (item.id === 'assetTag') {
    item.editContent = item.tempContent === DEFAULT_DATA.noDataStr ? '' : item.tempContent;
  } else {
    item.editContent = item.content === DEFAULT_DATA.noDataStr ? '' : item.content;
  }
}

const DELETE = 127; // 删除
const SPACE = 32; // 空格
// 检验不可见字符
function validateByte(str: string, item: ISystemItem): boolean {
  const isAssetTag = item.id === 'assetTag';
  for (let i = 0; i < str.length; i++) {
    const bt = str.charCodeAt(i);
    //  资产标签支持换行/回车
    if (isAssetTag) {
      if (bt === 10 || bt === 13) {
        continue;
      }
    }
    if (bt < SPACE || bt >= DELETE) {
      return false;
    }
  }
  return true;
}

export function labelChange(value: string, item: ISystemItem, pattern: RegExp) {
  if (!pattern.test(value) || !validateByte(value, item)) {
    item.inputError = true;
  } else {
    item.inputError = false;
  }
}

function updateProductValue(value: IUpdateBody, item: ISystemItem, store: any): any {
  updateProductInfo(value)
    .then((res: any) => {
      labelConfirm(item);
      store.state.event.setEventState({
        type: 'alertMessage',
        value: { type: 'success', message: traduction('COMMON_SUCCESS') },
      });
    })
    .catch((error: any) => {
      labelCancel(item);
    });
}

function getAssertTagItem(assetTag: any, store: any): ISystemItem {
  return {
    label: 'INFO_PRODUCT_ASSET_TAG',
    id: productId.assetTag,
    content: parseValue(assetTag) !== '' ? parseValue(assetTag).replace(/\n/g, '') : DEFAULT_DATA.noDataStr,
    hide: assetTag === undefined,
    tempContent: parseValue(assetTag) === DEFAULT_DATA.noDataStr ? '' : parseValue(assetTag),
    editContent: parseValue(assetTag) === DEFAULT_DATA.noDataStr ? '' : parseValue(assetTag),
    placeholderText: `${traduction('COMMON_INPUT_TEXT')}${traduction('INFO_PRODUCT_ASSET_TAG')}`,
    maxSize: 48,
    toolTipText: traduction('COMMON_TIPS_NOCHECK', [0, 48]),
    isEditable: true,
    inputShow: false,
    inputError: false,
    confirm: function (item: ISystemItem) {
      if (item.inputError) {
        return;
      }
      updateProductValue({ AssetTag: item.editContent }, item, store);
    },
    cancel: function (item: ISystemItem) {
      labelCancel(item);
    },
    editInfo: function (item: ISystemItem) {
      labelEditInfo(item);
    },
    change: function (value: string, item: ISystemItem) {
      labelChange(value, item, VALID_PRODUCT_TAG);
    },
  };
}

function getDeviceLocationItem(deviceLocation: any, store: any): ISystemItem {
  return {
    label: 'INFO_PRODUCT_POSITION',
    id: productId.position,
    content:
      parseValue(deviceLocation) !== '' ? parseValue(deviceLocation) : DEFAULT_DATA.noDataStr,
    hide: deviceLocation === undefined,
    editContent:
      parseValue(deviceLocation) === DEFAULT_DATA.noDataStr ? '' : parseValue(deviceLocation),
    placeholderText: `${traduction('COMMON_INPUT_TEXT')}${traduction('INFO_PRODUCT_POSITION')}`,
    maxSize: 64,
    toolTipText: traduction('COMMON_TIPS_NOCHECK', [0, 64]),
    isEditable: true,
    inputShow: false,
    inputError: false,
    confirm: function (item: ISystemItem) {
      if (item.inputError) {
        return;
      }
      updateProductValue({ DeviceLocation: (item.editContent as any) }, item, store);
    },
    cancel: function (item: ISystemItem) {
      labelCancel(item);
    },
    editInfo: function (item: ISystemItem) {
      labelEditInfo(item);
    },
    change: function (value: string, item: ISystemItem) {
      labelChange(value, item, VALID_PRODUCT_POSITION);
    },
  };
}
function getName(product: any): string {
  let name = product.ProductName;
  if (product.ProductAlias) {
    name += `(${product.ProductAlias})`;
  }
  return name;
}

export function getProductData(product: any, store: any): ISystemInfo {
  const name = getName(product);
  const itemArray = [
    { label: 'INFO_PRODUCT_NAME', id: productId.productInfoName, data: name },
    { label: 'INFO_MANUFACTURER', id: productId.productManufacturer, data: product.ProductManufacturer },
    { label: 'INFO_PRODUCT_SERIAL_NUMBER', id: productId.productSerialNum, data: product.ProductSN },
    {
      label: 'INFO_SYSTEM_NUMBER',
      id: productId.systemSN,
      data: product.SystemSN,
      hide: product.ProductSN === product.SystemSN,
    },
    { label: 'INFO_PRODUCT_NUMBER', id: productId.bomNumber, data: product.PartNumber },
    // 处理多主机下 bios 信息展示
    ...(getDataType(product.Bios) === 'Array' && product.Bios.length > 0
      ? product.Bios.flatMap((item: any) => (
        [
          {
            id: `${productId.biosVersion}-${item.SystemId}`,
            label: `${traduction('HOME_HOST')}${item.SystemId} ${traduction('HOME_BIOS_VERSION')}`,
            data: item.Version || '--',
          },
          {
            id: `${productId.biosReleaseDate}-${item.SystemId}`,
            label: `${traduction('HOME_HOST')}${item.SystemId} ${traduction('HOME_BIOS_DATE')}`,
            data: item.ReleaseDate || '--',
          },
        ]
      ))
      : [
        { label: 'INFO_MAIN_BOARD_BIOS_VERSION', id: productId.biosVersion, data: product.BIOSVersion },
        { label: 'HOME_BIOS_DATE', id: productId.biosReleaseDate, data: product.BIOSReleaseDate },
      ]),
    { label: 'INFO_MAIN_BOARD_IBMC_VERSION', id: productId.ibmcVersion, data: product.BMCVersion },
    { label: 'INFO_MAIN_BOARD_MAIN_BOOT', id: productId.mainBoot, data: product.ActiveUbootVersion },
    { label: 'INFO_MAIN_BOARD_BACKUP_BOOT', id: productId.backupBoot, data: product.BackupUbootVersion },
    { label: 'INFO_MAIN_BOARD_FIRMWARE', id: productId.coprocessorFirmware, data: product.CoprocessorFirmwareVersion },
  ];
  return {
    title: 'SYSINFO_PRODUCTINFO',
    backgroundClassName: 'product-img',
    id: 'productInfo',
    data: [
      ...getLabelItemArray(itemArray),
      getAssertTagItem(product.AssetTag, store),
      getDeviceLocationItem(product.DeviceLocation, store),
    ],
  };
}

/* 获取一般标签*/
function getLabelItemArray(
  itemArray: Array<{ label: string; id: string; data: any; hide?: boolean }>,
): ISystemItem[] {
  let labelDataArray: ISystemItem[] = [];
  itemArray.forEach(element => {
    labelDataArray.push({
      label: element.label,
      id: element.id,
      hide: element.data === undefined || element.hide === true,
      content: parseValue(element.data),
    });
  });
  return labelDataArray;
}

export function getOSData(osInfo: any): ISystemInfo {
  const itemArray = [
    { label: 'INFO_SYSTEM_LOCAL_DOMAIN', id: systemId.localDomain, data: osInfo.HostName },
    { label: 'INFO_SYSTEM_IBMA_SERVICE', id: systemId.ibmaService, data: osInfo.BMAVersion },
    {
      label: 'INFO_SYSTEM_HOST_DESCRIPTION',
      id: systemId.description,
      data: osInfo.HostDescription,
    },
    { label: 'INFO_SYSTEM_IBMA_STATUS', id: systemId.ibmaStatus, data: osInfo.BMARunningStatus },
    { label: 'INFO_SYSTEM_KERNAL_VERSION', id: systemId.kernalVersion, data: osInfo.KernalVersion },
    { label: 'INFO_SYSTEM_IBMA_DRIVER', id: systemId.ibmaDriver, data: osInfo.BMADriver },
    { label: 'INFO_SYSTEM_DOMAIN', id: systemId.domain, data: osInfo.Domain },
    { label: 'INFO_SYSTEM_OPERATOR', id: systemId.operator, data: osInfo.OSVersion },
  ];
  return {
    title: 'INFO_SYSTEM',
    backgroundClassName: 'os-img',
    id: 'systemInfo',
    data: getLabelItemArray(itemArray),
  };
}

function getStartPointItem(startPoint: any, store: any): ISystemItem {
  return {
    label: 'INFO_WARRANTY_START_POINT',
    id: DigitalWarrantyId.startPoint,
    content: parseValue(startPoint) !== '' ? parseValue(startPoint) : DEFAULT_DATA.noDataStr,
    hide: startPoint === undefined,
    editContent: parseValue(startPoint) === DEFAULT_DATA.noDataStr ? '' : parseValue(startPoint),
    placeholderText: `${traduction('COMMON_INPUT_TEXT')}${traduction('INFO_WARRANTY_START_POINT')}`,
    isEditable: true,
    inputShow: false,
    inputError: false,
    confirm: function (item: ISystemItem) {
      if (item.inputError) {
        return;
      }
      updateProductValue(
        {
          DigitalWarranty: {
            StartPoint: item.editContent,
          },
        },
        item,
        store,
      );
    },
    cancel: function (item: ISystemItem) {
      labelCancel(item);
    },
    editInfo: function (item: ISystemItem) {
      labelEditInfo(item);
    },
    change: function (value: any, item: ISystemItem) {
      if (!value) {
        item.inputError = true;
      } else {
        item.inputError = false;
      }
    },
  };
}

function getLifeSpanItem(lifespan: any, store: any): ISystemItem {
  return {
    label: 'INFO_WARRANTY_LIFE_span',
    id: DigitalWarrantyId.lifespan,
    content: parseValue(lifespan) !== '' ? parseValue(lifespan) : DEFAULT_DATA.noDataStr,
    hide: lifespan === undefined,
    editContent: parseValue(lifespan) === DEFAULT_DATA.noDataStr ? '' : parseValue(lifespan),
    placeholderText: `${traduction('COMMON_INPUT_TEXT')}${traduction('INFO_WARRANTY_LIFE_span')}`,
    errorTip: '',
    isEditable: true,
    inputShow: false,
    inputError: false,
    confirm: function (item: ISystemItem) {
      if (item.inputError) {
        return;
      }
      updateProductValue(
        {
          DigitalWarranty: {
            Lifespan: Number(item.editContent),
          },
        },
        item,
        store,
      );
    },
    cancel: function (item: ISystemItem) {
      labelCancel(item);
    },
    editInfo: function (item: ISystemItem) {
      labelEditInfo(item);
    },
    change: function (value: string, item: ISystemItem) {
      lifeSpanChange(value, item);
    },
  };
}

function lifeSpanChange(value: string, item: ISystemItem) {
  const reg = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/;
  const reg1 = /^[+-]?[0-9]+\.{0,1}[0-9]*$/;
  if (!reg1.test(String(value))) {
    item.inputError = true;
    item.errorTip = traduction('VALID_NUMBER_INFO');
    return;
  } else {
    // 判断是否是整数
    if ((String(value)).indexOf('.') > -1) {
      if ((String(value))[(String(value)).indexOf('.') + 1]) {
        item.inputError = true;
        item.errorTip = traduction('VALID_INTEGER_INFO');
        return;
      } else {
        item.inputError = true;
        item.errorTip = traduction('VALID_NUMBER_INFO');
        return;
      }
    }
    if (!reg.test(String(value))) {
      item.inputError = true;
      item.errorTip = traduction('VALID_NUMBER_INFO');
      return;
    }
    if (Number(value) <= 0 || Number(value) > 255) {
      item.inputError = true;
      item.errorTip = traduction('VALID_RANGE_VALUE_ERR_MSG', [1, 255]);
    } else {
      item.inputError = false;
    }
  }
}

export function getDigitalWarrantyData(digitalWarranty: any, store: any): ISystemInfo {
  const itemArray = [
    {
      label: 'INFO_WARRANTY_NAME',
      id: DigitalWarrantyId.productNamePolicy,
      data: digitalWarranty.ProductName,
    },
    {
      label: 'INFO_SYSTEM_NUMBER',
      id: DigitalWarrantyId.serialNumber,
      data: digitalWarranty.SerialNumber,
    },
    {
      label: 'INFO_WARRANTY_MANUFACTURE_DATE',
      id: DigitalWarrantyId.manufactureDate,
      data: digitalWarranty.ManufactureDate,
    },
    { label: 'INFO_WARRANTY_UUID', id: DigitalWarrantyId.UUID, data: digitalWarranty.UUID },
    { label: 'INFO_WARRANTY_TYPE', id: DigitalWarrantyId.unitType, data: digitalWarranty.UnitType },
  ];
  return {
    title: 'INFO_WARRANTY',
    backgroundClassName: 'insurance-img',
    id: 'electronicPolicy',
    data: [
      ...getLabelItemArray(itemArray),
      getStartPointItem(digitalWarranty.StartPoint, store),
      getLifeSpanItem(digitalWarranty.Lifespan, store),
    ],
  };
}

export function checkAndClearArray(obj: any, key: string): void {
  if (!obj || typeof obj !== 'object') {
    return;
  }
  const array = obj[key];
  if (array === undefined || array === null) {
    return;
  }

  if (Array.isArray(array)) {
    if (array.length === 0) {
      obj[key] = null;
    } else {
      for (let i = 0; i < array.length; i++) {
        array[i] = isOtherEmptyProperty(array[i]);
      }
    }
  }
};