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

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

    footprintList: []
  },

  onShow: function() {
    this.getFootprintList()
	},
	
	pullDownRefresh() {
    this.setData({ loading: true })
    this.getFootprintList()
    this.setData({ loading: false })
	},

	formatDate(date) {
		const month = new Date(date).getMonth() + 1
		const day = new Date(date).getDate()
		return month + '月' + day + '日'
	},

	getFootprintList() {
		util.showLoad('加载中')
		util.request(api.FootprintList).then(res => {
			util.hideLoad()
			if (res.errno === 0) {
				let footprintList = []
				for (const k in res.data) {
					if (Object.hasOwnProperty.call(res.data, k)) {
						const date = this.formatDate(k)
						const list = res.data[k].map(item => {
							item.picUrl = item.picUrl.split(',')
							return item
						})
						footprintList.push({ date, list })
					}
				}
				this.setData({ footprintList })
			} else util.showErrorToast(res.errmsg)
		}).catch(() => {
			util.hideLoad()
			util.showErrorToast('网络连接失败')
		})
	},

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

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

	deleteFootprint() {
		const { selectList } = this.data
		if (!selectList.length) return
		util.showLoad('加载中')
		util.request(api.FootprintDelete, selectList, 'POST').then(res => {
			util.hideLoad()
			if (res.errno === 0) {
				this.setData({ isEdit: false })
				this.getFootprintList()
			} 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 })}` })
		}
	}
})