import { boot } from "quasar/wrappers";
import axios from "axios";
import { Notify, LocalStorage, openURL, Dialog, Platform } from "quasar";

import {compareVersions} from 'compare-versions'
import { useSelfStore } from "stores/self";

// Be careful when using SSR for cross-request state pollution
// due to creating a Singleton instance here;
// If any client changes this (global) instance, it might be a
// good idea to move this instance creation inside of the
// "export default () => {}" function below (which runs individually
// for each client)
const service = axios.create({
  headers: {
    "Content-Type": "application/json"
    // "Content-Type": "application/x-www-form-urlencoded"
    // 'Access-Control-Allow-Origin': '*'
  },
  timeout: 30000,
  baseURL: process.env.BASE_URL+"api/",

  transformRequest: [function (data, headers) {
    // 对 data 进行任意转换处理
    return JSON.stringify(data);
  }],
});
service.interceptors.response.use(
  function (response) {
    if (response.data && response.data.code == 200) {
      return response.data.data;
    }
    console.warn("******"+response.data?.message+response.data?.code+"******")
    // const err = new Error();
    // err.code = response.data.code;
    return Promise.reject({
      message: response.data?.message,
      code: response.data?.code
    });
  },
  (error) => {
    let retErr = {
      message: error.message
    }
    console.warn("请求异常：", error.message);
    if (axios.isCancel(error)) {
      console.warn("Request canceled", error.request?.url, error.message);
      retErr.message = "请求已取消"
      return Promise.reject(retErr);
    } else {
      let data = error.response?.data;
      // error.response?.statusCode
      retErr.code = data?.code ?? (error.code||-1);
      if (data && data.message) {
        retErr.message = data.message;
      } else {
        retErr.message = "网络连接失败，请稍后重试";
      }
      return Promise.reject(retErr);
    }
  }
);

const api = {
  domain: process.env.BASE_URL == '/'? (window.location.origin+'/') : process.env.BASE_URL,
  checkUpdate(){
    if (!Platform.is.cordova) {
      return Promise.reject(new Error('未发现新版本'))
    }
    const version = window.AppVersion?.version??'0.0.1'
    return service.get('seller/app/version_info').then(res => {
      console.log("[更新检测]远端版本：",res.version,"；本地版本："+version,compareVersions(res.version, version))
      if (res && compareVersions(res.version, version) > 0) {
        return res
      } else {
        return Promise.reject(new Error('未发现新版本'))
      }
    })
  },
  login(account) {
    return service({
      method: "post",
      url: "seller/login",
      data: account
    }).then((data) => {
      LocalStorage.set('account',account)
      updateAuthToken(data.token_type+' '+data.access_token);
      return this.getLoginUser();
    });
  },
  logout() {
    const p = service.post("seller/logout");
    updateAuthToken();
    LocalStorage.remove('account')
    return p;
  },
  refreshToken(){
    const account = LocalStorage.getItem("account")
    if(account && account.phone && account.password) {
      return this.login(account)
    }
    return service.post("seller/refresh_token").then(data => {
      updateAuthToken(data.token_type+' '+data.access_token);
      return this.getLoginUser();
    })
  },
  getQrcodeUrl(url,size=80){
    return service.defaults.baseURL+'customer/qrcode?content='+encodeURIComponent(url)+'&size='+size
  },
  getCityTree(){
    return service.get('seller/area/tree')
  },
  // 获取当前登录用户个人信息
  getLoginUser(){
    return service.get('seller/seller/info',{params: {v:process.env.WEB_VERSION}})
  },
  updateShopInfo(data){
    return service.post('seller/shop/setting',data)
  },
  // 订单查询
  searchOrder(data){
    return service.get('seller/order/search',{params:data})
  },
  // 订单查询搜索条件
  getOrderFilterOptions(data){
    return service.get('seller/order/search_filter',{params:data})
  },
  // 订单管理
  getOrderList(data){
    return service.get('seller/order/list',{params:data})
  },
  getOrderInfo(data){
    return service.get('seller/order/show',{params:data})
  },
  receiveOrder(data){
    return service.post('seller/order/receive',data)
  },
  revokeOrder(data){
    return service.post('seller/order/revoke',data)
  },
  takeOrderTicket(data){
    return service.post('seller/order/take_ticket',data)
  },
  drawOrder(data){
    return service.post('seller/order/draw',data)
  },
  updateOrderTickets(data){
    return service.post('/seller/order/upload_piao',data)
  },
  // 甩单
  throwCooperate(data){
    return service.post('seller/order/throw_cooperate',data)
  },
  getOrderTickets(data){
    return service.get('seller/order/piao_show',{params:data})
  },
  getCustomerList(data){
    return service.get('seller/customer/list',{params:data})
  },
  getCustomerInfo(data){
    return service.get('seller/customer/show',{params:data})
  },
  // 用户提现列表
  getCustomerWithdrawList(data){
    return service.get('seller/customer/withdraw_list',{params:data})
  },
  getCustomerWithdrawInfo(data){
    return service.get('seller/customer/withdraw_show',{params:data})
  },
  auditCustomerWithdraw(data){
    return service.post('seller/customer/withdraw_audit',data)
  },
  getCustomerBillList(data){
    return service.get('seller/customer/bills',{params:data})
  },
  // FIXME 投注记录需要一个接口
  getCustomerOrders(data){
    return service.get('seller/customer/bets_record',{params:data})
  },
  // 修改用户信息
  updateCustomerInfo(data){
    return service.post('seller/customer/update',data)
  },
  // 重置彩民密码
  resetPassword(data){
    return service.post('seller/customer/reset_password',data)
  },
  // 重置彩民支付密码
  resetPayPassword(data){
    return service.post('seller/customer/reset_pay_password',data)
  },
  // 加款\扣款
  changeBalance(type,data){
    if(type == 'recharge'){
      return service.post('seller/customer/recharge',data)
    }
    return service.post('seller/customer/balance_'+type,data)
  },
  // 钱包相关
  // 支付-充值(获取充值单号)
  recharge(data){
    return service.post('seller/wallet/recharge',data)
  },
  // 支付-跳转到第三方支付
  redirectPay(url){
    return new Promise((resolve,reject)=>{
      setTimeout(()=>{
        openURL(url,reject)
        Dialog.create({
          title: '支付确认',
          message: '是否已经完成支付？',
          cancel: '未支付',
          ok:'已支付',
          persistent: true
        }).onDismiss(()=>{
        // 暂时不需要刷新支付状态。
        })
        resolve()
      },200)
      // return openURL(service.defaults.baseURL+'seller/wallet/redirect_pay?recharge_sn='+data.recharge_sn)
    })
    // return service.post('seller/wallet/redirect_pay',data)
  },
  // 发起提现
  withdrawMoney(data){
    return service.post('seller/wallet/withdraw_money',data)
  },
  // 我的提现记录
  getMyWithdrawList(data){
    return service.get('seller/wallet/withdraw_list',{params:data})
  },
  // 支付- 支付方式
  getPayTypes(){
    return service.get('seller/wallet/pay_types')
  },
  // 我的相关
  // 忘记密码
  resetMyPassword(data){
    return service.post('seller/seller/reset_password',data)
  },
  changePassword(data){
    return service.post('seller/seller/change_password',data)
  },
  changePayPassword(data){
    return service.post('seller/seller/change_pay_password',data)
  },
  // changeNickname(data){
  //   return service.post('seller/seller/change_nickname',data)
  // },
  // 实名认证
  realVerify(data){
    return service.post('seller/seller/real_verify',data)
  },
  //  店铺余额-账户明细/充值记录
  walletBills(data){
    return service.get('seller/wallet/bills',{params:data})
  },
  // 获取某一彩种配置信息参数{id:''}
  getLotteryConfig(data){
    return service.get('seller/lottery/config',{params:data})
  },
  updateLotteryConfig(data){
    return service.post('seller/lottery/config',data)
  },
  getLotterysType(){
    return service.get('seller/lottery/config_list')
  },
  // 员工管理
  getWorkerList(){
    return service.get('seller/seller/list')
  },
  addWorker(data){
    return service.post('seller/seller/store',data)
  },
  deleteWorker(data){
    return service.post('seller/seller/delete',data)
  },
  updateWorker(data){
    return service.post('seller/seller/update',data)
  },
  // 统计
  getDashboardInfo(data){
    return service.get('seller/report/dashboard',{params:data})
  },
  getAgentReport(data){
    return service.get('seller/report/agent',{params:data})
  },
  getAgentReportInfo(type,data){
    return service.get('seller/report/agent_'+type,{params:data})
  },
  feedback(data){
    return service.post('seller/seller/feedback',data)
  },
  // 派奖
  getWinOrderList(data){
    return service.get('seller/order/win_list',{params:data})
  },
  getSendPrizeList(data){
    return service.get('seller/order/send_list',{params:data})
  },
  sendPrize(data){
    return service.post('seller/order/send_prize',data)
  },
  // 收款管理
  getPayChannels(){
    return service.get('seller/shop/pay_channel_list')
  },
  setPayChannel(data){
    return service.post('seller/shop/pay_channel',data)
  },
  getPayChannel(data){
    return service.get('seller/shop/pay_channel',{params:data})
  },
  uploadPayChannel(data){
    return service.post('seller/shop/pay_channel_update',data)
  },
  // 合作申请
  getPartnerList({type,...data}={}){
    return service.get(type==='entrusted'?'seller/cooperate/entrusted_list':'seller/cooperate/entrust_list',{params:data})
  },
  addPartner(data){
    return service.post('seller/cooperate/apply',data)
  },
  // deletePartner(data){
  //   return service.post('seller/cooperate/delete',data)
  // },
  // updatePartner(data){
  //   return service.post('seller/cooperate/update',data)
  // },
  getPartnerInfo({type,...data}={}){
    return service.get('seller/cooperate/'+type+'_lottery_list',{params:data})
  },
  // 审核申请合作
  auditPartner(data){
    return service.post('seller/cooperate/audit',data)
  },
  // 扣款
  deductPartnerMoney(data){
    return service.post('seller/cooperate/balance_reduce',data)
  },
  // 加款
  addPartnerMoney(data){
    return service.post('seller/cooperate/balance_incr',data)
  },
  // 合作余额明细
  getPartnerWallet(data){
    return service.get('seller/cooperate/bills',{params:data})
  },
  // 合作彩种
  getPartnerLotteries(data){
    return service.get('seller/cooperate/lotteries',{params:data})
  },
  addPartnerLottery(data){
    return service.post('seller/cooperate/lottery_apply',data)
  },
  auditPartnerLottery(data){
    return service.post('seller/cooperate/lottery_audit',data)
  },
  updatePartnerLottery(data){
    return service.post('seller/cooperate/lottery_update',data)
  },
  unbindPartnerLottery(data){
    return service.post('seller/cooperate/lottery_unbind',data)
  },
  applyShopCertify(data){
    return service.post('seller/shop/certify_apply',data)
  },
  getShopCertify(){
    return service.get('seller/shop/certify_get')
  },
  getLotteryReport(type,data){
    return service.get('seller/report/'+type,{params:data})
  },
  getReportOrders(data){
    return service.get('/seller/report/order_list',{params:data})
  },
  getAppUpgrade(){
    return service.get('/app/upgrade').then(res=>{
      if(!res.upgrade || !res.content || res.id == LocalStorage.getItem('upgradeId')){
        return Promise.reject(false)
      }
      LocalStorage.set('upgradeId',res.id)
      return res
    })
  },
  updateMyInfo(data){
    return service.post('seller/seller/change_info',data)
  },
  getReportInfo(type,data){
    // report/customer_bills
    // report/customer_recharge
    // report/shop_bills
    // report/shop_coop_bills
    // report/registers
    // report/buyers
    return service.get(`seller/report/${type}`,{params: data})
  },
  getAgentShops(data){
    return service.get('seller/agent/shop_flow',{params:data})
  },
  test(data){
    return service.post('seller/test',data)
  }
};

function updateAuthToken(token) {
  if (!token) {
    LocalStorage.remove("token");
    service.defaults.headers.common["Authorization"] = "";
    return;
  }
  LocalStorage.set("token", token);
  service.defaults.headers.common["Authorization"] = token;
}

export default boot(({ app, router, store, urlPath, redirect }) => {
  // for use inside Vue files (Options API) through this.$axios and this.$api
  app.config.globalProperties.$axios = axios;
  app.config.globalProperties.$api = api;

  const selfStore = useSelfStore();

  let dismiss;
  // 添加响应拦截器
  service.interceptors.response.use(null, (err) => {
    if (err.code === 401) {
      // 登录超时,返回登录页面
      updateAuthToken();
      if (!dismiss) {
        dismiss = Notify.create({
          type: "negative",
          position: "center",
          message: '登录超时，请重新登录',
          onDismiss() {
            dismiss = null;
          }
        });
      }
      selfStore.clear()
      router.replace("/login");
    }
    return Promise.reject(err);
  });

  api.getAppUpgrade().then(res=>{
    Dialog.create({
      title: res.title||'系统提示',
      message: res.content,
    })
  })

  let refreshTimer = null
  function clearRefreshTimer() {
    if(refreshTimer) {
      clearTimeout(refreshTimer)
      refreshTimer = null
    }
  }
  router.onError(()=>{
    if(refreshTimer){
      return;
    }
    refreshTimer = setTimeout(()=>{
      clearRefreshTimer()
      window.location.reload();
    },2000)
    Notify.create({
      position: "top",
      progress: true,
      message: '加载失败，2s后自动重试',
      timeout: 2000,
      color: 'primary',
      // avatar: '/icons/favicon-32x32.png',
      actions: [
        { label: '取消', color: 'white', handler: clearRefreshTimer }
      ]
    })
  })

  // if (process.env.NODE_ENV !== "production") return;
  router.beforeEach((to, from, next) => {
    if (to.meta.Authorization && !selfStore.isLogin) {
      if (to.path !== "/login") {
        return next("/login");
      }
    }
    (!selfStore.shop?.shop_extra || selfStore.shop?.shop_extra.state==2) && to.name=='home' && Dialog.create({
      title: '系统提醒',
      message: selfStore.shop?.shop_extra?'店铺认证审核失败，请修改认证资料～':'店铺未认证，请先提交资料认证～',
      ok:'去认证',
      cancel:true,
      // persistent: true,
      // noBackdropDismiss:true,
      noRouteDismiss: true
    }).onOk(()=>{
      router.push("/shop/auth")
    })
    if (selfStore.isLogin && to.path === "/login") {
      return next("/");
    }
    next();
  });
  const isAuthorized = LocalStorage.getItem("token") || "";
  console.log("========="+urlPath+"========")
  if (urlPath.match(/(\#)?\/login/)) {
    return;
  } else if (!isAuthorized) {
    redirect({ path: "/login" });
    return;
  } else if(urlPath==='/#/'||urlPath.indexOf("#")==-1){
    redirect({ path: "/home" });
    return
  }
  updateAuthToken(isAuthorized);
  return api.refreshToken().then((res)=>{
    selfStore.setInfo(res);
  })
  .catch((e) => {
    redirect({ path: "/login" });
  });
});

export { api, service };
