// pages/new-page/index.js
var urlPath = require('../../config.js');

Page({
	bindDateChange: function(e) {
		this.setData({
			[e.mark.type + '_date']: e.detail.value
		})
	},
	getStatus: function(e) {
		let block = this.data.newList[this.data.currentIndex].activity_list[e.mark.cindex]
		block.isOpen = !block.isOpen
		this.setData({
			newList: this.data.newList
		})
	},
	goIndex() {
		wx.reLaunch({
			url: '../index/index'
		});
	},
	/**
	 * 页面的初始数据
	 */
	data: {
		host: urlPath.host,
		icon: "/img/nav/menu1.png",
		capsuleParam: {},
		id: '',
		start_date: '',// '开始时间',
		end_date: '',// '结束时间',
		activeName: '',
		newList: [
			// {
			//   id:2,
			//   icon:'/img/nav/huaindex.png',
			//   iconActive:'/img/nav/hua.png',
			//   text:'低碳婚礼',
			// },
			// {
			//   id:1,
			//   icon:'/img/nav/cheindex.png',
			//   iconActive:'/img/nav/che.png',
			//   text:'地毯旅游',
			// },
			// {
			//   id:3,
			//   icon:'',
			//   icon:'/img/nav/huaindex.png',
			//   iconActive:'/img/nav/hua.png',
			//   text:'低碳居家',
			// },
		],
		currentIndex: 0,
		templateId: '', //当前选择碳中和计算模板Id

		primaryn_total_carbon: 0, //原总排放
		actual_total_carbon: 0, //实际总排放
		difference_carbon: 0, //总排放差值
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		this.getNewsData()
		// this.setData({
		//   capsuleParam: getApp().globalData
		// })
	},
	getNewsData: function() {
		var that = this
		wx.request({
			url: urlPath.getTemplate,
			// header: {
			//   'openid': wx.getStorageSync('openid')
			// },
			header: {
				'content-type': 'application/x-www-form-urlencoded'
			},
			method:"post",
			dataType: 'json', // 添加这个配置
			data: {
				appkey:urlPath.appkey
				// m:'dxtc',
				// f:'apiCarbonArticles',
				// page:'1',
				// size:'10'
			},
			success(res) {
				if (res.data.result == 'success') {

					let list = JSON.parse(res.data.data)
					list.forEach(function(item) {
						item.activity_list.forEach(function(itema, index) {
							if (index == 0) {
								itema.isOpen = true
							}
						})
					})
					that.setData({
						newList: list,
						templateId: JSON.parse(res.data.data)[that.data.currentIndex].id,
						icon: that.data.host + list[0].icon_img,
						activeName: JSON.parse(res.data.data)[that.data.currentIndex].name
					})

				} else {
					console.log(res.data.msg); //失败
				}
			}
		});
	},
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {
		if (typeof this.getTabBar === 'function' &&
			this.getTabBar()) {
			this.getTabBar().setData({
				selected: 2
			})
		}
		
	
		
	},

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

	},

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

	},

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

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

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

	},
	titleClick(e) {
		var that = this

		that.setData({
			//拿到当前索引并动态改变
			currentIndex: e.mark.index,
			id: 'm' + e.mark.index,
			templateId: e.mark.id,
			icon: that.data.host + that.data.newList[e.mark.index].icon_img,
			activeName: that.data.newList[e.mark.index].name
		})

		wx.nextTick(() => {
			that.calculation();
		})
	},
	formSubmit(e) {
		let values = e.detail.value
		let type = e.detail.target.dataset.type
		let ids = [],
			list = []
		Object.keys(values).forEach(function(item) { //获取所有活动id
			let id = item.split('_')[0]
			if (ids.indexOf(id) == -1) {
				ids.push(id)
			}
		})
		var flag = false;
		ids.forEach(function(item) { //获取所有所填选项数据
			if (values[item + '_planned'] == 0 && values[item + '_actual'] == 0) return
			let active = {
				calculator_id: item,
				planned_amount: values[item + '_planned'],
				actual_amount: values[item + '_actual'],
			}

			if ((active.planned_amount != "" && active.actual_amount != "") && active.planned_amount >=
				0 && active.actual_amount >= 0) {
				list.push(active)
			} else {

				flag = true;
				return false;
			}

		})
		if (flag) {
			wx.showToast({
				title: "请填写消费数据",
				icon: 'none',
				duration: 2000
			})
			return false;
		}

		if (list.length <= 0) {
			wx.showToast({
				title: "请填写消费数据",
				icon: 'none',
				duration: 2000
			})
			return false;
		}

		this.setResult(list, type)
		// wx.request({
		//   url: urlPath.postResult,
		//   header: {
		//     'content-type': 'application/x-www-form-urlencoded',
		//     'openid': wx.getStorageSync('openid')
		//   },
		//   method: 'post',
		//   dataType: 'json', // 添加这个配置
		//   data: {
		//     operate: true,
		//     template_id: this.data.templateId,
		//     start_date: this.data.start_date,
		//     end_date: this.data.end_date,
		//     items: JSON.parse(list)
		//   },
		//   success(res) {
		//     console.log(res)
		//   }
		// });

	},
	setResult: function(list, type, operate = 'normal') {
		var that = this
		wx.request({
			url: urlPath.postResult,
			header: {
				'content-type': 'application/x-www-form-urlencoded',
			},
			method: 'post',
			// dataType: 'json', // 添加这个配置
			data: {
				'openid': wx.getStorageSync('openid'),
				operate: operate,
				template_id: this.data.templateId,
				start_date: this.data.start_date,
				end_date: this.data.end_date,
				items: JSON.stringify(list)
			},
			success(res) {
				if (res.data.result == 'success') {
					// var neutralization = JSON.parse(res.data.data).neutralization
					// if (!!neutralization) {
					// 	wx.navigateTo({
					// 		url: '/pages/footprint/footprint',
					// 	})
					// 	return
					// }
					if (type == '1') {
						wx.navigateTo({
							url: '/pages/footprint/footprint?',
						})
					} else {
						wx.navigateTo({
							url: '/pages/gproduct/gproduct?id=' + JSON.parse(res.data.data)
								.id + "&&carbon=" + that.data.actual_total_carbon +
								"&&icon=" + that.data.icon,
						})
					}
				} else {
					if (res.data.code_str == 'replace') {
						wx.showModal({
							title: '提示',
							content: res.data.message != undefined ? res.data.message :
								"错误",
							success(item) {
								if (item.confirm) {
									that.setResult(list, type, 'replace')
								} else if (item.cancel) {}
							}
						})
					} else {
						wx.showToast({
							title: res.data.message != undefined ? res.data.message : "错误",
							icon: 'none',
							duration: 2000
						})
					}
				}
			}
		});
	},

	setPrimarynNmber: function(e) {
		var that = this;
		// console.log(e.currentTarget.dataset.activity_list_key)
		// console.log(e.currentTarget.dataset.factor_list_key)
		var currentIndex = that.data.currentIndex;
		var activity_list_key = e.currentTarget.dataset.activity_list_key;
		var factor_list_key = e.currentTarget.dataset.factor_list_key;
		var list = that.data.newList;
		list[currentIndex]["activity_list"][activity_list_key]["factor_list"][factor_list_key].primaryn = e
			.detail
			.value
		// console.log(list[currentIndex]["activity_list"][activity_list_key]["factor_list"][factor_list_key]);
		//console.log(that.data.currentIndex)
		that.setData({
			newList: list
		});
		wx.nextTick(() => {
			that.calculation();
		})

	},
	setActualNmber: function(e) {
		var that = this;
		// console.log(e.currentTarget.dataset.activity_list_key)
		// console.log(e.currentTarget.dataset.factor_list_key)
		var currentIndex = that.data.currentIndex;
		var activity_list_key = e.currentTarget.dataset.activity_list_key;
		var factor_list_key = e.currentTarget.dataset.factor_list_key;
		var list = that.data.newList;
		list[currentIndex]["activity_list"][activity_list_key]["factor_list"][factor_list_key].actual = e
			.detail
			.value;

		that.setData({
			newList: list
		});
		wx.nextTick(() => {
			that.calculation();
		})
	},
	//计算
	calculation: function() {
		var that = this;
		var list = that.data.newList[that.data.currentIndex];
		var primaryn_total_carbon = 0; //原总排放
		var actual_total_carbon = 0; //实际总排放
		var difference_carbon = 0; //总排放差值
		//console.log(list);
		for (var aa = 0; aa < list.activity_list.length; aa++) {
			for (var bb = 0; bb < list.activity_list[aa].factor_list.length; bb++) {
				if (list.activity_list[aa].factor_list[bb].primaryn != undefined &&
					list.activity_list[aa].factor_list[bb].actual != undefined) {
					var primaryn = list.activity_list[aa].factor_list[bb].primaryn;
					var actual = list.activity_list[aa].factor_list[bb].actual;

					primaryn_total_carbon += (list.activity_list[aa].factor_list[bb].factor_modulus *
						primaryn); //原总排放
					actual_total_carbon += (list.activity_list[aa].factor_list[bb].factor_modulus *
						actual); //实际总排放

				}

			}
		}
		that.setData({
			primaryn_total_carbon: Math.round(primaryn_total_carbon * 100, 2) / 100, //原总排放
			actual_total_carbon: Math.round(actual_total_carbon * 100, 2) / 100, //实际总排放
			difference_carbon: Math.round((primaryn_total_carbon - actual_total_carbon) * 100, 2) /
				100, //总排放差值
		})
	}
})