const Parse = getApp().Parse
const company = getApp().globalData.company
const dateF = require('../../../utils/date')
const req = require('../../utils/request')
const colorChange = require("../../utils/color");
// const activeColor=getApp().globalData.activeColor
let {
	statusBarHeight
} = wx.getSystemInfoSync();
statusBarHeight = Math.abs(statusBarHeight)
let custom = wx.getMenuButtonBoundingClientRect();
let customBarHeight = custom.bottom + custom.top - statusBarHeight;
customBarHeight = Math.abs(customBarHeight)
Page({
	data: {
		status: 1,
		active: null,
		activeColor: null,
		goodsList: [],
		currentGoods: null,
		type: null, // 订单类型
		themeColor: '',
		themeRGB: [],
		customBarHeight,
	},
	onChange(e) {
		console.log(e)
		console.log(e.detail)
		let {
			index
		} = e.detail
		this.setData({
			active: index
		})
		console.log(index, e.detail)
		let switchFn = {
			'0': 0,
			'1': 100,
			'2': 200,
			'3': 300,
			'4': 400
		}
		this.setData({
			goodsList:[]
		})
		this.queryShopOrder(switchFn[index])
	},

	//删除
	delOrder(e) {
		console.log(e);
		let {
			index
		} = e.currentTarget.dataset
		let {
			goodsList
		} = this.data
		let _this = this
		wx.showModal({
			title: '',
			content: '你确定删除该订单吗?',
			showCancel: true,
			cancelText: '取消',
			cancelColor: '#000000',
			confirmText: '确定',
			confirmColor: '#3CC51F',
			success: async (result) => {
				if (result.confirm) {
					await this.upDel(goodsList[index].objectId)
					goodsList.splice(index, 1)
					_this.setData({
						goodsList
					})
					wx.showToast({
						title: '已取消',
						icon: 'none',
						image: '',
						duration: 1500,
					});
				}
			},
			fail: () => { },
			complete: () => { }
		});
	},
	async upDel(id) {
		let ShopOrder = new Parse.Query('Order')
		let order = await ShopOrder.get(id)
		if (order && order.id) {
			console.log(order);
			await order.destroy()
		}
	},
	// 查看物流
	onShowExpress(e) {
		let { item } = e.currentTarget.dataset
		console.log(item)
		if (item?.trackingNumber) {
			let url = `/common-page/pages/nova-express/index?num=${item.trackingNumber}&com=${item.expressCompany && item.expressCompany.code}`
			wx.navigateTo({
				url: url,
			});
			return
		}
		wx.showToast({
			title: '暂无物流信息',
			icon: 'error',
			image: '',
			duration: 1500,
			mask: false,
		});
	},

	//确认收货
	receipt(e) {
		console.log(e);
		let {
			index
		} = e.currentTarget.dataset
		let {
			goodsList
		} = this.data
		let _this = this
		wx.showModal({
			title: '',
			content: '是否确认收货',
			showCancel: true,
			cancelText: '取消',
			cancelColor: '#000000',
			confirmText: '确定',
			confirmColor: '#3CC51F',
			success: async (result) => {
				if (result.confirm) {
					await _this.upOk(goodsList[index].objectId)
					wx.showToast({
						title: '已收货',
						icon: 'none',
						image: '',
						duration: 1500,
					});
				}
			},
			fail: () => { },
			complete: () => { }
		});
	},
	async upOk(id) {
		let {
			active
		} = this.data
		let ShopOrder = new Parse.Query('Order')
		let order = await ShopOrder.get(id)
		if (order && order.id) {
			order.set("status", '400')
			await order.save()
			let e = {
				detail: active
			}
			this.onChange(e)
		}
	},


	toUrl(e) {
		let {
			url
		} = e.currentTarget.dataset
		wx.navigateTo({
			url: url,
		});
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad:async function (options) {
		//测试数据
		console.log(getApp().globalData.activeColor);
		let status = options.status ? Number(options.status) : 0
		let type = options.type;
		let themeColor = options.themeColor || getApp().globalData.activeColor;
		let titleColor = getApp().globalData.titleColor;
		console.log(status, 11111)
		this.setData({
			status: status,
			type,
			themeColor,
			titleColor
		})
		console.log(titleColor);
		themeColor && this.changeTheme()
		let switchFn = {
			'100': 1,
			'200': 2,
			'300': 3,
			'400': 4
		}
		
		let active = switchFn[status] ? switchFn[status] : 0
		await this.queryShopOrder(status)
		this.setData({
			active: active
		})
	},
	async reqSql() {
		let user = Parse.User.current().id
		let type = this.data.type;

		let sql = `select sr."objectId",sr.name,sr.price,sr.count,sr."createdAt",sr.status,
            gd.desc,gd.image
            from "ShopOrder" as sr
            join "ShopGoods" as gd
            on gd."objectId" = sr."goods"
            where sr.user = '${user}' and sr.type = '${type}'
            and (sr.status = 400 or sr.status = 800)`
		let res = await req.customSQL(sql)
		console.log(res);
		let goodsList = res.reduce((total, item) => {
			item.orderTime = dateF.formatTime("YYYY-mm-dd HH:MM:SS", item.createdAt)
			total.push(item)
			return total
		}, [])
		this.setData({
			goodsList: goodsList
		})

	},

	async queryShopOrder(status) {
		let user = Parse.User.current()
		let type = this.data.type;
		let ShopOrder = new Parse.Query('Order')
		ShopOrder.equalTo('company', company)
		ShopOrder.equalTo('user', user.id)
		ShopOrder.equalTo('type', 'goods')
		ShopOrder.include('targetObject')
		ShopOrder.descending('createdAt')
		ShopOrder.limit(6)
		ShopOrder.skip(this.data.goodsList.length)
		if (status != 0 && status) {
			ShopOrder.equalTo('status', String(status))
		}
		if (type) {
			ShopOrder.equalTo('type', type)
		}
		let orders = await ShopOrder.find()
		if (orders && orders.length > 0) {
			let orderJSON = this.data.goodsList ?  this.data.goodsList : []
			orders.forEach(order => {
				let orderObj = order.toJSON()
				orderObj.orderTime = dateF.formatTime("YYYY-mm-dd HH:MM:SS", orderObj.createdAt)
				orderJSON.push(orderObj)
			})
			this.setData({
				goodsList: orderJSON
			})
			console.log(this.data.goodsList)
			
		} else {
			let orderJSON = this.data.goodsList ?  this.data.goodsList : []
			this.setData({
				goodsList: orderJSON
			})
		}
	},


	showPay(e) {
		let item = e.currentTarget.dataset.item
		let id = item.objectId
		console.log(id);
		let specMap = e.currentTarget.dataset.specMap ? e.currentTarget.dataset.specMap : null
		wx.navigateTo({
			url: `/nova-shop/pages/shop-goods/pay/index?id=${id}&specMap=${specMap}&count=${item.count}`
		});
	},
	//支付
	async acceptResult(e) {
		let that = this
		let {
			params,
			no
		} = e.detail;
		that.setData({
			show: false
		})
		try {
			if (params == "ok") {
				wx.showLoading({
					title: "处理中",
					mask: true
				});
				let shopOrder = new Parse.Query("Order")
				let isOrder = await shopOrder.get(this.data.PayId)
				if (isOrder && isOrder.id) {
					isOrder.set('isPay', true)
					isOrder.set('status', '200')
					let order = await isOrder.save()
					if (order && order.id) {
						wx.hideLoading();
						wx.showToast({
							title: "支付成功",
							icon: "success",
							duration: 1500,
						});
						// 存储云仓
						if (order.get('giftList') && order.get('giftList').length > 0) {
							order.get('giftList').forEach(li => {
								if (li.type == 'stock') {
									that.creatShopStock(li, order.id)
								}
								if (li.type == 'agentlevel') {
									that.updateUserAgent(li)
								}
							})
						}
						// 更换经销商等级
						wx.navigateTo({
							url: "/nova-zhiliang/pages/my/myOrder/index",
						});
					} else {
						wx.showToast({
							title: "支付成功, 订单状态修改失败,请联系客服",
							icon: "error",
							duration: 1500,
						});
					}
				}
			} else {
				wx.hideLoading();
				this.setData({
					show: false
				})
			}
		} catch (error) {
			wx.showToast({
				title: "支付失败",
				icon: "error",
				duration: 1500,
			});
			wx.hideLoading()
		}
	},

	//修改地址    
	modify(e) {
		console.log(e)
		let id = e.currentTarget.dataset.item.objectId
		wx.navigateTo({
			url: "/nova-zhiliang/pages/my/myOrder/order-detail/index?id=" + id
		})
	},
	//催单
	reminder() {
		wx.showToast({
			title: '催单成功',
			icon: 'success',
			duration: 2000,
		});
	},

	//查看物流
	logistics(e) {
		let {
			item
		} = e.currentTarget.dataset
		console.log(item);
		this.setData({
			showExpress: true,
			express: item.express
		})
	},
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {

	},
	changeTheme() {
		let themeColor = this.data.themeColor;
		console.log(themeColor);
		let colorRgb = colorChange.hexToRgb(themeColor); // 十六进制转rgb
		console.log(colorRgb);
		let {
			r,
			g,
			b
		} = colorRgb;
		this.setData({
			themeRGB: [r, g, b]
		})
	},
	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {
		let switchFn = {
			'0': 0,
			'1': 100,
			'2': 200,
			'3': 300,
			'4': 400
		}
		let active = this.data.active
		console.log(111)
		this.queryShopOrder(switchFn[active])
	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function () {

	}
})