const _Http = getApp().globalData.http,
	getTime = require("../../utils/getTime");
let sa_quotedpriceid = 0,
	quotedpricenotes = [],
	address = "";

Page({
	data: {
		loading: false,
		subLoading: false,
		sa_quotedpriceid: 0,
		showAll: false,
		accessory: true,
		form: [{
			label: "客户",
			error: false,
			errMsg: "",
			type: "route",
			url: "/packageA/contract/add/setclient/select",
			value: "",
			params: {
				"id": 20220920083901,
				"content": {
					"pageNumber": 1,
					"pageSize": 20,
					"where": {
						"condition": "",
						"type": 19,
						"sa_projectid": ""
					}
				},
			},
			interrupt: true,
			query: "&radio=true&idname=sys_enterpriseid",
			placeholder: "选择客户",
			valueName: "sys_enterpriseid",
			checking: "base",
			required: true
		}, {
			label: "报价金额(元)",
			error: false,
			errMsg: "",
			type: "digit",
			value: "",
			placeholder: "请填写金额",
			valueName: "quotedpriceamount",
			checking: "twoDecimalPlaces",
			required: true
		}, {
			label: "产品系列",
			error: false,
			errMsg: "",
			type: "option",
			optionNmae: "itemtype",
			optionType: "checkbox", //复选   radio 单选
			value: "",
			placeholder: "请选择产品系列",
			valueName: "itemtype",
			checking: "base",
			required: true
		},  {
			label: "报价日期",
			error: false,
			errMsg: "",
			type: "date",
			value: getTime.formatTime(new Date(), '-').split(' ')[0] + "",
			placeholder: "报价日期",
			valueName: "billdate",
			checking: "base",
			required: false
		}, {
			label: "有效期",
			error: false,
			errMsg: "",
			type: "dateRange",
			value: [getTime.formatTime(new Date(), '-').split(' ')[0] + "", getTime.formatTime(new Date(Date.now() + (86400000 * 30)), '-').split(' ')[0] + ""],
			placeholder: ['生效日期', '截止日期'],
			valueName: "invaliddate",
			checking: "base",
			required: true
		}, {
			label: "备注",
			error: false,
			errMsg: "",
			type: "textarea",
			value: "",
			placeholder: "报价单说明",
			valueName: "remarks",
			required: false, //必填
		}],
		disabled: true
	},
	changeState({
		detail
	}) {
		this.setData({
			loading: detail,
			subLoading: detail
		})
	},
	onLoad(options) {
		sa_quotedpriceid = 0;
		quotedpricenotes = [];
		address = "";
		if (options.data) {
			let data = JSON.parse(options.data);
			let form = this.data.form;

			sa_quotedpriceid = data.sa_quotedpriceid || 0;
			quotedpricenotes = data.quotedpricenotes || [];
			address = data.address || "";

			data.sys_enterpriseid = [data.enterprisename, [data.sys_enterpriseid]];
			form = form.map(v => {
				if (v.valueName == "invaliddate") {
					v.value = [data.begdate, data.enddate]
				} else {
					v.value = data[v.valueName] || "";
					if (v.valueName == "quotedpriceamount") v.disabled = data.iseditamount == 0
				}
				return v
			})
			form.splice(1, 0, {
				label: "联系人",
				error: false,
				errMsg: "",
				type: "route",
				url: "/packageA/select/contacts/select",
				value: [data.contactsname, [data.sys_phonebookid]],
				params: {
					"id": "20240614151004",
					"version": 1,
					"content": {
						nocache: true,
						"sys_enterpriseid": data.sys_enterpriseid[1][0],
						sa_projectid: 0,
						"where": {
							"condition": "",
							"workaddress": 0
						}
					}
				},
				query: "&radio=true&idname=sys_phonebookid",
				placeholder: "选择客户联系人",
				valueName: "sys_phonebookid",
				checking: "base",
				required: true
			});
			form.splice(form.findIndex(v => v.label == '备注'), 0, {
				label: "业务员",
				error: false,
				errMsg: "",
				type: "route",
				url: "/packageA/select/contacts/select",
				value: [data.name, [data.saler_hrid]],
				params: {
					"id": "20230306144402",
					"content": {
						nocache: true,
						"type": 1, //type:1客户2:项目
						"sys_enterpriseid": data.sys_enterpriseid[1][0],
						"where": {
							"condition": ""
						}
					}
				},
				query: "&radio=true&idname=hrid",
				placeholder: "选择业务员",
				valueName: "saler_hrid",
				checking: "base",
				required: true
			});
			this.setData({
				form,
				accessory: false,
				sa_quotedpriceid
			});
			this.selectComponent("#Form").confirm();
		} else {
			_Http.basic({
				"classname": "sysmanage.develop.optiontype.optiontype",
				"method": "optiontypeselect",
				"content": {
					"pageNumber": 1,
					"pageSize": 1,
					"typename": "itemtype",
					"parameter": {
						"siteid": wx.getStorageSync('siteP').siteid
					}
				},
			}).then(res => {
				console.log(res)
				if (res.code == 1 && res.data.length) {
					this.data.form[this.data.form.findIndex(v => v.label == '产品系列')].value = [res.data[0].value]
					this.setData({
						form: this.data.form
					})
				}
			})
		}
		getApp().globalData.Language.getLanguagePackage(this, '客户报价');
	},
	/* 打断处理form */
	interrupt(e) {
		let {
			data,
			form,
			temporary
		} = e.detail;
		if (temporary.item.value[0] == data.value[0]) return wx.navigateBack();
		temporary.item.value = data.value;

		if (temporary.item.valueName == "sys_enterpriseid") {
			//联系人
			let contacts = {
				label: "联系人",
				error: false,
				errMsg: "",
				type: "route",
				url: "/packageA/select/contacts/select",
				value: "",
				params: {
					"id": "20240614151004",
					"version": 1,
					"content": {
						nocache: true,
						"sys_enterpriseid": data.value[1][0],
						sa_projectid: 0,
						"where": {
							"condition": "",
							"workaddress": 0
						}
					}
				},
				query: "&radio=true",
				placeholder: "选择客户联系人",
				query: "&radio=true&idname=sys_phonebookid",
				valueName: "sys_phonebookid",
				checking: "base",
				required: true
			};
			form.splice(1, form.some(v => v.label == '联系人') ? 1 : 0, contacts);

			let hr = {
				label: "业务员",
				error: false,
				errMsg: "",
				type: "route",
				url: "/packageA/select/contacts/select",
				value: "",
				params: {
					"id": "20230306144402",
					"content": {
						nocache: true,
						"type": 1, //type:1客户2:项目
						"sys_enterpriseid": data.value[1][0],
						"where": {
							"condition": ""
						}
					}
				},
				query: "&radio=true&idname=hrid",
				placeholder: "选择业务员",
				valueName: "saler_hrid",
				checking: "base",
				required: true
			};
			_Http.basic({
				"id": "20230306144402",
				"content": {
					"nocache": true,
					"type": 1,
					"sys_enterpriseid": data.value[1][0],
					"where": {
						"condition": ""
					},
					"pageNumber": 1,
					"pageSize": 1,
				},
			}).then(res => {
				console.log('获取一个业务员', res)
				if (res.code == 1 && res.data.length) {
					hr.value = [res.data[0].name, [res.data[0].hrid]]
					if (form.some(v => v.label == '业务员')) {
						form.splice(form.findIndex(v => v.label == '备注') - 1, 1, hr);
					} else {
						form.splice(form.findIndex(v => v.label == '备注'), 0, hr);
					}
					this.setData({
						form
					})
				}
			})
			if (form.some(v => v.label == '业务员')) {
				form.splice(form.findIndex(v => v.label == '备注') - 1, 1, hr);
			} else {
				form.splice(form.findIndex(v => v.label == '备注'), 0, hr);
			}
		}
		form[temporary.index] = temporary.item;
		wx.navigateBack()
		this.setData({
			form
		})
	},
	/* 绑定媒体 */
	insertImgEdit({
		detail
	}) {
		this.handleFileLink(detail)
	},
	handleFileLink(attachmentids, ownertable = "temporary", ownerid = 1, data) {
		_Http.basic({
			"classname": "system.attachment.Attachment",
			"method": "createFileLink",
			"content": {
				ownertable,
				ownerid,
				usetype: 'default',
				attachmentids
			}
		}).then(res => {
			console.log('跟进记录绑定附件', res)
			if (res.code != '1') return wx.showToast({
				title: res.msg,
				icon: "none"
			})
			if (ownertable == 'temporary') {
				this.selectComponent("#Yl_files").handleFiles(res.data)
			} else {
				if (res.data.length) data.attinfos = res.data;
				this.changeItem(data)
			}
		})
	},
	changeItem(data) {
		this.setData({
			loading: false,
			subLoading: false
		})
		let pages = getCurrentPages(),
			page = pages[pages.length - 2];
		if (page.__route__ == 'packageA/offers/detail') {
			page.getDetail(true);
			wx.navigateBack()
		} else {
			if (['packageA/setclient/detail', 'packageA/publicCustomer/detail'].includes(page.__route__)) {
				let model = page.selectComponent("#Offers");
				model.getList(model.data.sys_enterpriseid, true);
			}
			wx.redirectTo({
				url: '/packageA/offers/detail?sa_quotedpriceid=' + data.sa_quotedpriceid
			})
		}

	},
	submit(e) {
		const {
			submit
		} = e.currentTarget.dataset;
		if (submit == 1) {
			this.setData({
				subLoading: true
			})
		} else {
			this.setData({
				loading: true
			})
		}
		let content = {
			...this.selectComponent("#Form").submit(),
			"sa_projectid": 0, //项目id
			projectname: "",
			sa_quotedpriceid,
			quotedpricenotes,
			address
		};
		content.sys_enterpriseid = content.sys_enterpriseid[1] ? content.sys_enterpriseid[1][0] : 0;
		content.sys_phonebookid = content.sys_phonebookid[1] ? content.sys_phonebookid[1][0] : 0;
		content.saler_hrid = content.saler_hrid[1] ? content.saler_hrid[1][0] : 0;
		content.discountrate = ''
		content.begdate = content.invaliddate[0];
		content.enddate = content.invaliddate[1];
		delete(content.invaliddate)
		_Http.basic({
			"id": 20221020164803,
			"version": 1,
			content
		}).then(res => {
			console.log("添加客户报价单", res)
			wx.showToast({
				title: res.code != '1' ? res.msg : getApp().globalData.Language.getMapText('保存成功'),
				icon: "none",
				mask: true
			})
			if (res.code != '1') return this.setData({
				loading: false,
				subLoading: false
			});
			if (submit == 1) {
				_Http.basic({
					"id": 20221020165303,
					"version": 1,
					"content": {
						"sa_quotedpriceid": res.data.sa_quotedpriceid
					}
				}).then(s => {
					console.log("提交报价单", s)
					getApp().globalData.Language.showToast(s.code == '1' ? "创建成功" : s.msg)
					try {
						let attachmentids = this.selectComponent("#Yl_files").getFiles().attachmentids;
						if (attachmentids.length) {
							this.handleFileLink(attachmentids, 'sa_quotedprice', res.data.sa_quotedpriceid, res.data)
						} else {
							setTimeout(() => {
								this.changeItem(res.data)
							}, 500)
						}
					} catch (error) {
						setTimeout(() => {
							this.changeItem(res.data)
						}, 500)
					}
				})
			} else {
				try {
					let attachmentids = this.selectComponent("#Yl_files").getFiles().attachmentids;
					if (attachmentids.length) {
						this.handleFileLink(attachmentids, 'sa_quotedprice', res.data.sa_quotedpriceid, res.data)
					} else {
						setTimeout(() => {
							this.changeItem(res.data)
						}, 500)
					}
				} catch (error) {
					setTimeout(() => {
						this.changeItem(res.data)
					}, 500)
				}
			}
		})
	},
	// 是否显示全部
	onChange({
		detail
	}) {
		this.setData({
			showAll: detail
		})
	},
	/* 表单必填项是否完成 */
	onConfirm({
		detail
	}) {
		this.setData({
			disabled: detail
		})
	}
})