<import name="short-page" src="../../components/short/index.ux"></import>
 <import name="wechat-page" src="../../components/wechat/index.ux"></import> 
<template>
  <div id="reader-content">
    <stack>
      <div class="reader-wrap" id='list' style="background-color:{{currentColor.color}}">
        <div class="reader-title">
          <text class="title" style="color:{{isNight=='night'?'#666':'#333'}}">{{bookinfo.chapter_name}}</text>
          <!-- <text class="add-shelf" @click="addShelf">加入书架1</text> -->
        </div>
        <div class="reader-content">
          <div class="readContent" @click="showMore"><text class="chapter-text" for='content' style="color:{{currentColor.fontColor}};font-size:{{`${readFontSize}px`}}">{{$item}}</text></div>
          <div class="bottom-setting" style="background-color:{{currentColor.btColor}}" if={{showSetting}} @click="stopPop">
            <div class="item-content">
              <text class="label-min" style="color:{{isNight=='night'?'#666':'#333'}}">A</text>
              <slider class="slider" min="30" max="48" step="2" value="{{readFontSize}}" onchange="changeFontSize" style="blockColor: #fff"></slider>
              <text class="label-max" style="color:{{isNight=='night'?'#666':'#333'}}">A</text>
            </div>
            <div class="item-color">
              <text class="colori" for="colorList" onclick="changeColor($item,undefined)" style="border-color:{{currentColor.color==$item.color? currentBorder: $item.borderColor}};background-color:{{$item.color}};"></text>
              <text class="color-icon {{ isNight }}" onclick="changeColor(nightColor,isNight)"></text>
            </div>
            <div class="item-page">
              <text @click="getPrevChapter" style="color:{{isNight=='night'?'#666':'#333'}}">上一章</text>
              <text @click="toCatalog" style="color:{{isNight=='night'?'#666':'#333'}}">目录</text>
              <text @click="getNextChapter" style="color:{{isNight=='night'?'#666':'#333'}}">下一章</text>
            </div>
            <div>
            </div>
            <div class="setting-top" style="background-color:{{currentColor.color}}" if={{showSetting}} @click="backRouter">
              <image src="{{getImgUrl}}" class="back-icon"></image> <text style="color:{{isNight=='night'?'#666':'#333'}}">{{bookinfo.chapter_name}}</text><text style="text-indent:-999px">1</text>
            </div>
          </div>
  
          <div class="banner-list" if="{{reader_banner.length>0}}">
            <swiper class="swipe-bar" autoplay="true" indicator="false">
              <block for="reader_banner">
                <div class="swipe-item">
                  <image class="cover" src="{{$item.img}}" @click="goActivity($item)"></image>
                </div>
              </block>
            </swiper>
          </div>
        </div>
        <short-page if="{{showShortPop}}" @addshort="shortEnd"></short-page>
        <!-- <wechat-page></wechat-page> -->
        <div class='toast' if="{{showtoast}}">
          <text>正在加载中...</text>
        </div>
    </stack>
    <div class="reader-bottom">
        <div class="reader-operator-next" @click="getNextChapter"><text class="operator">下一章</text></div>
          <div class="reader-operator">
                  <text class="operator prev" @click="getPrevChapter">上一章</text>
                  <text>|</text>
                 <text class="operator catalog" @click="toCatalog">目录</text>
          </div>
    </div>
    <div class="mustToask" show="{{showMustTost}}">
      <div class="mustBox">
        <text class="title-must">
          提示
        </text>
        <text class="content">
          添加桌面后方可继续阅读精彩内容
        </text>
        <text class="button-must" @click="addDestop">添加到桌面</text>
      </div>
    </div>
  </div>

</template>

<script>
import prompt from '@system.prompt';
import router from "@system.router";
import storage from '@system.storage';
import it from "../../helper/interface.js";
import { getChapters, getIsonshelf, postUserShelfBooks, chapterOrders, userAddDsktop } from "../../api";
import { getAppConfig } from '../../api/utils.js';
let getConfig;
export default {
  // protected: {
  //   bid: '',
  //   chapter_id: ''
  // },
  public: {
    bid: '',
    chapter_id: '',
    send_order_id: "",
    push_id: "",
    canReadecid: "",
    showtoast: false
  },
  private: {
    bookinfo: {},
    content: [],
    reader_banner: [],
    showShortPop: false,
    readFontSize: 38,
    isNight: 'sun',
    hasShort: false,
    showSetting: false,
    force_add_desk_type: 0,
    showMustTost: false,
    back_reader: 0,
    colorList: [
      { color: '#DFDAC7', borderColor: '#6090AE', btColor: '#E8F6FF', isIcon: false },
      { color: '#E6E6E6', borderColor: '#CCC', btColor: '#F2F2F2', isIcon: false },
      { color: '#EED9BB', borderColor: '#C6A473', btColor: '#FFFBE8', isIcon: false },
      { color: '#B3E2CB', borderColor: '#68AA8A', btColor: '#D5F2D8', isIcon: false },
      { color: '#B3D0E2', borderColor: '#6090AE', btColor: '#E8F6FF', isIcon: false },

    ],
    currentBorder: '#EE6159',
    nightColor: {
      fontColor: '#666',
      btColor: '#333',
      color: '#1a1a1a'
    },
    currentColor: {
      color: '#DFDAC7', btColor: '#F2F2F2', fontColor: '#1a1a1a'
    }
  },
  computed: {
    getImgUrl() {
      return this.isNight == 'night' ? '../../assets/imgs/white_back.png' : '../../assets/imgs/black_back.png'
    }
  },
  async onInit() {
    if (this.send_order_id) {
      await storage.set({ key: "send_order_id", value: this.send_order_id });
    } else {
      let send_order_id = (await storage.get({ key: "send_order_id" })).data;
      if (send_order_id) this.send_order_id = send_order_id;
    }
    if (this.push_id) {
      await storage.set({ key: "push_id", value: this.push_id });
    }
    /* let s = (await storage.get({ key: "send_order_id" })).data;
    console.log("save send_order_id in storage");
    console.log("send_order_id", this.send_order_id);
    console.log("storage send_order_id", s); */
    await this.getChapters(this.bid, this.chapter_id);
    let setting = (await storage.get({ key: "readSetting" })).data;
    if (setting) {
      let sets = JSON.parse(setting)
      this.currentColor = sets;
      this.isNight = sets.isNight;
    }
    let font = (await storage.get({ key: "readFont" })).data;
    if (font) {
      this.readFontSize = font;
    }
    getConfig = getAppConfig(this);
    let { reader_banner } = await getConfig('position');
    this.reader_banner = reader_banner;
    let { sign_out_reader_show } = await getConfig('add_desk_alert');
    this.back_reader = sign_out_reader_show;
    userAddDsktop(this.$app.$def.data.backClickCount).then(res => {
      //TODO 加桌后统计上报
    }).catch(r => {
      //TODO 失败后统计上报
    });
  },
  goActivity(item) {
    router.push({
      uri: item.url,
      params: item.params
    })
  },
  backRouter() {
    if (this.back_reader == 1) {
      it.backCreateShortCut(res => {
        if (res == 'back') {
          if (router.getLength() === 1) {
            router.replace({ uri: "/views/Index" });
            return true;
          } else {
            router.back()
          }
        }
      });
    } else {
      if (router.getLength() === 1) {
        router.replace({ uri: "/views/Index" });
        return true;
      } else {
        router.back()
      }
    }
  },
  async onShow() {
    it.getShortCut((value) => {
      this.showSetting = false;
      this.showShortPop = !value;
      this.hasShort = value;
      if (value) {
        this.$app.$def.data.backClickCount = 1
      } else {
        this.$app.$def.data.backClickCount = 0
      }
    })
    let params = {
      bid: this.bid,
      chapter_id: this.chapter_id,
    }
    await storage.set({ key: "lastCapter", value: JSON.stringify(params) });
  },
  stopPop(evt) {
    evt.stopPropagation();
    return;
  },
  showMore() {
    this.showSetting = !this.showSetting;
    if (this.showSetting) {
      this.showShortPop = false;
    } else {
      if (!this.hasShort) this.showShortPop = true;
    }
  },

  async changeFontSize(evt) {
    this.readFontSize = evt.progress;
    await storage.set({ key: "readFont", value: this.readFontSize });
  },
  async changeColor(item, type) {
    if (type) {
      if (type == 'sun') {
        this.isNight = 'night';
        this.currentColor = this.nightColor;
        await storage.set({ key: "readSetting", value: JSON.stringify({ ...this.nightColor, isNight: 'night' }) });
      } else {
        this.isNight = 'sun';
        this.currentColor = { color: '#E6E6E6', borderColor: '#CCC', btColor: '#F2F2F2', isIcon: false };
        await storage.set({ key: "readSetting", value: JSON.stringify({ ...this.currentColor, isNight: 'sun' }) });
      }
    } else {
      this.isNight = 'sun';
      this.currentColor = {
        color: item.color,
        btColor: item.btColor,
        fontColor: '#1a1a1a'
      }
      await storage.set({ key: "readSetting", value: JSON.stringify({ ...this.currentColor, isNight: 'sun' }) });
    }
  },
  addShelf() {
    console.log("add shelf");
    getIsonshelf({ bid: this.bid }).then(r => {
      r.is_on ? '' : postUserShelfBooks({ bid: this.bid })
    })
  },
  shortEnd(value) {
    if (value.detail.installed) {
      this.showMustTost = false;
      prompt.showToast({ message: "添加桌面成功！请前往任务中心领取奖励" });
    }
    this.showShortPop = !value.detail.installed;
    this.hasShort = value.detail.installed;

  },
  getChapters(bid, chapter_id) {
    this.showtoast = true
    console.log("router length:", router.getLength());
    getChapters({ bid: bid, chapter_id: chapter_id }).then(r => {
      this.force_add_desk_type = r.force_add_desk_type;
      this.content = r.chapter_content.trim().split(/\n/)
      this.bookinfo = r;

      // this.$element('list').scrollTo({ index: 0 })
      this.addShelf();
      this.showtoast = false
    }).catch(e => {
      console.log('e code')
      console.log(e.data)
      console.log(e.data.code == '10016' || e.data.code == '10019')
      if (e.data.code == '10016' || e.data.code == '10019' || e.data.code == '10017') {
        chapterOrders({ bid: bid, chapter_id: chapter_id }).then(r => {
          this.content = r.chapter_content.trim().split(/\n/)
          this.bookinfo = r
          this.showtoast = false
          // this.$element('list').scrollTo({ index: 0 })
        }).catch(f => {
          console.log('f code')
          console.log(f.data)
          this.showtoast = false
          if (f.data.code == '10014' || f.data.code == '10015' || f.data.code == '10016') {
            this.getChapters(bid, this.canReadecid)
            router.push({
              uri: "/views/Pay",
              params: {
                code: f.data.code,
                fee: e.data.data.fee,
                bid: this.bid
              }
            })
          }
        })
      } else if (e.data.code == '10014' || e.data.code == '10015') {
        this.showtoast = false
        this.getChapters(bid, this.canReadecid)
        router.push({
          uri: "/views/Pay",
          params: {
            code: e.data.code,
            fee: e.data.data.fee,
            bid: this.bid
          }
        })
      }
    })
  },
  toCatalog(evt) {
    evt.stopPropagation();
    router.replace({
      uri: "/views/Catalog",
      params: {
        chapter_sequence: this.bookinfo.chapter_sequence,
        bid: this.bid,
        chapter_id: this.chapter_id,
        fromReader: true,
      }
    })
  },
  getPrevChapter(evt) {
    evt.stopPropagation();
    console.log("get prev chapter");
    if (this.bookinfo.prev_cid == 0) {
      return prompt.showToast({ message: '已经是第一章啦' });
    }
    router.replace({
      uri: "/views/Reader",
      params: {
        bid: this.bookinfo.bid,
        chapter_id: this.bookinfo.prev_cid,
        canReadecid: this.bookinfo.chapter_id
      }
    })
  },
  addDestop() {
    it.mustCreateShort((res, code) => {
      if (res) {
        this.goNext();
      } else {
        prompt.showToast({ message: '开启加桌权限可以领取新人福利哟~' });
      }
    })
  },
  getNextChapter(evt) {
    evt.stopPropagation();
    let _this = this;
    if (this.force_add_desk_type == 1) {
      it.getShortCut(res => {
        if (!res) { this.showMustTost = true; } else {
          this.goNext();
        }
      })
    } else if (this.force_add_desk_type == 2) {
      it.loseLevelShortCut(res => {
        this.goNext();
      })
    } else {
      this.goNext();
    }
  },
  goNext() {
    let self =this;
    if (this.bookinfo.next_cid == 0) {
      router.push({
        uri: "/views/Raderover",
        params: {
          bid: this.bid
        }
      })
      return
    }
    //判断是否自然流量自然流量付费章节开启付费提醒
    if (!this.send_order_id && this.bookinfo.next_chapter_status == 2) {
      prompt.showDialog({
        title: '温馨提示',
        message: `下一章即将消耗${this.bookinfo.next_price}书币哟~`,
        buttons: [
          {
            text: '阅读下一章',
            color: '#EF5952'
          },
          {
            text: '我再想想',
            color: '#999'
          }
        ],
        success: function (data) {
          if (data.index === 0) {
            router.replace({
              uri: "/views/Reader",
              params: {
                bid: self.bookinfo.bid,
                chapter_id: self.bookinfo.next_cid,
                canReadecid: self.bookinfo.chapter_id
              }
            })
          }

        },
        cancel: function () {
          console.log('取消前往')
        },
      })
    } else {
      router.replace({
        uri: "/views/Reader",
        params: {
          bid: this.bookinfo.bid,
          chapter_id: this.bookinfo.next_cid,
          canReadecid: this.bookinfo.chapter_id
        }
      })
    }

    // this.getChapters(this.bookinfo.bid, this.bookinfo.next_cid)

  },
  onBackPress() {
    if (this.back_reader == 1) {
      it.backCreateShortCut(res => {
        if (res == 'back') {
          if (router.getLength() === 1) {
            router.replace({ uri: "/views/Index" });
            return true;
          } else {
            router.back()
          }
        }
      });
    } else {
      if (router.getLength() === 1) {
        router.replace({ uri: "/views/Index" });
        return true;
      } else {
        router.back()
      }
    }


    return true;
  }
}
</script>

<style lang="less">
@import '../../assets/less/reader.less';
</style>
