const _Http = getApp().globalData.http;
let figure = null; //免运费额度
import currency from "../../utils/currency";
Page({
	data: {
		hidePrice: wx.getStorageSync('hidePrice'),
		loading: true,
		sa_orderid: null,
		tabsActive: 0,
		tabsList: [{
			label: "产品明细",
			icon: "icon-tabchanpin",
			model: "#Product"
		}, {
			label: "附件",
			icon: "icon-tabfujian1",
			model: "#Yl_Attachment"
		}, {
			label: "订单进度",
			icon: "icon-tabcaozuojilu1",
			model: "#Progress"
		}]
	},
	onLoad(options) {
		this.setData({
			options: wx.getStorageSync('auth').worderform.options,
			sa_orderid: options.id,
			order_rebate_used: wx.getStorageSync('siteP').order_rebate_used,
			userrole: wx.getStorageSync('userrole')
		});
		this.getDetail(true);
	},
	/* 获取详情 */
	getDetail(init = false, show = true) {
		_Http.basic({
			"id": 20221108151302,
			"content": {
				nocache: true,
				"sa_orderid": this.data.sa_orderid
			}
		}, show).then(res => {
			console.log("订单详情", res)
			if (res.msg != '成功') return wx.showToast({
				title: res.msg,
				icon: "none"
			});
			let CNY = value => currency(value, {
				symbol: "￥",
				precision: 2
			}).format();
			let account = {
				name: "",
				text: ""
			};
			let accountclass = res.data.accountclass;
			if (accountclass.accountname) {
				account.name = accountclass.accountname
				account.text = `\n(余额:${CNY(accountclass.balance)},信用额度:${CNY(accountclass.creditquota)})`
			}
			this.setData({
				detail: res.data,
				loading: false,
				amount: CNY(res.data.amount),
				account
			});
			if (init) {
				this.partialRenewal(true)
				let content = wx.getStorageSync('userrole') == '业务员' ? {
					sys_enterpriseid: this.data.detail.sys_enterpriseid
				} : {};
				//业务员根据指定经销商的免运费
				_Http.basic({
					"id": 20220920084001,
					content
				}, false).then(res => {
					console.log("查询企业档案获取企业免邮额度", res)
					if (res.msg != '成功') return wx.showToast({
						title: res.msg,
						icon: "none"
					})
					figure = res.data.freefreightamount;
					this.setLogisticsMsg();
				})
			} else {
				this.setLogisticsMsg();
			}
		})
	},
	/* 免运费信息 */
	setLogisticsMsg() {
		let logistics = null;
		if (figure == -1) {
			logistics = '到付'
		} else if (figure == 0) {
			logistics = '预付'
		} else {
			let amount = this.data.detail.amount;
			logistics = amount >= figure ? '免运费' : '差' + currency(figure).subtract(amount).value + '元免运费';
		}
		this.setData({
			logistics
		})
	},
	/* 选择结算人 */
	selectAgent() {
		if (this.isEdit()) return;
		if (this.data.detail.type == '项目订单') return;
		wx.navigateTo({
			url: `/select/agent/index?params=${JSON.stringify({ 
				"id":20230104103702,
				"content": {
					"pageNumber": 1, 
					"pageTotal": 1, 
					"pageSize": 20,
					"where": {
						"condition": "",
						}, 
				}
			 })}&radio=true`,
		});
		getApp().globalData.handleSelect = this.setAgeant.bind(this);
	},
	/* 设置结算人 */
	setAgeant({
		item
	}) {
		let that = this;
		console.log("选择经销商", item)
		wx.showModal({
			title: '提示',
			content: `是否确认设置"${item.enterprisename}"为结算人？`,
			complete: (res) => {
				if (res.confirm) {
					let pay_enterpriseid = that.data.detail.pay_enterpriseid,
						sys_enterprise_financeid = that.data.detail.sys_enterprise_financeid,
						sa_accountclassid = that.data.detail.accountclass.sa_accountclassid;
					that.setData({
						"detail.pay_enterpriseid": item.sys_enterpriseid,
						"detail.sys_enterprise_financeid": item.finance[0] ? item.finance[0].sys_enterprise_financeid : 0,
						"detail.accountclass.sa_accountclassid": item.accounts[0] ? item.accounts[0].sa_accountclassid : 0,
					});
					that.changeDetail().then(s => {
						if (s.msg == '成功') {
							wx.showToast({
								title: '设置成功',
								icon: "none"
							});
							setTimeout(() => {
								wx.navigateBack();
								that.getDetail();
							}, 500)
						} else {
							that.setData({
								"detail.pay_enterpriseid": pay_enterpriseid,
								"detail.sys_enterprise_financeid": sys_enterprise_financeid,
								"detail.sa_accountclassid": sa_accountclassid
							});
						}
					})
				}
			}
		})
	},
	/* 选择财务信息 */
	selectFinance() {
		if (this.isEdit()) return;
		wx.navigateTo({
			url: `/select/finance/index?params=${JSON.stringify({ 
				"id":20221013160602,
				"content": {
					nocache:true,
					sys_enterpriseid:this.data.detail.sys_enterpriseid,
					"pageNumber": 1, 
					"pageTotal": 1, 
					"pageSize": 20,
					"where": {
						"condition": "",
					}, 
				}
			 })}&radio=true`,
		});
		getApp().globalData.handleSelect = this.setFinance.bind(this);
	},
	/* 设置财务信息 */
	setFinance({
		item
	}) {
		let that = this;
		console.log("设置财务信息", item)
		wx.showModal({
			title: '提示',
			content: `是否确认设置"${item.enterprisename}"为开票单位？`,
			complete: (res) => {
				if (res.confirm) {
					let sys_enterprise_financeid = that.data.detail.sys_enterprise_financeid;
					that.setData({
						"detail.sys_enterprise_financeid": item.sys_enterprise_financeid
					});
					that.changeDetail().then(s => {
						if (s.msg == '成功') {
							wx.showToast({
								title: '设置成功',
								icon: "none"
							});
							setTimeout(() => {
								wx.navigateBack();
								that.getDetail();
							}, 500)
						} else {
							that.setData({
								"detail.sys_enterprise_financeid": sys_enterprise_financeid
							});
						}
					})
				}
			}
		})
	},
	//tabs 切换
	tabsChange({
		detail
	}) {
		this.setData({
			tabsActive: detail
		});
		this.partialRenewal();
	},
	//局部数据更新 tabs
	partialRenewal(init = false) {
		let model = this.data.tabsList[this.data.tabsActive].model;
		if (model) {
			let Component = this.selectComponent(model),
				{
					total,
					pageNumber,
					pageTotal
				} = Component.data.content,
				id = this.data.detail.sa_orderid;
			if (total == null || init) {
				Component.getList(id, init);
			} else if (pageNumber <= pageTotal) {
				Component.getList(id, false);
			}
		}
	},
	onReachBottom() {
		this.partialRenewal();
	},
	/* 更新数据 */
	changeDetail() {
		let data = this.data.detail,
			content = {
				"sa_orderid": data.sa_orderid,
				"sys_enterpriseid": data.sys_enterpriseid, //订货企业id
				"sa_accountclassid": data.sa_accountclassid || 0, //营销账户类型ID
				"sa_brandid": data.sa_brandid, //品牌ID
				"sys_enterprise_financeid": data.sys_enterprise_financeid || 0, //合作企业财务信息ID（开票信息）
				//"sa_logiscompid": data.logiscomp.sa_logiscompid || 0, 物流公司档案ID
				"rec_contactsid": data.rec_contactsid || 0, //合作企业联系人表ID（收货信息）
				"type": data.type, //订单类型
				"typemx": data.typemx, // 明细分类，可选
				"remarks": data.remarks,
				"saler_hrid": data.saler_hrid, //销售人员hrid,业务员hrid
				"tradefield": data.tradefield, //必选
				"pay_enterpriseid": data.pay_enterpriseid, //结算单位
				"rebate_userate": data.accountclass.rebate_userate, //返利金使用比例
			};
		return new Promise((resolve, reject) => {
			_Http.basic({
				"id": 20221108111402,
				content
			}).then(res => {
				console.log("修改订单数据", res);
				if (res.msg != '成功') wx.showToast({
					title: res.msg,
					icon: "none"
				});
				resolve(res)
			})
		})
	},
	/* 修改订单备注 */
	changeRemarks(e) {
		let value = e.detail.value,
			remarks = this.data.detail.remarks,
			that = this;
		if (value == this.data.detail.remarks) return;
		wx.showModal({
			title: '提示',
			content: '是否确定修改订单备注？',
			complete: async (res) => {
				if (res.cancel) that.setData({
					"detail.remarks": remarks
				})
				if (res.confirm) {
					this.data.detail.remarks = value;
					let res = await that.changeDetail();
					that.setData({
						"detail.remarks": res.msg == '成功' ? value : remarks
					})
				}
			}
		})
	},
	/* 设置是否使用返利金 */
	changeRebateUsed() {
		if (this.isEdit()) return this.setData({
			detail: this.data.detail
		})
		let amount = (this.data.detail.order_rebate_userate * this.data.detail.amount).toFixed(2); //最大可用金额
		let rebatebalance = this.data.detail.rebatebalance; //返利金账户余额
		_Http.basic({
			"id": 20230218225002,
			"content": {
				"sa_orderid": this.data.sa_orderid, //订单金额
				"isused": this.data.detail.rebate_used == 1 ? 0 : 1, //是否使用
				"rebateamount": rebatebalance > amount ? amount : rebatebalance //返利金使用金额
			}
		}, false).then(res => {
			console.log('设置启用返利金', res)
			if (res.msg != '成功') {
				wx.showToast({
					title: res.msg,
					icon: "none"
				});
				this.setData({
					"detail.rebate_used": this.data.detail.rebate_used
				})
				return;
			}
			this.getDetail(true, false)
		})
	},
	/* 修改返利金 */
	setRebate_amount(e = 0) {
		let value = e.detail.value;
		let rebatebalance = this.data.detail.rebatebalance; //返利金账户余额
		value = value > rebatebalance ? rebatebalance : value;
		let amount = (this.data.detail.order_rebate_userate * this.data.detail.amount).toFixed(2); //最大可用金额
		_Http.basic({
			"id": 20230218225002,
			"content": {
				"sa_orderid": this.data.sa_orderid, //订单金额
				"isused": 1, //是否使用
				"rebateamount": value > amount ? amount : value
			}
		}, false).then(res => {
			console.log('设置返利金', res)
			if (res.msg != '成功') {
				wx.showToast({
					title: res.msg,
					icon: "none",
					mask: true
				});
				this.setData({
					"detail.accountclass.rebate_amount": this.data.detail.accountclass.rebate_amount
				})
			} else {
				this.setData({
					"detail.accountclass.rebate_amount": value
				})
				if (value > amount || amount == 0) wx.showToast({
					title: "返利金最大可使用" + amount + "元",
					icon: "none"
				})
				this.getDetail(true, false)
			}
		})
	},
	/* 删除订单 */
	deleteItem() {
		let that = this;
		wx.showModal({
			title: '提示',
			content: '是否确认删除订单？',
			complete: (res) => {
				if (res.confirm) _Http.basic({
					"id": 20221108152102,
					"content": {
						"sa_orderids": [
							that.data.sa_orderid
						]
					}
				}).then(s => {
					console.log("删除订单", s)
					if (s.msg != '成功') return wx.showToast({
						title: s.msg,
						icon: "none"
					});
					wx.showToast({
						title: `成功删除${that.data.detail.sonum}订单`,
						icon: "none"
					});
					setTimeout(() => {
						wx.navigateBack()
					}, 500)
				})
			}
		})
	},
	/* 特殊订单预提交 */
	presubmission(e) {
		let that = this;
		let isrecheck = e.currentTarget.dataset.isrecheck == 1;
		wx.showModal({
			title: '提示',
			content: `是否确认${isrecheck?'预提交订单':'撤回预提交'}？`,
			complete: (res) => {
				if (res.confirm) _Http.basic({
					"id": 20230331152503,
					"content": {
						isrecheck,
						sa_orderid: that.data.sa_orderid
					},
				}).then(s => {
					console.log("预提交订单", s)
					wx.showToast({
						title: s.msg != '成功' ? s.msg : isrecheck ? '预提交成功' : '撤回预提交成功',
						icon: "none"
					});
					if (s.msg == '成功') that.setData({
						"detail.status": isrecheck ? "预提交" : '新建'
					})
				})
			}
		})
	},
	/* 提交订单 */
	submit() {
		let that = this;
		wx.showModal({
			title: '提示',
			content: '是否确认提交订单？',
			complete: (res) => {
				if (res.confirm) _Http.basic({
					"id": 20221108153402,
					"content": {
						sa_orderid: that.data.sa_orderid
					},
				}).then(s => {
					console.log("提交订单", s)
					wx.showToast({
						title: s.msg != '成功' ? s.msg : '提交成功',
						icon: "none"
					});
					if (s.msg == '成功') that.setData({
						"detail.status": "提交"
					})
				})
			}
		})
	},
	/* 判断是否可以编辑 */
	isEdit() {
		if (this.data.detail.status != '新建') wx.showToast({
			title: '当前订单状态不可设置!',
			icon: "none"
		});
		return this.data.detail.status != '新建' || this.data.detail.type == '特殊订单';
	},
	/* 拷贝订单 */
	copyItem() {
		let item = this.data.detail;
		wx.showModal({
			title: '提示',
			content: `是否确认复制${item.type}“${item.sonum}”`,
			complete: (res) => {
				if (res.confirm) _Http.basic({
					"id": 20230102144502,
					"content": {
						"sa_orderid": item.sa_orderid
					}
				}).then(res => {
					console.log("复制订单", res)
					if (res.msg != '成功') return wx.showToast({
						title: res.msg,
						icon: "none"
					});
					wx.showModal({
						title: '提示',
						content: `${item.type}复制成功 是否立即前往`,
						complete: (s) => {
							if (s.confirm) wx.redirectTo({
								url: '/packageA/orderForm/detail?id=' + res.data.sa_orderid,
							})
						}
					})

				})
			}
		})
	},
	/* 设置项目订单品牌领域 */
	setBraned() {
		wx.navigateTo({
			url: './modules/setBrand/index?id=' + this.data.sa_orderid,
		})
	},
	onUnload() {
		let page = getCurrentPages().find(v => v.__route__ == "packageA/orderForm/index")
		if (page) page.updateList && page.updateList()
	}
})