/*
 * @Author: Maple
 * @Date: 2021-03-22 11:42:26
 * @LastEditors: Do not edit
 * @LastEditTime: 2021-05-27 11:07:18
 * @Description: 全局系统服务
 */
import { Injectable, Injector } from '@angular/core';
import { Observable, zip } from 'rxjs';
import { catchError, switchMap } from 'rxjs/operators';
import { CoreService } from 'src/app/core/core.service';
import { BaseService } from '../core/base.service';

@Injectable({
  providedIn: 'root',
})
export class EAPlatformService extends BaseService {
  public $api_update_platform_name = `/chia/operationInfo/updatePlatformName`; // 修改当前登录平台名称

  /**
   * 判断是否已经设置平台名称
   */
  private $api_is_set_platform_name = `/chia/operationInfo/judgeSetPlatformName`;
  /**
   * 获取当前登录用户绑定的运营商有效期
   */
  private $api_get_validity_period_of_operator = `/chia/operationInfo/getOperationDetailByToken`;

  /**
   * 缓存平台状态键名
   */
  private _cachePlatformStatusKey = '_cpsk';
  /**
   * 运营商剩余有效期
   */
  private _validityPeriodOfOperator: Observable<number> | null = null;
  /**
   * 允许运营商超出有效期时登录
   */
  private _allowLoginBeyondValidity = true;
  /**
   * 获取基础配置
   */
  // public $api_get_config = `/scce/pbc/pbc/baseConfig/getBaseConfigList?_allow_anonymous=true`;
  constructor(public injector: Injector) {
    super(injector);
  }

  // 注入核心服务
  private get coreSrv(): CoreService {
    return this.injector.get(CoreService);
  }

  /**
   * 获取平台状态(参考Http状态码)
   * 200：平台状态正常
   * 401: 未设置平台名称
   * 403
   */
  getPlatformStatus(): number {
    const encryptStatus = this.coreSrv.cacheSrv.getNone<string>(this._cachePlatformStatusKey);
    try {
      // const status = EAEncryptUtil.deencryptByDeAES(encryptStatus);
      return +status;
    } catch (error) {
      return 0;
    }
  }

  /**
   * 获取当前运营商剩余有效期
   * @returns 有效期天数
   */
  getValidityPeriodOfOperator(): Observable<number> {
    return this.loadValidityPeriodOfOperator();
  }

  /**
   * 加载平台状态
   *
   * @returns 平台状态码
   */
  loadPlatformStatus(): Promise<void> {
    return new Promise((resolve) => {
      zip(this.loadIsSetPlatformName(), this.loadValidityPeriodOfOperator())
        .pipe(
          catchError((res) => {
            console.error(`加载平台状态时发生错误:`, res);
            this.msgSrv.error(`加载平台状态时发生错误！`);
            resolve();
            return [];
          }),
        )
        .subscribe(
          ([nameStauts, validityPeriod]) => this.setPlatformStatus(nameStauts, validityPeriod),
          () => {},
          () => resolve(),
        );
    });
  }

  /**
   * 获取平台名称设置状态
   * @param nameStatus 平台名称设置状态
   * @param validityPeriod 运营剩余有效期天数
   */
  setPlatformStatus(nameStatus: boolean, validityPeriod: number) {
    let status = 0;
    // 判断平台名称
    if (status !== 200) {
      status = nameStatus ? 200 : 401;
    }

    // 判断运营商有效期
    if (!this._allowLoginBeyondValidity && status === 200) {
      status = validityPeriod > 0 ? 200 : 402;
    }

    // 加密并保存平台状态
    // const ciphertext = EAEncryptUtil.encryptByEnAES(status.toString());
    // this.coreSrv.cacheSrv.set(this._cachePlatformStatusKey, ciphertext);
  }

  /**
   * 获取平台是否设置平台名称
   * @returns true | false
   */
  private loadIsSetPlatformName(): Observable<boolean> {
    return this.request(this.$api_is_set_platform_name).pipe(switchMap(async (sm) => sm === true));
  }

  /**
   * 获取当前账户绑定的运营商有效期
   * @returns 有效期时间（天）
   */
  private loadValidityPeriodOfOperator(): Observable<number> {
    return this.request(this.$api_get_validity_period_of_operator);
  }

  /**
   * 获取指定平台的地址
   * @param platformName 平台名称
   * @param hasOperationCode 是否需要运营商代码
   */
  getPlatfomrUrl(platformName: string, hasOperationCode = true) {
    const url: string = this.getAllPlatformUrls().find((r: any) => r.name === platformName)?.url || '';
    if (hasOperationCode) {
      return url;
    }

    return url.includes('?') ? url.substring(0, url.indexOf('?')) : url;
  }

  /**
   * 获取所有平台的地址
   */
  getAllPlatformUrls() {
    let platforms: any = [];
    const sc = this.coreSrv.tokenSrv.get()?.sc;
    const protocol = window.location.protocol;
    const hostname = window.location.hostname;
    const port = window.location.port;
    switch (hostname) {
      case 'localhost':
        platforms = [
          {
            name: '运营后台',
            url: `${protocol}//${hostname}:8001/#/?v=${sc}`,
          },
          {
            name: '开放平台',
            url: `${protocol}//localhost:8005/#/?v=${sc}`,
          },
          {
            name: '供应商平台',
            url: `${protocol}//localhost:8004/#/?v=${sc}`,
          },
          {
            name: '分销商平台',
            url: `${protocol}//localhost:8003/#/?v=${sc}`,
          },
          {
            name: '代理商平台',
            url: `${protocol}//localhost:8002/#/?v=${sc}`,
          },
        ];
        break;
      case 'sce-ows-test.380star.com':
        platforms = [
          {
            name: '运营后台',
            url: `${protocol}//${hostname}${port ? ':' + port : ''}/#/?v=${sc}`,
          },
          {
            name: '开放平台',
            url: `${protocol}//sce-opc-test.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
          },
          {
            name: '供应商平台',
            url: `${protocol}//sce-cvc-test.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
          },
          {
            name: '分销商平台',
            url: `${protocol}//sce-cdc-test.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
          },
          {
            name: '代理商平台',
            url: `${protocol}//sce-cac-test.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
          },
        ];
        break;
      case 'sce-ows-pre.380star.com':
        platforms = [
          {
            name: '运营后台',
            url: `${protocol}//${hostname}${port ? ':' + port : ''}/#/?v=${sc}`,
          },
          {
            name: '开放平台',
            url: `${protocol}//sce-opc-pre.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
          },
          {
            name: '供应商平台',
            url: `${protocol}//sce-cvc-pre.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
          },
          {
            name: '分销商平台',
            url: `${protocol}//sce-cdc-pre.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
          },
          {
            name: '代理商平台',
            url: `${protocol}//sce-cac-pre.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
          },
        ];
        break;
      case 'sce-ows-demo.380star.com':
        platforms = [
          {
            name: '运营后台',
            url: `${protocol}//${hostname}${port ? ':' + port : ''}/#/?v=${sc}`,
          },
          {
            name: '开放平台',
            url: `${protocol}//sce-opc-demo.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
          },
          {
            name: '供应商平台',
            url: `${protocol}//sce-cvc-demo.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
          },
          {
            name: '分销商平台',
            url: `${protocol}//sce-cdc-demo.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
          },
          {
            name: '代理商平台',
            url: `${protocol}//sce-cac-demo.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
          },
        ];
        break;
      case 'sce-ows.380star.com':
        platforms = [
          {
            name: '运营后台',
            url: `${protocol}//${hostname}${port ? ':' + port : ''}/#/?v=${sc}`,
          },
          {
            name: '开放平台',
            url: `${protocol}//sce-opc.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
          },
          {
            name: '供应商平台',
            url: `${protocol}//sce-cvc.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
          },
          {
            name: '分销商平台',
            url: `${protocol}//sce-cdc.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
          },
          {
            name: '代理商平台',
            url: `${protocol}//sce-cac.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
          },
        ];
        break;
    }
    return platforms;
  }

  /**
   * 获取运营商代码
   * @returns 运营商代码
   */
  getOperatorCode() {
    return this.coreSrv.tokenSrv.get()?.sc || this.coreSrv.settingSrv.getData('app')?.v || '';
  }

  /**
   * 获取平台配置信息列表
   */
  // getPlatformConfigurationList(): Observable<Array<any>> {
  //   return this.request(this.$api_get_config, {
  //     pageIndex: 1,
  //     pageSize: 999,
  //   });
  // }
}
