import "./promise.finally";
import fly from "./fly";
import qs from "qs";
import { hex_md5 } from "./md5";
import storage from "@system.storage";
import device from "@system.device";
import request from "@system.request";
import media from "@system.media";
import prompt from "@system.prompt";
import { userOptions } from "./index"
import apiConfig from "./config";
// 获取token
let token = null;
let requestLoginTime = 0;

export const getToken = async () => {
  if (getToken.promise) return getToken.promise;
  if (!token) token = (await storage.get({ key: "token" })).data;
  // token格式化
  if (token && typeof token === "string") token = JSON.parse(token);
  console.log("checkToken", checkToken(token));
  if (!token) getToken.promise = login();
  else if (checkToken(token)) return Promise.resolve(token.token);
  else {
    getToken.promise = login();
  }
  getToken.promise = getToken.promise
    .finally(() => {
      getToken.promise = null;
    })
    .then(r => {
      console.log("refresh");
      return setToken(r);
    });

  return getToken.promise;
};


// 登录
export const login = async () => {
  requestLoginTime++;
  if (requestLoginTime != 1) {
    let loginResponed = await loginPromise();
  }
  const signKey = "a!A&AFRWT65Nb3NlklezUiqHyQAA@Z8M";
  const packages = apiConfig.package;
  let device_info = (await device.getInfo()).data;
  let androidid = (await device.getUserId()).data;
  let send_order_id = (await storage.get({ key: "send_order_id" })).data;
  let timestamp = parseInt(new Date().valueOf() / 1000);
  let oaId = (await device.getOAID()).data
  if (oaId) {
    device_info['__oaid'] = oaId.oaid
  } else {
    device_info['__oaid'] = ''
  }
  let word='abcdefg'
  let queryString = "";
  if (send_order_id) queryString = `androidid=${androidid.userId || word }&device_no=${androidid.userId || word}&package=${packages}&send_order_id=${send_order_id}&timestamp=${timestamp}&key=${signKey}`;
  else queryString = `androidid=${androidid.userId || word}&device_no=${androidid.userId || word}&package=${packages}&timestamp=${timestamp}&key=${signKey}`;
  let data = qs.stringify({
    androidid: androidid.userId|| word,
    device_info: JSON.stringify(device_info)|| word,
    device_no: androidid.userId|| word,
    package: packages,
    send_order_id: send_order_id, 
    timestamp: timestamp,
    sign: hex_md5(queryString),
  });
  let ret = await fly.post("/login", data);
  requestLoginTime = 0;
  return ret;
};

const loginPromise = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(true)
    }, 800)
  })
}


// 检测数据结果
export const checkResult = r => {
  if (!r.data.code) {
    return r.data.data;
  } else {
    return Promise.reject(r);
  }
};

// 刷新token
const refreshToken = () => {
  return fly
    .get("/refreshToken", {
      token: token.token
    }, {
      headers: {
        Authorization: token.token
      }
    })
    .then(r => {
      return r;
    })
    .catch(e => {
      console.log(e);
      console.error("刷新token失败");
      return Promise.reject(e);
    });
};

// 检查token的有效期
const checkToken = t => {
  console.log("current timestamp: ", new Date().getTime());
  console.log("token timestamp: ", t.time);
  console.log("check time:", new Date().getTime() < t.time)
  return new Date().getTime() < t.time;
};

// 设置token
const setToken = async t => {
  token = formatToken(t);
  await storage.set({ key: "token", value: token });
  return t.token;
};

// 清除token
export const clearToken = async () => {
  token = null;
  await storage.delete({ key: "token" });
  console.log("clear token done");
};

// 处理token的格式
const formatToken = t => {
  t.token = "Bearer " + t.token;
  t.time = t.time * 1000;
  return t;
};

// 下载图片
export const downImg = photoPath => {
  //获取图片名
  let list = photoPath.split(".");
  let timeValue = new Date().valueOf();
  /* 获取图片后缀 */
  let photoExt = list[list.length - 1];
  /* 设置要保存的图片名 */
  let filename = `${timeValue}.${photoExt}`;
  request.download({
    url: photoPath,
    filename: filename,
    success: data => {
      request.onDownloadComplete({
        token: data.token,
        success: data => {
          /* 保存图片 */
          media.saveToPhotosAlbum({
            uri: data.uri,
            success: () => {
              prompt.showToast({
                message: "图片保存成功！"
              });
            },
            fail: (data, code) => {
              if (code == 201) {
                prompt.showToast({
                  message: "授权成功后才能保存图片哦"
                });
              } else if (code == 202) {
                prompt.showToast({
                  message: "请刷新后重试"
                });
              } else if (code == 300) {
                prompt.showToast({
                  message: "图片保存失败"
                });
              }
            }
          });
        },
        fail: (data, code) => {
          if (code == 1000) {
            prompt.showToast({
              message: "图片下载失败"
            });
          } else if (code == 1001) {
            prompt.showToast({
              message: "下载任务不存在"
            });
          }
        }
      });
    },
    fail: () => { }
  });
};

//存储期限storge
export const setStore = (key, value) => {
  if (!key) return;
  let curTime = new Date().getTime();
  value = JSON.stringify({ data: value, time: curTime });
  storage.set({ key: key, value: value });
};

//取期限storge expDay:storge 几天内有效
export const getStore = async (key, expDay = 3) => {
  if (!key) return false;
  let storgeData = JSON.parse((await storage.get({ key: key })).data);
  if (isExceedDay(storgeData.time, expDay)) {
    return false;
  } else {
    return storgeData.data;
  }
};

function isExceedDay(theDate, expDay) {
  let date = new Date();
  let targetTime =
    new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() -
    (expDay - 1) * 24 * 3600 * 1000;
  return theDate < targetTime;
}

export const getSendOrderId = (fn) => {
  storage.get({
    key: 'send_order_id',
    success: data => {
      fn && fn(data);
    },
    fail: (data, code) => {
      console.log(`handling fail, code = ${code}`)
    }
  })
}

//获取全局配置
export const getAppConfig = (self) => {
  return async (key) => {
    let option = self.$app.getAppData('options');
    if (!option) {
      let data = await userOptions();
      self.$app.setAppData('options', data);
      return self.$app.getAppData('options')[key];
    } else {
      return option[key];
    }
  }
}

