<import name="x-book" src="../../components/book/book.ux"></import>
<template>
  <div class="task-page">
    <div class="task-banner">
      <div class="swiper-container">
        <swiper class="swipe-bar" autoplay="true" indicator="false">
          <block for="book in bannerList">
            <div class="swipe-item">
              <image
                class="cover"
                src="{{book.banner_url}}"
                @click="pageRouter(book)"
              ></image>
            </div>
          </block>
        </swiper>
      </div>
    </div>
    <div class="sign-section">
      <div class="sign-title" @click="showRules">
        <text>已连续签到{{ signData.signDay }}天</text>
        <image src="../../assets/imgs/question.png"></image>
      </div>
      <text class="sign-desc">连续签到可持续获得高额奖励</text>
      <div class="sign-line">
        <div class="sign-line__item " for="{{signList}}">
          <div class="line__item_wrap">
            <text class="sign-line__fee">+{{ $item.fee }}</text>
            <image src="../../assets/imgs/sign_{{$item.iconType}}.jpg"></image>
          </div>
          <text class="sign-line__day">{{ $item.day }}天</text>
        </div>
      </div>
      <text class="sign-button" @click="signToday" if="{{!signData.is_sign}}">
        立即签到
      </text>
      <text class="sign-button-disabled" if="{{signData.is_sign}}">
        已签到
      </text>
    </div>

    <div class="task-section">
      <div class="task-section__list">
        <text class="task-section__list_new">新手必做任务</text>
        <div
          class="list-item"
          for="{{newList}}"
          @click="compeletTask($item.status, $item.type, $item.id, $item.path)"
        >
          <div class="content">
            <div>
              <text>{{ $item.name }}</text>
              <div class="task-award">
                <image src="../../assets/imgs/sign_coin.jpg"></image
                ><text>+{{ $item.value }}积分</text>
              </div>
            </div>

            <text class="content-desc">{{ $item.desc }}</text>
          </div>
          <text
            class="button-status {{ $item.status==0 ? 'wait': ($item.status==1 ? 'get' : 'disabled') }}"
          >
            {{
              $item.status == 0
                ? '去完成'
                : $item.status == 1
                ? '领取'
                : '已领取'
            }}
          </text>
        </div>
      </div>
      <div class="task-section__list">
        <text class="task-section__list_new">日常福利</text>
        <div
          class="list-item"
          for="{{dayList}}"
          @click="compeletTask($item.status, $item.type, $item.id, $item.path)"
        >
          <div class="content">
            <div>
              <text>{{ $item.name }}</text>
              <div class="task-award">
                <image src="../../assets/imgs/sign_coin.jpg"></image
                ><text>+{{ $item.value }}积分</text>
              </div>
            </div>
            <text class="content-desc">{{ $item.desc }}</text>
          </div>
          <text
            class="button-status {{ $item.status==0 ? 'wait': ($item.status==1 ? 'get' : 'disabled') }}"
          >
            {{
              $item.status == 0
                ? '去完成'
                : $item.status == 1
                ? '领取'
                : '已领取'
            }}
          </text>
        </div>
      </div>
    </div>
    <div class="mask" show="{{showRule}}">
      <div class="rule">
        <text class="rule-title">签到规则</text>
        <text class="detail"
          >1.每7天为一个签到周期，用户连续签满7天，完成一个签到周期，下次签到重新计算签到周期
        </text>
        <text class="detail"
          >2.用户连续签到获得的奖励更高，若中途漏签，则从第一天开始重新计算签到周期
        </text>
      </div>
      <image
        src="../../assets/imgs/pop_close.png"
        class="close-icon"
        @click="closeRule"
      ></image>
    </div>
    <div class="mask" if="{{SignSuccess}}">
      <div class="sign-banner">
        <text class="sign-banner__text"
          ><span>获得</span><span class="orange">{{ currentFee }}</span
          ><span>书币</span></text
        >
      </div>
      <image
        src="../../assets/imgs/pop_close.png"
        class="close-icon"
        @click="closeSign"
      ></image>
    </div>
  </div>
</template>
<script>
import {
  userTaskList,
  userAddDsktop,
  getTaskAward,
  getSignInfo,
  noVipSign,
  taskBook,
  getReadrecord
} from '../../api/index'
import router from '@system.router'
import shortcut from '@system.shortcut'
import storage from '@system.storage'
import prompt from '@system.prompt'
export default {
  public: {
    push_id: '',
    send_order_id: ''
  },
  protected: {
    signList: [],
    currentFee: 0,
    signData: {},
    showRule: false,
    SignSuccess: false,
    dayList: [],
    newList: [],
    type: 'new',
    bannerList: [],
    isClick: false,
    mockList: []
  },
  computed: {
    currentList() {
      let curList = this.type == 'new' ? this.newList : this.dayList
      return curList
    }
  },
  async onInit() {
    if (this.push_id) {
      await storage.set({ key: 'push_id', value: this.push_id })
    }
    if (this.send_order_id) {
      await storage.set({ key: 'send_order_id', value: this.send_order_id })
    }
    this.getBook()
    this.getSignList()
    this.getRordList()
  },
  onShow() {
    this.getTaskList()
  },
  // async getRordList() {
  // 	getReadrecord().then(r => {
  // 		r.map(m => {
  // 			m.cover_url = m.cover
  // 			m.recent_cid = m.cid
  // 			delete m.cover
  // 			delete m.cid
  // 		})
  // 		r.length > 3 ? this.mockList = r.slice(0, 3) : this.mockList = r;
  // 	})
  // },
  async getBook() {
    let bookList = await taskBook()
    this.bannerList = bookList
  },
  async getSignList() {
    let signList = []
    let signData = await getSignInfo()
    signData.reward_list.map((item, idx) => {
      signList.push({
        day: idx + 1,
        iconType: idx < signData.sign_day ? 'checked' : 'coin',
        fee: item
      })
    })
    signData.signDay = signData.sign_day
    this.currentFee = signData.reward_list[Number(signData.sign_day)]
    this.signList = signList
    this.signData = signData
  },
  async getTaskList() {
    //每次展示刷新当前任务
    let list = await userTaskList().catch(err => {
      console.log(err)
    })
    let dayList = list.date_tasks
    let newList = list.new_user_tasks
    //TODO数组处理
    this.dayList = dayList
    this.newList = newList
  },
  // changeTab(type) {
  // 	this.type = type;
  // },
  closeRule() {
    this.showRule = false
  },
  showRules() {
    this.showRule = true
  },
  goMore() {
    router.push({ uri: '/views/Index?curPage=1' })
  },
  signToday() {
    noVipSign().then(res => {
      this.signList[this.signData.sign_day].iconType = 'checked'
      this.SignSuccess = true
      this.signData.signDay++
      this.signData.sign_day++
      this.signData.is_sign = true
      prompt.showToast('恭喜您签到成功！')
    })
  },
  pageRouter(page) {
    router.push({
      uri: page.redirect_url,
      params: {
        bid: page.bid,
        chapter_id: page.cid
      }
    })
  },
  closeSign() {
    this.SignSuccess = false
  },
  async compeletTask(status, type, id, path) {
    if (this.isClick) return false
    this.isClick = true
    if (status == 2) {
      this.isClick = false
      return false
    } else if (status == 0) {
      this.isClick = false
      this.goTask(type, path)
    } else {
      let data = await getTaskAward(id)
      this.getTaskList()
      this.isClick = false
      prompt.showToast('领取成功！')
    }
    this.isClick = false
  },
  onBackPress() {
   this.getLastpage();
    return true
  },
  goTask(type, path) {
    let _self = this
    if (type == 'add_desk') {
      shortcut.hasInstalled({
        success: ret => {
          if (!ret) {
            shortcut.install({
              message: '添加【阅乐】到桌面，方便下次阅读',
              success: () => {
                prompt.showToast('添加成功！')
                userAddDsktop(1)
                  .then(res => {
                    _self.getTaskList()
                  })
                  .catch(r => {
                    //TODO 失败后统计上报
                  })
              },
              fail: code => {
                console.log(code)
              }
            })
          } else {
            userAddDsktop(1)
              .then(res => {
                _self.getTaskList()
              })
              .catch(r => {
                //TODO 失败后统计上报
              })
          }
        }
      })
    } else if (path && path != '') {
      router.push({
        uri: path
      })
    }
  },getLastpage(){
    let backPage = {};
      try{
        let page = router.getState();
        let allPage = router.getPages();
        // console.log('page = ',page,'all pages',allPage,'length',allPage.length);
        for(var k = allPage.length -1; k >=  0;k--){
          if(allPage[k].name != page.name && allPage[k].name != "views/Phone" && allPage[k].name != "views/Pay" && allPage[k].name != "views/Activity"){
            backPage = allPage[k];
            break;
          }
        }
      } catch(e){
        backPage = {};
        // console.log('back err',e);
      }
      // console.log(backPage,backPage.length,typeof backPage);
      if(JSON.stringify(backPage) === '{}'){
         router.replace({ uri: "/views/Index" });
      }else{
        router.back(backPage);
      }
    return true;
  }
}
</script>
<style lang="less">
@import '../../assets/less/task.less';
</style>
