import {Injectable} from '@angular/core';
import {LocalStorageService} from './local-storage.service';
import {ADMIN_INFO_OBJECT, DATA} from './local-storage.namespace';
import {NzModalService, NzNotificationService} from 'ng-zorro-antd';
import {environment} from '../../environments/environment';
import {HttpClient} from '@angular/common/http';

@Injectable({
    providedIn: 'root'
})
export class CommonsService {

    constructor(
        private storage: LocalStorageService,
        private modalService: NzModalService, // 对话框
        private http: HttpClient,
        private notification: NzNotificationService
    ) {
    }

    /**
     * 将对象转换成GET请求参数  key1=value1&key2=value2
     * @param object 传入对象
     */
    getWhereCondition(object: object): string {
        let str = '';
        for (const i in object) {
            if (object[i] != null && object[i] !== '') {
                if (str === '') {
                    str = i + '=' + object[i];
                } else {
                    str += '&' + i + '=' + object[i];
                }
            }
        }
        return str;
    }

    /**
     * 校验当前用户是否拥有按钮权限
     * @param btnCode 按钮名称
     */
    public isBtnCompetence(btnCode: string): boolean {
        let buttonList = [];
        buttonList = this.storage.get(ADMIN_INFO_OBJECT).buttonList;
        if (buttonList != null && buttonList.length > 0) {
            if (buttonList.find(b => b.permissionCode === btnCode) != null) {
                return true;
            }
        }
        return false;
    }


  /**
   * 提示框提示
   * @param  message   传入文字
   * @param  callback   回调
   */
  public showConfirm(message , callback) {
    this.modalService.confirm({
      nzTitle: message,
      nzOkText: '是',
      nzOkType: 'danger',
      nzOnOk: () => callback(true),
      nzCancelText: '否',
    });
  }

  /**
   * 根据estateId 查询类目树
   *
   * @param  estateId   类目id
   * @param  callBack   回调
   */
  public getMallCategoryTree(estateId: number ,  callBack) {
    this.http.get(environment.baseUrl + 'categoryEstates/getMallCategoryTree?estateId=' + estateId).subscribe(data => {
      callBack(data);
    });
  }

  /**
   * 获取全部区域
   * @param  callBack   回调
   */
  public getParentInfosByRegionId(regionId: number, callBack) {
      this.http.get(environment.baseUrl + 'common/getParentInfosByRegionId?regionId=' + regionId).subscribe(data => {
          callBack(data);
      });
  }

  /**
   * 获取全部区域
   * @param  callBack   回调
   */
  public getAllRegion(callBack) {
    this.http.get(environment.baseUrl + 'common/getAllProvinceAndCity').subscribe(data => {
      callBack(data);
    });
  }

  /**
   * 获取所有 省 市 区
   * @param  callBack   回调
   */
  public getAllProvinceAndCityRegion(callBack) {
    this.http.get(environment.baseUrl + 'common/getAllProvinceAndCityRegion').subscribe(data => {
      callBack(data);
    });
  }

  /**
   * 获取行业分类
   * @param  callBack   回调
   */
  public getAllIndustry(callBack) {
    this.http.get(environment.baseUrl + 'secCompanyIndustry/findIndustryTree').subscribe(data => {
      callBack(data);
    });
  }

  /**
   * 查询省级列表
   * @param  callBack   回调
   */
  public getProvinceList(callBack) {
    this.http.get(environment.baseUrl + 'common/getProvinceList').subscribe(data => {
      callBack(data);
    });
  }

  /**
   * 查询省级列表
   * @param  callBack   回调
   */
  public getGasSelectList(callBack) {
    this.http.get(environment.baseUrl + 'highGas/getGasSelectList').subscribe(data => {
      callBack(data);
    });
  }


  /**
   * 根据数组对象去重
   *
   * @param  object   对象
   */
  public getUniqueObject<T>(object: any): any {
    const map = {};
    // 1、把数组元素作为对象的键存起来（这样就算有重复的元素，也会相互替换掉）
    object.forEach(item => map[JSON.stringify(item)] = item);

    // 2、再把对象的值抽成一个数组返回即为不重复的集合
    return Object.keys(map).map(key => map[key]) as T[];
  }

  /**
   * 根据String 非空判断
   *
   * @param  name   String
   */
  public getStringIsNull<T>(name: string): boolean {
      if (name == null) {
        return  true;
      }
      if (name === '') {
        return true;
      }
  }

  /**
   * 校验手机号码
   *
   * @param  phone   String
   */
  public verifyPhone<T>(phone: string): boolean {
    return phone.length === 11;
  }

  /**
   * 根据数据类型查询数据字典
   *
   * @param  codeType 页码
   * @param  callback 回调
   */
  public getRedisValueByType(key: string , callback): any {
      this.http.get(environment.baseUrl + '/common/getRedisValueByType?key=' + key).subscribe( data => {
          callback(data);
      });
  }

    /**
     * 根据数据类型查询数据字典
     *
     * @param  codeType 页码
     * @param  callback 回调
     */
    public getDictionary(codeType: string , callback): any {
        this.http.get(environment.baseUrl + '/common/getDictionaryByCodeType?codeType=' + codeType).subscribe( data => {
            callback(data);
        });
    }

  public mappingSysNameOl(codeType: string , callback): any {
    this.http.get(environment.baseUrl + '/common/getDictionaryByCodeTypeOl?codeType=' + codeType).subscribe( data => {
      callback(data);
    });
  }

  public updateDictionary(codeType: string , codeValue: string , callback): any {
    this.http.get(environment.baseUrl + '/common/updateDictionary?codeType=' + codeType + '&codeValue=' + codeValue).subscribe( data => {
      callback(data);
    });
  }

    public editConfig(param: object, callback): any {
        this.http.post(environment.baseUrl + '/common/editConfig', param).subscribe( data => {
            callback(data);
        });
    }

  /**
   *
   * 获取全部职位类型
   *
   * @param  callback
   */
  getAllJobType(callback) {
    this.http.get('assets/json/jobType.json').subscribe( data => {
      callback(data);
    });
  }

    /**
     * 时间戳转化为年 月 日 时 分 秒
     * timestamp: 时间戳
     * format：返回格式，支持自定义，但参数必须与formatArr里保持一致
     */
    public formatTime(timestamp: number, format: string) {

        const formatArr = ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss'];
        const returnArr = [];
        const date = new Date(timestamp);

        returnArr.push(date.getFullYear());
        returnArr.push(this.formatNumber(date.getMonth() + 1));
        returnArr.push(this.formatNumber(date.getDate()));

        returnArr.push(this.formatNumber(date.getHours()));
        returnArr.push(this.formatNumber(date.getMinutes()));
        returnArr.push(this.formatNumber(date.getSeconds()));

        // tslint:disable-next-line:forin
        for (const i in returnArr) {
            format = format.replace(formatArr[i], returnArr[i]);
        }
        return format;
    }

    // 数据转化
    formatNumber(n) {
        n = n.toString();
        return n[1] ? n : '0' + n;
    }

    /**
     * Notification通知提醒框
     *
     * @param  type 页码
     * @param  title 标题
     * @param  content 内容
     */
    public createNotification(type: string, title: string, content: string): void {
        this.notification.create(
            type,
            title,
            content
        );
    }

    /**
     * 职位列表key查询value
     *
     * @param  value string
     * @param  object object
     * @param  callback 回调
     */
    public positionKeyValue<T>(value: string, object: Array<any>, callback): void {
        // tslint:disable-next-line:forin
        for (const i in object) {
            if (object[i].value === value) {
                callback(object[i].label);
            } else {
                this.positionKeyValue(value, object[i].children, callback);
            }
        }
    }

    /**
     * 根据数据类型查询数据字典
     *
     * @param  codeType 类型
     * @param  codeValue value
     * @param  callback 回调
     */
    public getDictionaryByCodeTypeAndValue(codeType: string, codeValue: string, callback): any {
        this.http.get(environment.baseUrl + '/common/getDictionaryByCodeTypeAndValue?codeType=' + codeType + '&codeValue=' + codeValue).subscribe(data => {
            callback(data);
        });
    }

    /**
     * 根据数据类型查询数据字典 同步请求
     *
     * @param  codeType 类型
     * @param  codeValue value
     * @param  callback 回调
     */
    public getDictionaryByCodeTypeAndValuePromise(codeType: string, codeValue: string): any {
        return new Promise(resolve => {
            this.http.get(environment.baseUrl + '/common/getDictionaryByCodeTypeAndValue?codeType=' + codeType + '&codeValue=' + codeValue).subscribe(data => {
                resolve(data['return_data']['codeName']);
            });
        });
    }

    /**
     * 查询登录页展示的公司
     * @param param 参数
     * @param callback 回调
     */
    public getHomeCompanyList(param: object, callback): any {
        this.http.get(environment.baseUrl + 'common/getHomeCompanyList?' + this.getWhereCondition(param)).subscribe(data => {
            callback(data);
        });
    }

    /**
     * 新增团油油品配置
     *
     * @param params 上传对象
     * @param  callBack   回调
     * @return data 返回结果
     */
    public editGasDiscountOilPrice(params: object, callBack) {
        this.http.post(environment.baseUrl + 'highGasDiscountOilPrice/editGasDiscountOilPrice', params).subscribe(data => {
            callBack(data);
        });
    }

    /**
     * 查询公司列表
     *
     * @param  paramsObject   对象
     * @param  callBack   回调
     */
    public getList(paramsObject: object, callBack) {
        this.http.get(environment.baseUrl + 'highGasDiscountOilPrice/getList?' + this.getWhereCondition(paramsObject)).subscribe(data => {
            callBack(data);
        });
    }

    /**
     * 根据estateId 查询类目树
     *
     * @param  id   类目id
     * @param  callBack   回调
     */
    public getDetailById(id: number, callBack) {
        this.http.get(environment.baseUrl + 'highGasDiscountOilPrice/getDetailById?id=' + id).subscribe(data => {
            callBack(data);
        });
    }

    /**
     * 根据estateId 查询类目树
     *
     * @param  id   类目id
     * @param  callBack   回调
     */
    public delete(id: number, callBack) {
        this.http.post(environment.baseUrl + 'highGasDiscountOilPrice/delete', {id: id}).subscribe(data => {
            callBack(data);
        });
    }

    /**
     * 查询公司
     * @param param 参数
     * @param callback 回调
     */
    public getOrganizationList(param: object, callback): any {
        this.http.get(environment.baseUrl + 'bsOrganization/getOrganizationList?' + this.getWhereCondition(param)).subscribe(data => {
            callback(data);
        });
    }

    /**
     * 查询所有数据字典
     * @param param 参数
     * @param callback 回调
     */
    public getDictionaries(callback): any {
        this.http.get(environment.baseUrl + 'bsOrganization/getOrganizationList').subscribe(data => {
            callback(data);
        });
    }

    /**
     * 发送充值短信验证码
     *
     * @param  phone  手机号
     * @param  merchantId  手机号
     * @param  price  手机号
     * @param  callBack   回调
     */
    public sendRechargeSmsCode(phone: string, merchantId: number, price: string, callBack) {
        this.http.get(environment.baseUrl + 'sendSms/sendRechargeSmsCodeByMchId?phone=' + phone + '&merchantId=' + merchantId + '&price=' + price).subscribe(data => {
            callBack(data);
        });
    }

}
