<template>
  <div class="mainPage">
    <div>
      <loadMore :on-infinite="onInfinite" :dataList="scrollData">
        <div class="header flex-h">
          <div class="flex-item flex-h">
            <i class="iconfont icon-sousuo"></i>
            <a
              class="flex-item"
              style="line-height: .3rem;color: #ccc;"
              @click="tosearch"
            >书本名称</a>
          </div>
          <a @click="showDialog = true">
            <i class="iconfont icon-dingwei"></i>
            <span>{{currentCaseName}}</span>
          </a>
        </div>
        <nav class="nav">
          <a
            v-for="(item, index) in navList"
            v-if="(navList || []).length < 9 || index<7"
            :key="index"
            @click="navClick(item)"
          >
            <img :src="item.BookTypeImg" alt>
            <span>{{item.BookTypeName}}</span>
          </a>
          <a v-if="(navList || []).length > 8 " @click="moreNav()">
            <img src="https://spaceofcheng.oss-cn-beijing.aliyuncs.com/icon_more.png" alt>
            <span>更多</span>
          </a>
        </nav>
        <div class="list">
          <h1>精选推荐</h1>
          <ul>
            <li v-for="(item, index) in books.list" :key="index">
              <libraryListItem
                :data="item"
                :status="mineBookStatus(item)"
                @appointmentBook="appointmentBook"
              ></libraryListItem>
            </li>
          </ul>
        </div>
      </loadMore>
      <van-dialog v-model="showDialog" :show-confirm-button="false">
        <div class="dialogContent">
          <span class="title">选择案场</span>
          <div>
            <radio :data="cases" v-model="caseId"></radio>
          </div>
          <div class="btn">
            <a @click="selectCaseId">确定</a>
          </div>
        </div>
      </van-dialog>
      <van-dialog v-model="showAppointmentDialog" :show-confirm-button="false">
        <div class="dialogContent">
          <span class="title">确认在线预约当前图书?</span>
          <div>
            <span style="color: #666;font-size:0.14rem;">在线预约需在{{reserveEndDate}}前前往案场借阅图书, 否则将取消预约资格</span>
          </div>
          <div class="btn">
            <a @click="sureAppointmentBook">确定</a>
            <a @click="showAppointmentDialog = false">取消</a>
          </div>
        </div>
      </van-dialog>
    </div>
  </div>
</template>

<script>
import loadMore from '@/components/vue-load-more/index'
import libraryListItem from '../../../../components/libraryListItem/index'
import radio from '../../../../components/radio/index'
import toolClass from '../../../../util/util'
import { mapState, createNamespacedHelpers } from 'vuex'
const { mapActions: mapAppActions } = createNamespacedHelpers('app')
const { mapState: mapBookState, mapActions: mapBookActions } = createNamespacedHelpers('book')
import { Toast } from '../../../../../node_modules/vant';
import wxsdk from '../../../../util/share'
import wx from 'weixin-jsapi'
// const wx = require('weixin-js-sdk')
export default {
  name: '',
  data () {
    return {
      showDialog: false,
      showAppointmentDialog: false,
      caseId: '',
      currentCaseId: '',
      currentCaseName: '',
      cases: [],
      indexSearchKey: '',
      page: 1,
      pagesize: 10,
      scrollData: {
        noFlag: false // 暂无更多数据显示
      },
      reserveBookId: '',
      latitude: '',
      longitude: '',
    }
  },
  computed: {
    ...mapState({
      userInfo: x => x.userCenter.userInfo,
      CaseList: x => x.app.CaseList
    }),
    ...mapBookState({
      navList: x => x.types.list,
      books: x => x.recommends,
      mineBooks: x => x.minebooks,
      bookcaseid: x => x.bookcaseid,
    }),
    reserveEndDate () {
      return toolClass.calDate(7)
    }
  },
  components: {
    libraryListItem,
    radio,
    loadMore
  },
  created () {
    if (!this.CaseList.length || this.CaseList === null) {
      this.getCaseList().then((res) => {
        (res.cases || []).map((item) => {
          this.cases.push({
            value: item.CaseName,
            id: item.CaseId
          })
        })
        this.detectLoc().then(() => this.init()).catch(() => this.init())
      })
    } else {
      (this.CaseList || []).map((item) => {
        this.cases.push({
          value: item.CaseName,
          id: item.CaseId
        })
      })
      this.detectLoc().then(() => this.init()).catch(() => this.init())
    }
  },
  methods: {
    ...mapAppActions(['getCaseList']),
    ...mapBookActions([
      'getBookType',
      'getRecommendBook',
      'getMineBook',
      'reserveBook',
      'updateRecommendBookLeftNum',
      'setBookCase',
    ]),
    tosearch () {
      if (this.currentCaseId === '') {
        Toast.fail({
          duration: 2000, // 持续展示 toast
          forbidClick: true, // 禁用背景点击
          message: '请先选择案场'
        })
        return 
      }
      this.$router.push({name: 'booksSearch', query: {caseid: this.currentCaseId}})
    },
    detectLoc () {
      return new Promise((resolve, reject) => {
        let hasSol = false
        const startDt = (new Date).getTime()

        // const t = window.setInterval(() => {
        //   const nw = (new Date).getTime()

        //   if (hasSol) {
        //     window.clearInterval(t)
        //     return
        //   }

        //   // 500 毫秒还未定位则直接取消定位
        //   if ((nw - startDt) >= 500) {
        //     hasSol = true
        //     window.clearInterval(t)

        //     this.setDefaultCase(((this.CaseList || [])[0] || {}).CaseId)
        //     reject('定位超时 ...')
        //   }
        // }, 100)

        wxsdk({ url: encodeURIComponent(window.location.href.split('#')[0]) }, {
          title: '城的空间',
          desc: '城的空间',
          link: `${window.location.origin}${window.location.pathname}#/mainPage/indexPage`,
          thu_image: `https://spaceofcheng.oss-cn-beijing.aliyuncs.com/indexlogo.jpg?x-oss-process=style/wxicon`
        }).then(() => {
          console.log(wx.getLocation)
          if (hasSol) return
          hasSol = true
          const that = this

          // 如果已经存在案场
          if (!!that.bookcaseid) {
            that.currentCaseId = that.bookcaseid
            that.caseId = that.bookcaseid
            that.currentCaseName = (that.CaseList.filter(x => x.CaseId === that.currentCaseId)[0] || {}).CaseName
            resolve()
          } else {
            // 如果没有案场
            wx.getLocation({
              type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
              success: function (res) {
                that.latitude = res.latitude // 纬度，浮点数，范围为90 ~ -90
                that.longitude = res.longitude // 经度，浮点数，范围为180 ~ -180。
                console.log('获取到位置 ->', that.latitude, that.longitude)
              },
              complete: function (res) {
                console.log(res)
                console.log('获取位置后, 不管成功与否', that.latitude, that.longitude)

                if(that.latitude && that.longitude ) {
                  for (let i = 0; i < that.CaseList.length; i++) {
                    let result = that.CaseList[i].Coordinate.split(",")
                    let latitude2 = parseFloat(result[0])
                    let longitude2 = parseFloat(result[1])
                    if (that.toolClass.getGreatCircleDistance(that.latitude, that.longitude, latitude2, longitude2) < 500) {
                      that.currentCaseId = that.CaseList[i].CaseId
                    }
                  }
                }

                if(!that.currentCaseId) {
                  that.currentCaseId = ((that.CaseList || [])[0] || {}).CaseId
                }

                that.setDefaultCase(that.currentCaseId)
                resolve()
              },
            })
          }
        }).catch((err) => {
          console.log('微信初始化失败', err.message)
          if (hasSol) return
          hasSol = true

          // 如果已经存在案场
          if (!!this.bookcaseid) {
            this.setDefaultCase(this.bookcaseid)
          } else {
            this.setDefaultCase(((that.CaseList || [])[0] || {}).CaseId)
          }

          reject()
        })
      })
    },
    setDefaultCase(caseID) {
      this.setBookCase(caseID)
      this.caseId = caseID
      this.currentCaseId = caseID
      this.currentCaseName = (this.CaseList.filter(x => x.CaseId === caseID)[0] || {}).CaseName
    },
    selectCaseId () { // 选择案场
      if (this.currentCaseId !== this.caseId) {
        this.currentCaseId = this.caseId
        this.CaseList.map((item) => {
          if (item.CaseId === this.currentCaseId) this.currentCaseName = item.CaseName
        })
        this.setBookCase(this.caseId)
        this.page = 1
        this.init()
      }
      this.showDialog = false
    },
    init () { // 初始化
      this.getBookType({
        caseid: this.currentCaseId,
        page: 1,
        pagesize: 10,
      })
      // this.getRecommendBook({
      //   caseid: this.currentCaseId,
      //   page: this.page,
      //   pagesize: this.pagesize,
      // })
      this.$nextTick(() => {
        this.onInfinite()
      })
    },
    onInfinite () {
      this.getMineBook({
        page: 1,
        pagesize: 1000,
      })
      let more = this.$el.querySelector('.load-more')
      this.getRecommendBook({
        caseid: this.currentCaseId,
        page: this.page,
        pagesize: this.pagesize,
      }).then((res) => {
        this.page++
        res.list = res.list || []
        if (res.list.length < res.pageSize) {
          more.style.display = 'none'// 隐藏加载条
          this.scrollData.noFlag = true
        } else {
          more.style.display = 'none'// 隐藏加载条
        }
      })
    },
    appointmentBook (id) { // 预约图书
      this.reserveBookId = id
      this.showAppointmentDialog = true
    },
    sureAppointmentBook () { // 确定预约图书
      this.reserveBook({
        bookid: this.reserveBookId,
      }).then(() => {
        this.updateRecommendBookLeftNum(this.reserveBookId)
        this.getMineBook({
          page: 1,
          pagesize: 1000,
        })
      })
      this.showAppointmentDialog = false
    },
    navClick (item) { // 点击nav
      this.$router.push({ name: 'booksList', query: { type: item.BookTypeId, caseid: this.currentCaseId } })
    },
    moreNav () {
      this.$router.push({ name: 'libraryNavList', query: { caseid: this.currentCaseId } })
    },
    mineBookStatus (item) {
      return ((this.mineBooks.list || []).filter(x => x.BookId === item.BookId && (x.BorrowStatus == '4' || x.BorrowStatus == '1' || x.BorrowStatus == '0'))[0] || {}).BorrowStatus
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
@import 'page.scss';
</style>
