//  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 { IVolumeEditData, StorageTree, VolumeEditModel } from '../../../models';
import { deleteEmptyProperty } from '../../../utils';
import $http from '@/utils/http-service';

export class VolumeEditService {
  constructor() { }

  private save(dataCopy: any, data: IVolumeEditData) {
    const obj = {};
    for (const attr in data) {
      if (JSON.stringify(data[attr]) !== JSON.stringify(dataCopy[attr])) {
        const key: string = attr.substring(0, 1).toUpperCase() + attr.substring(1);
        let value: any = null;
        if (data[attr]?.name) {
          value = data[attr].id;
        } else {
          value = data[attr];
        }
        obj[key] = value;
      }
    }
    const param = deleteEmptyProperty(obj);
    return (param && JSON.stringify(param) !== '{}') ? param : null;
  }

  public updateEditData(url: string) {
    const param = this.save(VolumeEditModel.getInstance().getOriginData, VolumeEditModel.getInstance().getSelectData);
    // 若有容量单位便获或有容量变化，则将容量数据也带到发送参数中
    if (param.CapacityUnit || param.Capacity) {
      const unitType = {
        MB: 1,
        GB: 1024,
        TB: 1024 * 1024,
      };
      let capacityBytes = param.Capacity || VolumeEditModel.getInstance().getSelectData.capacity;
      const unit = param.CapacityUnit || VolumeEditModel.getInstance().getSelectData.capacityUnit;
      capacityBytes = Math.floor(parseFloat(capacityBytes) * unitType[unit.id || unit]);
      delete param.Capacity;
      delete param.CapacityUnit;
      param.CapacityMBytes = capacityBytes;
    }
    return $http.patch(url, param);
  }
}
