import { remove } from 'ionicons/icons';

export class CloudQuery {
  className = '';
  constructor(className: string) {
    this.className = className;
  }
  async getAll() {
    let response = await fetch(
      'http://1.94.237.145:1338/parsecyx/classes/' + this.className,
      {
        headers: {
          accept: '*/*',
          'accept-language':
            'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6,zh-TW;q=0.5,ja;q=0.4',
          'if-none-match': 'W/"f36-Q0ech+Jn3bu0uYx1n7/k1+XDYr0"',
          'x-parse-application-id': 'cyx',
        },
        referrer: 'http://127.0.0.1:4040/',
        referrerPolicy: 'strict-origin-when-cross-origin',
        body: null,
        method: 'GET',
        mode: 'cors',
        credentials: 'omit',
      }
    );

    let json = [];
    if (response) {
      json = await response.json();
    }
    return json || [];
  }

  async getBy(id: string) {
    let response = await fetch(
      'http://1.94.237.145:1338/parsecyx/classes/' + this.className + '/' + id,
      {
        headers: {
          accept: '*/*',
          'accept-language':
            'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6,zh-TW;q=0.5,ja;q=0.4',
          'if-none-match': 'W/"f36-Q0ech+Jn3bu0uYx1n7/k1+XDYr0"',
          'x-parse-application-id': 'cyx',
        },
        referrer: 'http://127.0.0.1:4040/',
        referrerPolicy: 'strict-origin-when-cross-origin',
        body: null,
        method: 'GET',
        mode: 'cors',
        credentials: 'omit',
      }
    );

    let json = {};
    if (response) {
      json = await response.json();
    }

    return json || null;
  }
}

// fetch("http://1.94.237.145:1338/parsecyx/classes/_User?", {
//   headers: {
//     accept: "*/*",
//     "accept-language":
//       "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6,zh-TW;q=0.5,ja;q=0.4",
//     "if-none-match": 'W/"fa-azg+Ndlb0QPHwwjUHnRWOyZVfK8"',
//     "x-parse-application-id": "cyx",
//     "x-parse-session-token": "r:59067722e551c61a2146dc890bc4a888",
//   },
//   referrer: "http://127.0.0.1:4040/",
//   referrerPolicy: "strict-origin-when-cross-origin",
//   body: null,
//   method: "GET",
//   mode: "cors",
//   credentials: "omit",
// });

// user操作
export class CloudUser {
  constructor() {}

  objectId: string = '';
  sessionToken: string = '';
  data: any = {};

  // 获取当前用户信息
  async current() {
    let userCache = localStorage.getItem('userData');
    if (userCache) {
      let userData = JSON.parse(userCache);
      this.objectId = userData.objectId;
      this.sessionToken = userData.sessionToken;
    }
  }

  // 用户登录
  async login(username: string, password: string): Promise<CloudUser | null> {
    let url = `http://1.94.237.145:1338/parsecyx/login`;
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'X-Parse-Application-Id': 'cyx',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ username, password }),
    });

    const result = await response?.json();
    if (result?.error) {
      console.error(result?.error);
      return null;
    }

    this.objectId = result.objectId;
    this.sessionToken = result.sessionToken;
    this.data = result;
    return this;
  }

  // 用户登出
  async logout(): Promise<boolean> {
    let url = 'http://1.94.237.145:1338/parsecyx/logout';
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'X-Parse-Application-Id': 'cyx',
        'X-Parse-Session-Token': this.sessionToken,
      },
    });

    this.objectId = '';
    this.sessionToken = '';
    this.data = {};
    return true;
  }

  // 用户注册
  async register(username: string, password: string) {
    let url = 'http://1.94.237.145:1338/parsecyx/users';
    let response = await fetch(url, {
      method: 'POST',
      headers: {
        'X-Parse-Application-Id': 'cyx',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ username, password }),
    });
    const result = await response?.json();
    this.objectId = result.objectId;
    this.sessionToken = result.sessionToken;
    this.data = result;
    return this;
  }

  // 修改用户信息
  async update(userChangeInfo: any) {
    console.log(userChangeInfo);

    this.current();
    let url =
      `http://1.94.237.145:1338/parsecyx/classes/_User/` + this.objectId;
    let response = await fetch(url, {
      method: 'PUT',
      headers: {
        'X-Parse-Application-Id': 'cyx',
        'X-Parse-Session-Token': this.sessionToken,
        'Content-Type': 'application/json;charset=UTF-8',
      },
      body: JSON.stringify(userChangeInfo),
      mode: 'cors',
      credentials: 'omit',
    });
    console.log('update: ', this);

    return this;
  }
}

// fetch('http://1.94.237.145:1338/parsecyx/classes/_User/WBhghn8NuZ', {
//   headers: {
//     accept: '*/*',
//     'accept-language':
//       'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6,zh-TW;q=0.5,ja;q=0.4',
//     'content-type': 'text/plain',
//   },
//   referrer: 'http://127.0.0.1:4040/',
//   referrerPolicy: 'strict-origin-when-cross-origin',
//   body: '{"phoneNumber":"12345","_method":"PUT","_ApplicationId":"cyx","_ClientVersion":"js3.4.2","_MasterKey":"cyxmk","_InstallationId":"111053ea-8bfc-4dfc-8818-df34dd45d6b0"}',
//   method: 'POST',
//   mode: 'cors',
//   credentials: 'omit',
// });
// module.exports.Query = Query;
// module.exports.CloudUser = CloudUser;
