import {Injectable} from '@angular/core';
import {HttpErrorResponse} from '@angular/common/http';
import {of} from 'rxjs';
import {ToastService} from 'ng-zorro-antd-mobile';
import axios from 'axios';

interface IRequest {
  data?: any;
  success?: Function;
  fail?: Function;
  toast?: boolean;
}

@Injectable({
  providedIn: 'root'
})
export class HttpService {
  baseUrl = 'https://www.chtax.cn';

  constructor(
    private toast: ToastService,
  ) {
  }

  post(url: string, {data, success, fail, toast = true}: IRequest) {
    axios({
      url: url,
      method: 'post',
      data: data,
      // baseURL: this.baseUrl,
    }).then(res => {
      const data = res.data;
      if (data.code == 0) {
        success && success(data.data, data.msg);
      } else {
        if (toast) {
          this.toast.hide();
          this.toast.show(data.msg);
        }
        fail && fail(data.data);
      }
    }).catch(err => {
      console.log(err);
    });
  }

  get(url: string, {data, success, fail, toast = true}: IRequest) {
    axios({
      url: url,
      method: 'get',
      params: data,
      // baseURL: this.baseUrl,
    }).then(res => {
      const data = res.data;
      if (data.code == 0) {
        success && success(data.data, data.msg);
      } else {
        if (toast) {
          this.toast.hide();
          this.toast.show(data.msg);
        }
        fail && fail(data.data);
      }
    }).catch(err => {
      console.log(err);
    });
  }

  handleError = (error: HttpErrorResponse) => {
    if (error.status === 401) {
    }

    return of({code: null, msg: error.error, data: null});
  };

  apis = {
    smsCode: '/api/sms/getSmscode', // 获取验证码
    register: '/api/marketing/participant/register', // 注册
    login: '/api/marketing/participant/login', // 登陆
    findPageByParticipant: '/api/marketing/recommended/findPageByParticipant', // 推荐人-分页查询活动推荐申请数据列表
    productPage: '/api/marketing/prize/product/findPage', // 分页查询活动奖品
    recommendedSave: '/api/marketing/recommended/save', // 推荐申请信息保存
    applyReward: '/api/marketing/prize/apply/save', // 申领奖品
    findPageByOper: '/api/marketing/prize/apply/findPageByOper', // 运营商-分页查询活动推荐申请数据列表
  };
}
