/*
 * @Author: ZhengXiaowei
 * @Date: 2019-07-24 17:21:47
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-06-28 15:51:55
 * @Description: file content
 */
import Axios from "axios";
import axios from "./axios";
import {
  bookListFormat,
  bookFormat,
  urlFormat,
  contentFormat,
  recordFormat,
  shelfFormat
} from "./util";
import cache from "../util/cache.js";
import { Subscribe, Pay } from "../view/namespace.js";
import bus from "../util/bus";

//获取首页(书城)内容
let index = {};
export function getIndex(type) {
  //male or female
  if (type === "boy") type = "male";
  else if (type === "girl") type = "female";
  else type = "male";
  if (index[type]) return Promise.resolve(index[type]);
  return axios(`/books/${type}/index`).then(r => {
    r.forEach(list => {
      bookListFormat(list.books);
    });
    index[type] = r;
    return r;
  });
}
/**
获取书库书籍
关键字 key	String 
分类id category_id	Number 
页码 page String	
完结 status 完结:1 | 连载:0	
 */

export function getBook(params) {
  getBook.source = Axios.CancelToken.source();
  return axios("/books/library", { cancelToken: getBook.source.token, params })
    .then(r => {
      bookListFormat(r.list);
      return r;
    })
    .catch(function(thrown) {
      if (!Axios.isCancel(thrown)) {
        return Promise.reject(thrown);
      }
    });
}

//获取分类
let category = null;
export function getCategory() {
  if (category) return Promise.resolve(category);
  return (category = axios("/books/getCategory").then(r => {
    r.unshift({
      name: "不限",
      id: 0
    });
    return r;
  }));
}
// 获取详情
// 创建一个书籍详情的缓存池
let detail = new cache({
  meta: {
    name: "书籍详情"
  },
  limit: 40
});

//更新书籍信息中的是否在书架上(is_on_user_shelf)
function detailUpdate(id, status) {
  let book = detail.find(id);
  if (book.complete) {
    book.result.data.is_on_user_shelf = status;
  }
}
export function getDetail(id, s = "", pos = "") {
  return detail
    .getAsync(id, function() {
      return axios("/book/" + id + "?s=" + s + "&pos=" + pos).then(r => {
        return {
          id,
          data: r
        };
      });
    })
    .then(r => {
      return bookFormat(r.result.data);
    });
}

// 获取目录
// 创建一个目录的缓存池
let catalog = new cache({
  meta: {
    name: "目录"
  },
  limit: 20
});
export function getCatalog(id, page = 1, s = "") {
  return catalog
    .getAsync(id + "+" + page, function() {
      return axios(`/books/${id}/catalog`, {
        params: { page_size: 100, page, s }
      }).then(r => {
        return {
          id: id + "+" + page,
          data: r.list,
          meta: r.meta
        };
      });
    })
    .then(r => {
      return r.result;
    });
}

// 获取同款推荐
// 创建一个同款推荐的缓存池
let similar = new cache({
  meta: {
    name: "同款推荐"
  },
  limit: 20
});

export function getSimilar(bid, category_id) {
  return similar
    .getAsync(bid, function() {
      return axios(`/books/similar`, { params: { category_id, bid } }).then(
        r => {
          let data = bookListFormat(r);
          detail.push(
            data.map(v => {
              return {
                id: v.book_id,
                data: v
              };
            })
          );
          return {
            id: bid,
            data: data
          };
        }
      );
    })
    .then(r => {
      return r.result.data;
    });
}

//获取用户信息
let userinfo = null;
export function getUserInfo() {
  // if (userinfo) return Promise.resolve(userinfo)
  return axios("/userinfo").then(r => {
    return r;
  });
}

//获取书架
let shelf = null;
export function getShelf() {
  if (shelf) return Promise.resolve(shelf);
  return axios("/userShelfBooks").then(r => {
    r = shelfFormat(r);
    return r;
  });
}

//删除书架
export function delShelf(bid) {
  return axios("/userShelfBooks/delete?bid=" + bid).then(r => {
    detailUpdate(bid, 0);
    return r;
  });
}

//添加书架
export function addShelf(bid) {
  return axios.post("/userShelfBooks", { bid }).then(r => {
    shelf = null;
    detailUpdate(bid, 1);
    return r;
  });
}

//获取阅读记录
let readerRecord = null;

export function getReadrecord() {
  if (readerRecord) return Promise.resolve(readerRecord);
  return axios("/readrecord").then(r => {
    return r.map(book => {
      book.book_id = book.bid;
      return book;
    });
  });
}

// 添加阅读记录
export function setReadrecord(params) {
  return axios.post("/readrecord", params);
}
//删除阅读记录
export function delReadrecord(bid) {
  return axios.post("/readrecord/delete", { bid }).then(r => {
    return r;
  });
}

// 签到记录
export function getSignRecord(page = 1) {
  return axios(`/user/sign_record?page=${page}`);
}

//获取章节内容
// 创建一个同款推荐的缓存池

/*
错误处理
10012       未关注(默认链接)
10014       全本订阅余额不足（rmb）
10015       章订余额不足（充值）
10016       购买章节(书币)
10017       购买图书（书币）
10019       全本订阅余额不足（充值）
10023       未关注 (跳转渠道接诶)
----- 以上是弹窗  -------
10020       全本订阅余额不足,直接进入充值页
10021       章节订阅余额不足,直接进入充值页
10022       进入版权站
*/
let content = new cache({
  meta: {
    name: "章节内容"
  },
  limit: 20
});

export function getContent(bid, cid, adStatus = 0, from, code = "") {
  let url = options.adTargetId
    ? `/books/${bid}/chapters/${cid}?ad_status=${adStatus}&page_from=${from}&code=${encodeURIComponent(
        code
      )}`
    : `/books/${bid}/chapters/${cid}?page_from=${from}&code=${encodeURIComponent(
        code
      )}`;
  return content
    .getAsync(bid + "+" + cid, function() {
      return axios(url).then(r => {
        return {
          id: bid + "+" + cid,
          data: contentFormat(r)
        };
      });
    })
    .then(r => {
      if (!r.fresh) {
        setReadrecord({ bid, cid, chapter_name: r.result.data.chapter_name });
      }
      // TODO: 暂时这么做
      // let cacheTap = localStorage.getItem(cid)
      // if (cacheTap) {
      //   r.result.data.chapter_comment = cacheTap
      // }
      return r.result.data;
    });
}

//余额支付
export function subscribeByBalance(bid, cid, remind) {
  let params = remind ? { params: { remind: 1 } } : {};
  return axios(`/books/${bid}/balance/chapterOrders/${cid}`, params).then(r => {
    content.push({
      id: bid + "+" + cid,
      data: contentFormat(r)
    });
    return r;
  });
}

//RMB支付
export function subscribeByRMB(params) {
  const a = document.createElement("a");
  const redirect = {
    host: location.origin,
    pathname: "/reader",
    query: {
      bid: params.book_id,
      cid: params.chapter_id
    }
  };
  const href = {
    host: window.options.pay_url,
    query: {
      product_id: params.product_id,
      uid: window.options.uid,
      distribution_channel_id: window.options.distribution_channel_id,
      send_order_id: window.options.send_order_id,
      pay_redirect_url: encodeURIComponent(urlFormat(redirect))
    }
  };
  a.href = urlFormat(href);
  a.click();
}

// 排行帮
//type	Int (点击帮:1|字数帮:2|新书榜:3)
//time	Int (周:1|月:2|总:3)
let rank = {};
export function getRank(type = 1, time = 1) {
  let id = type + "+" + time;
  if (rank[id]) return Promise.resolve(rank);
  return axios("/books/rank", {
    params: {
      type,
      time
    }
  }).then(r => {
    bookListFormat(r.male);
    bookListFormat(r.female);
    rank[id] = r;
    return rank;
  });
}

//充值产品列表
let product = null;
export function getProductList(bid) {
  if (product) return product;
  else return axios("/order/chargeList", { params: { bid } });
}

//充值
export function recharge({ product_id, bid, cid, use_coupon }) {
  const a = document.createElement("a");
  const redirect =
    bid && cid
      ? {
          host: location.origin,
          pathname: "/reader",
          query: {
            bid,
            cid
          }
        }
      : {
          host: location.origin,
          pathname: "/recent"
        };
  const token = localStorage.getItem("token");

  const href = {
    host: window.options.pay_url,
    query: {
      product_id: product_id,
      token: token ? `${token}` : "",
      use_coupon,
      distribution_channel_id: window.options.distribution_channel_id,
      send_order_id: window.options.send_order_id,
      from: window.options.from,
      bid,
      cid,
      pay_redirect_url: encodeURIComponent(urlFormat(redirect))
    }
  };
  //window.open(urlFormat(href),'微信支付',true)
  a.href = urlFormat(href);
  a.click();
}

//单本消费记录
export function getRecordOrderByBook(page) {
  return axios("/order/bookOrderList", { params: { page } });
}

//章节消费记录
export function getRecordOrderByChapter(page) {
  return axios("/order/chapterOrderList", { params: { page } });
}

//充值记录
export function getRecordRecharge(page) {
  return axios("/order/chargeRecordLists", { params: { page } }).then(r => {
    recordFormat(r.list);
    return r;
  });
}
//赠送记录
export function getRecordSend(page) {
  return axios("/getGivenRocords", { params: { page } }).then(r => {
    return r;
  });
}

// 尾页推荐
export function getReadOverRecommend(bid) {
  return axios("/books/readOverRecommend", { params: { bid } }).then(r => {
    bookListFormat(r.recommend_result);
    return r;
  });
}

// 获取弱关二维码
export function getweakSubscribeQR() {
  return axios("/subscribe/qrcode");
}

// 用户行为
export function PostUserBehavior(data) {
  return axios.post("/userBehavior", data);
}

// 错误捕获
export function undefinedCollect(data) {
  return axios.post("/error/undefinedCollect", data);
}

// 章节底部评价
export function chapterComment(bid, chapter, tags) {
  return axios.post("/chapter/comment", { bid, chapter, tags });
}

// 获取章节底部评价
export function getChapterComment(bid, chapter) {
  return axios("/chapter/getComment", { params: { bid, chapter } });
}

// 签到页面
export function toSign() {
  return axios("user/sign");
}

// 获取礼物列表
export function getGiftList() {
  return axios("/gift/getGiftsList");
}

// 送礼
export function sendGift(data) {
  return axios.post("/gift/sendGifts", data);
}

// 送礼记录
export function getSendGiftRecord(params) {
  return axios("/gift/getUserSendGiftsRecord", { params });
}

// 消费记录中的送礼记录
export function getUserSendGiftRecord(page) {
  return axios("/gift/getUserGiftsConsumeRecord", { params: { page } });
}

// 获取代付用户数据
export function getSubstitutePay(product_id) {
  return axios("/order/substitutePay", { params: { product_id } });
}

// 获取代付充值列表
export function getSubstitutePayList(product_id, su) {
  return axios("/order/substitutePayChargeList", {
    params: { product_id, su }
  });
}

// 代充
export function substituteRecharge({ product_id, uid }) {
  const a = document.createElement("a");
  const href = {
    host: window.options.pay_url,
    query: {
      product_id: product_id,
      suid: window.options.uid,
      uid: uid,
      distribution_channel_id: window.options.distribution_channel_id,
      send_order_id: window.options.send_order_id,
      from: window.options.from
    }
  };
  a.href = urlFormat(href);
  a.click();
}

// 最近阅读轮播
export function recentSlideList() {
  return axios("/books/H5SmartRecommendBooks?pos=h5RecentReadLoop");
}

// 获取代付充值列表
export function getbookFromWhere(bid, fromwhere) {
  return axios("/bookFromWhere/" + bid, { params: { fromwhere } });
}

// 获取分享按钮是否显示
export function getRecordShare(bid, cid) {
  return axios("/user/recordShare", { params: { bid, cid } });
}

// 获取分享签名
export function getWechatJsConfig(bid, cid, url) {
  return axios("/chapter/getWechatJsConfig", { params: { bid, cid, url } });
}

// 广告点击情况
export function recordAdClickStatus(bid, cid, type = "UNLOCK") {
  return axios.post("/user/advisitstat", {
    bid,
    cid,
    type
  });
}

// 尾页推荐催更
export function upgBookStatus(bid) {
  return axios("/user/urgeUpdate", { params: { bid } });
}

// 获取举报内容
export function getReportList() {
  return axios("/complaints/getComplaintTags");
}

// 举报
export function uploadReport(data) {
  return axios.post("/complaints/add", data);
}

// 获取广告banner
export function getReaderAdBanner() {
  return axios("//banner.66kshu.com/b.gif");
}

// 发送验证码
export function getPhoneCode(phone) {
  return axios.post("/bindphone/sendcode", { phone });
}

// 绑定手机
export function phoneBind(data) {
  return axios.post("/bindphone/bind", data);
}

// 获取验证码
export function getCode(data) {
  return axios.post("/bindphone/sendcode", data);
}

// 获取fakebook详情
export function getBookDetail(id) {
  return axios("/red_book/getBookDetail?id=" + id);
}

// 获取fakebook详情
export function getChapterList(id) {
  return axios("/red_book/getChapterList?id=" + id);
}

// 查询包月订单是否成功
export function isMonthOrderSuc() {
  return axios("/monthorder/issuccess");
}

// 配置wx分享
export function getWxConfig(url) {
  return axios.post("/weixin/jsSdkConfig", { url });
}

// 个人中心客服
export function getCustomQRCode(distribution_channel_id, openid) {
  return axios("/custom_qrcode", {
    params: { distribution_channel_id, openid }
  });
}

// 限免书单
export function getBookLimitFree() {
  return axios("/books/freeBook");
}

// 新版排行列表
export function getRankListV2() {
  return axios("/books/rankList");
}
//用户优惠券列表
export function getUserCoupon() {
  return axios("/user/userCoupon");
}

//支付可用优惠券
export function getOrderCoupon() {
  return axios("/order/effectiveCoupon");
}

//登录平台
export function userLogin(data) {
  return axios("/login", { params: data });
}

//绑定手机号新版
export function bindUserPhone(data) {
  return axios.post("/bindphone/bind", data);
}

//获取中间页数据
export function getYun(id) {
  return axios(`/yun/${id}`);
}

//获取最近阅读记录
export function getRecentReader() {
  return axios(`/readrecord/getLastRead`);
}

//换取userId
export function uuidsGetTokens(uuid) {
  return axios(`/hashuserToToken`, { params: { hashuser: uuid } });
}

//记录用户加桌状态
export function setUserMode(status) {
  return axios.post(`/setAddDeskStatus`, {  add_desk_status: status  });
}
