const util = require('../../utils/util')
const api = require('../../config/api')

Page({
  data: {
		loading: false,
		isEdit: false, // 是否显示选择按钮
		selectList: [], // 已选中收藏id

    collectList: [],
    page: 1,
    totalPages: 1
  },

  onShow: function() {
    this.getCollectList()
	},
	
	pullDownRefresh() {
    this.setData({ page: 1, loading: true })
    this.getCollectList()
    this.setData({ loading: false })
	},

	// 加载更多
	scrolltolower() {
		if (this.data.totalPages > this.data.page) {
			this.setData({ page: this.data.page + 1 })
			this.getCollectList()
		} else util.showToast('已经到底了')
	},

	getCollectList() {
		util.showLoad('加载中')
		util.request(api.CollectList, { page: this.data.page, type: 0 }).then(res => {
			util.hideLoad()
			if (res.errno === 0) {
				const list = res.data.collectList.map(item => {
					item.picUrl = item.picUrl.split(',')
					return item
				})

				const collectList = this.data.page == 1 ? list : this.data.collectList.concat(list)
				this.setData({ collectList, totalPages: res.data.totalPages })
			} else util.showErrorToast(res.errmsg)
		}).catch(() => {
			util.hideLoad()
			util.showErrorToast('网络连接失败')
		})
	},

	// 编辑
	toggleEdit() {
		this.setData({ isEdit: !this.data.isEdit, selectList: [] })
	},

	selectCollect({ detail }) {
		this.setData({ selectList: detail })
	},

	deleteCollect() {
		const { selectList } = this.data
		if (!selectList.length) return
		util.showLoad('加载中')
		util.request(api.CollectDelete, selectList, 'POST').then(res => {
			util.hideLoad()
			if (res.errno === 0) {
				this.setData({ isEdit: false })
				this.getCollectList()
			} else util.showErrorToast(res.errmsg)
		}).catch(() => {
			util.hideLoad()
			util.showErrorToast('网络连接失败')
		})
	},

	// 商品详情
  toDetail({ currentTarget }) {
		if (!this.data.isEdit) {
			const { id } = currentTarget.dataset
			wx.navigateTo({ url: `/packageGoods/detail/detail?obj=${JSON.stringify({ id })}` })
		}
	}
})