import Request from '../utils/request.js';
import { ElMessage } from 'element-plus';
import { setNotLoggedIn } from '@/utils/auth';
import router from '../router';
import store from '../store';
import FileSaver from 'file-saver';
import XLSX from 'xlsx';
import { getLodop } from '@/utils/print.js';
const http = new Request();

// 日期转换
export const transformTimestamp = (timestamp) => {
	const date = new Date(timestamp);
	const Y = date.getFullYear() + '-';
	const M =
		(date.getMonth() + 1 < 10
			? '0' + (date.getMonth() + 1)
			: date.getMonth() + 1) + '-';
	const D =
		(date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + '  ';
	const h =
		(date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
	const m =
		(date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) +
		':';
	const s =
		date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds(); // 秒
	const dateString = Y + M + D;
	return dateString;
};

// 根据key值获取value
export const getObjValue = (arr, thekey) => {
	let thevalue = '';
	for (let key in arr) {
		if (key === thekey) {
			thevalue = key;
			thevalue = arr[key];
			return thevalue;
		}
	}
};
// 根据数据集合id，去查找对应的名称（一般结构是 id --name type存在是防止数据结构不同获取名称的拓展,暂时还没什么用途）
export const getListIdByName = (arr, id, type) => {
	let datalist = [];
	if (arr && arr.length > 0) {
		datalist = arr.filter((it) => {
			return it.id === id;
		});
		if (datalist && datalist.length > 0) {
			return datalist[0].name;
		} else {
			return '';
		}
	}
};
export const theUnitSet = (list, id) => {
	// 修改标题
	if ((id || id == '0' || id == 0) && list && list.length > 0) {
		return list.filter((i) => {
			return i.id === id;
		}).length > 0
			? list.filter((i) => {
					return i.id === id;
			  })[0].name
			: '';
	} else {
		return '';
	}
};

export const getStatusTypeQuery = (url, id, type, query) => {
	if (type && type === 'post') {
		if (id) {
			return http
				.showLoading(false)
				.post(url, query)
				.then((res) => {
					if (res.status === 200) {
						return res.data;
					} else {
						return [];
					}
				});
		}
	}
};

// 获取各种状态
export const getStatusType = (url, id, type) => {
	// 获取状态
	if (type && type === 'post') {
		// POST
		if (id) {
			if (url === 'SysConfig/GetDept/') {
				return http
					.showLoading(false)
					.post(url + id)
					.then((res) => {
						if (res.status === 200) {
							return res.data;
						} else {
							return [];
						}
					});
			} else {
				return http
					.showLoading(false)
					.post(url + id)
					.then((res) => {
						if (res.status === 200) {
							return res.data;
						} else {
							return [];
						}
					});
			}
		}
	} else {
		// GET
		if (id) {
			return http
				.showLoading(false)
				.get(url + id)
				.then((res) => {
					if (res.status === 200) {
						return res.data;
					} else {
						return [];
					}
				});
		} else {
			return http
				.showLoading(false)
				.get(url)
				.then((res) => {
					if (res.status === 200) {
						return res.data;
					} else {
						return [];
					}
				});
		}
	}
};

// 获取本位币
export const getBaseCurrency = (arr, val) => {
	for (let index = 0; index < arr.length; index++) {
		if (arr[index].id === val) {
			return arr[index].standardCoinId;
		}
	}
};

// 获取汇率
export const getTaxPrice = (localcurrId, url, settlecurrId) => {
	if (localcurrId && settlecurrId) {
		return http
			.showLoading(false)
			.post(url, {
				from: settlecurrId,
				to: localcurrId,
			})
			.then((req) => {
				if (req.status == 200) {
					if (req.data === 0) {
						return 1;
					} else {
						return req.data;
					}
				}
			});
	}
};

// 获取时间
export const getNowTime = () => {
	var date = new Date();
	var year = date.getFullYear();
	var month =
		date.getMonth() + 1 < 10
			? '0' + (date.getMonth() + 1)
			: date.getMonth() + 1;
	var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
	return year + '-' + month + '-' + day;
};

// 判断isNan
export const isNanValue = (value) => {
	if (value === 0) {
		return value;
	} else {
		if (!isNaN(value)) {
			return value;
		} else {
			return '';
		}
	}
};

export const adoptValGetInd = (val, url) => {
	if (val && url) {
		return http
			.showLoading(false)
			.get(url + val)
			.then((req) => {
				if (req.status == 200) {
					return req.data;
				}
			});
	} else {
		return '';
	}
};

export const moreEnpty = (val) => {
	if (val) {
		return val.toString().replace(/(^\s*)|(\s*$)/g, '');
	}
};
export const exporthandel = function (path, search) {
	if (search && path) {
		return http
			.showLoading(false)
			.post(path, search)
			.then((res) => {
				if (res.status === 200) {
					ElMessage.success(
						'导出成功！请前往[导出]-[导出管理]查看进度或下载文件'
					);
				}
			});
	}
};

//ljm---批量填充公共封装  页面数据  物料集合数据, 第几行  那个字段  要填充的字段
export const batchhandle = function (
	pagefromData,
	matterallCodelist,
	romIndex,
	columnkey,
	batcharry,
	diftag
) {
	if ((romIndex || romIndex === 0) && columnkey) {
		if (columnkey === 'customerStockId') {
			ElMessage.error('客户仓库不允许批量填充');
		}
		(diftag
			? pagefromData.product[0].details
			: pagefromData.details
		).forEach((it, index) => {
			if (index > romIndex) {
				if (
					columnkey !== 'materialId' &&
					columnkey !== 'specification'
				) {
					if (batcharry.indexOf(columnkey) !== -1) {
						it[columnkey] = (
							diftag
								? pagefromData.product[0].details
								: pagefromData.details
						)[romIndex][columnkey];
						if (columnkey === 'stockId') {
							it['stockManagerId'] = (
								diftag
									? pagefromData.product[0].details
									: pagefromData.details
							)[romIndex]['stockManagerId'];
							it['stockManagerName'] = (
								diftag
									? pagefromData.product[0].details
									: pagefromData.details
							)[romIndex]['stockManagerName'];
							it['stockerName'] = (
								diftag
									? pagefromData.product[0].details
									: pagefromData.details
							)[romIndex]['stockerName'];
							it['stockerId'] = (
								diftag
									? pagefromData.product[0].details
									: pagefromData.details
							)[romIndex]['stockerId'];
						}
					}
				} else {
					if (
						columnkey === 'materialId' ||
						columnkey === 'specification'
					) {
						matterallCodelist[index] = matterallCodelist[romIndex];
						let metterInfo = {};
						metterInfo = matterallCodelist[index].filter((res) => {
							return (
								(diftag
									? pagefromData.product[0].details
									: pagefromData.details)[romIndex]
									.materialId === res.id
							);
						})[0];
						it.materialId = metterInfo.id;
						it.materialName = metterInfo.name;
						it.materialNumber = metterInfo.number;
						it.specification = metterInfo.specifications;
						it.unitId = metterInfo.baseUnitId;
						it.bomId = metterInfo.bomId;
						it.is211 = metterInfo.is211;
						it.bomVersion = metterInfo.bomVersion;
						it.subUnitMultiple = metterInfo.subUnitMultiple;
						it.supplierId = metterInfo.defaultSupplierId;
						it.subUnitId = metterInfo.subUnitId;
					}
				}
			}
		});
	}
	return pagefromData;
};

function offline() {
	// mingpin.f2b211 http://login.ops.f2b211.com/api/   https://api.mingpin.f2b211.com/api/v1/Public/get/offline
	//let pathurl = `http://login.ops.f2b211.com/api/v1/Public/get/online?c=${localStorage.getItem(
	let companyId = localStorage.getItem('companyId');
	const pathurl = `https://proxy.ops.f2b211.com/api/v1/Public/get/offline?c=${companyId}`;
	//http://dev.proxy.ops.f2b211.com/api/
	//const pathurl = `https://login.ops.f2b211.com/api/v1/Public/get/offline?c=${companyId}`;
	fetch(pathurl, {
		method: 'GET',
		credentials: 'include',
		keepalive: true,
		headers: {
			Authorization: window.localStorage.getItem('userToken'),
		},
	}).then((r) => {
		console.log(r, '=========r===========');
		if (r) {
			http.post('Login/LoginOut').then((r) => {
				if (store && store.state && store.state.org) {
					store.state.org.orgId = null;
				}
				console.log(r.isSuccess, '=r.isSuccess=');
				if (r.isSuccess) {
					setTimeout(() => {
						router.push({
							path: '/login',
						});
						setNotLoggedIn();
						store.replaceState({});
						localStorage.removeItem('store');
						localStorage.removeItem('userToken');
						localStorage.clear();
					}, 500);
				}
			});
		}
	});
}
// ljm 退出公共方法
export const SigninOut = function (path, search) {
	offline();
};

// ljm 操作弹框的导出
export const htmlToExcel = function (dom, title) {
	var excelTitle = title ? title : '导出文件';
	var wb = XLSX.utils.table_to_book(document.querySelector('#' + dom));
	var wbout = XLSX.write(wb, {
		bookType: 'xlsx',
		bookSST: true,
		type: 'array',
	});
	try {
		FileSaver.saveAs(
			new Blob([wbout], {
				type: 'application/octet-stream',
			}),
			excelTitle + '.xlsx'
		);
	} catch (e) {
		if (typeof console !== 'undefined') console.log(e, wbout);
	}
	return wbout;
};

// jx 递归删除children[]
export const removeChildren = function (arr) {
	if (arr) {
		if (arr.length) {
			for (let i in arr) {
				if (arr[i].children && arr[i].children.length) {
					removeChildren(arr[i].children);
				} else {
					delete arr[i].children;
				}
			}
		}
	}
	return arr;
};

// jx 处理自定义搜索框返回结果
export const resultComMethods = function (
	result,
	fieldSale,
	fieldObj,
	tempObj,
	search
) {
	fieldSale = result.currVal;
	if (JSON.stringify(fieldObj) != '{}') {
		tempObj = JSON.parse(JSON.stringify(fieldObj));
		for (const key in fieldObj) {
			search[key] = fieldObj[key];
		}
	} else {
		for (const key in tempObj) {
			delete search[key];
		}
		tempObj = null;
	}
	if (fieldSale == undefined || fieldSale == '') {
		for (const key in tempObj) {
			delete search[key];
		}
		tempObj = null;
	}
	return {
		fieldSale,
		fieldObj,
		tempObj,
		search,
	};
};

// jx 监听自定义搜索
export const customChangeMethods = function (
	selfVal,
	otherO,
	otherT,
	key,
	keyRsf
) {
	if (selfVal == undefined) {
		selfVal = key;
	}
	if (selfVal !== '') {
		if (selfVal == otherO || selfVal == otherT) {
			selfVal = key;
			keyRsf += 1;
			ElMessage.error('不能重复选择!');
		}
	}
	return {
		selfVal,
		otherO,
		otherT,
		key,
		keyRsf,
	};
};

// jx 快粘贴处理
export const copyValueMethods = function (event, value) {
	let pastedText = undefined; // 定义变量
	let isPasteOneCol = false; // 锁
	let oldVal = value; // 记录当前的值
	if (event.clipboardData && event.clipboardData.getData) {
		// 获取复制内容
		pastedText = event.clipboardData.getData('Text');
	} else {
		pastedText = event.originalEvent.clipboardData.getData('Text');
	}
	let rows = pastedText.split('\r\n'); // 分割字符
	rows.forEach((el) => {
		if (el.indexOf('\t') !== -1) {
			// 判断是否多列
			isPasteOneCol = true;
		}
	});
	return {
		pastedText,
		isPasteOneCol,
		oldVal,
		rows,
	};
};

// jx 日期比较
export const compareDateMethods = function (logintime, logouttime) {
	let arys1 = new Array();
	let arys2 = new Array();
	if (logintime != null && logouttime != null) {
		arys1 = logintime.split('-');
		logintime = new Date(arys1[0], parseInt(arys1[1] - 1), arys1[2]);
		arys2 = logouttime.split('-');
		logouttime = new Date(arys2[0], parseInt(arys2[1] - 1), arys2[2]);
	}
	return logintime > logouttime ? false : true;
};

// jx 销售物料编码携带数据
export const saleMatterGetMethods = function (
	matterDate,
	matterallCodelist,
	specificationalllist,
	details,
	ind,
	type
) {
	if (matterDate.length > 0) {
		matterallCodelist[ind] = matterDate;
		specificationalllist[ind] = matterDate;
		if (type === 'getDate') {
			if (details[ind] !== undefined) {
				matterallCodelist[ind].forEach((el) => {
					details[ind].materialId = el.id;
					details[ind].specificationId = el.id;
					details[ind].matterName = el.name;
					details[ind].unitId = el.baseUnitId;
					details[ind].paezOrgName = el.paezOrgName;
					details[ind].defaultSupplierName = el.defaultSupplierName;
					details[ind].taxRateNmae = el.taxRateNmae;
					details[ind].is211 = el.is211;
					details[ind].supplyChainName = el.supplyChain;
					details[ind].supplyChain = el.supplyChainKey;
					details[ind].lifeCycle = el.lifeCycleKey;
					details[ind].lifeCycleName = el.lifeCycle;
					details[ind].supplyOriginId = el.paezOrgId;
					details[ind].defaultSupplier = el.defaultSupplierId;
				});
			}
		}
	}
	return {
		matterallCodelist,
		specificationalllist,
		details,
	};
};
// ljm 快粘贴处理
export const quikecopyValue = function (event) {
	let pastedText =
		event.clipboardData && event.clipboardData.getData
			? event.clipboardData.getData('Text')
			: event.originalEvent.clipboardData.getData('Text'); // 定义变量
	let rows =
		pastedText && pastedText.split('\r\n')
			? pastedText.split('\r\n').filter((it) => {
					return it !== '';
			  })
			: [];
	return rows && rows.length > 0 ? rows : [];
};
// ljm 订单下载
export const orderDownload = function (api, contractId, filename) {
	if (contractId) {
		var xhr = new XMLHttpRequest(); // 用这种原生请求下载后端返回的二进制流打开就不会出现空白
		xhr.open(
			'get',
			import.meta.env.VITE_APP_API_BASEURL +
				import.meta.env.VITE_APP_API_VERSION +
				'/' +
				api +
				contractId,
			true
		);
		xhr.responseType = 'blob';
		xhr.setRequestHeader(
			'Authorization',
			localStorage.getItem('userToken')
		);
		xhr.onload = function () {
			const url = window.URL.createObjectURL(this.response);
			const link = document.createElement('a');
			link.style.display = 'none';
			link.href = url;
			link.setAttribute('download', filename);
			document.body.appendChild(link);
			link.click();
			document.body.removeChild(link);
		};
		xhr.send();
	} else {
		ElMessage.error('还不能下载！');
	}
};
// ljm 数据日期降序
export const dateData = function (property, bol) {
	//property是你需要排序传入的key,bol为true时是升序，false为降序
	return function (a, b) {
		var value1 = a[property];
		var value2 = b[property];
		if (bol) {
			// 升序
			return Date.parse(value1) - Date.parse(value2);
		} else {
			// 降序
			return Date.parse(value2) - Date.parse(value1);
		}
	};
};
//ljm打印
export const printPreview = function (s, pageName, arry) {
	LODOP = getLodop();
	var companyTilte =
		'<body>' +
		document.getElementById('companyTilte').innerHTML +
		'</body>';
	var str1 =
		'<body>' + document.getElementById('headhtml').innerHTML + '</body>';
	var str2 =
		'<body>' + document.getElementById('foothtml').innerHTML + '</body>';
	LODOP.PRINT_INIT('订单'); //打印初始化
	LODOP.ADD_PRINT_HTM(10, 0, 2100, 2970, companyTilte);
	LODOP.SET_PRINT_STYLEA(0, 'ItemType', 1);
	LODOP.ADD_PRINT_HTM(100, 0, 2100, 2970, str1);
	LODOP.ADD_PRINT_TABLE(
		pageName === '销售出库单'
			? 180
			: pageName === '发货通知单'
			? 190
			: pageName === '生产用料清单'
			? arry &&
			  arry.length > 0 &&
			  (arry[0].pSpecification.length > 45 ||
					arry[0].orderRemark.length.length > 45)
				? 235
				: 205
			: pageName === '委外用料清单'
			? 205
			: pageName === '分步式调出单'
			? 165
			: pageName === '采购入库单'
			? 130
			: 150,
		0,
		'100%',
		pageName === '生产用料清单' ? '70%' : '72%',
		document.getElementById('div2').innerHTML
	);
	LODOP.SET_PRINT_STYLEA(
		0,
		'Offset2Top',
		pageName === '生产用料清单' &&
			(arry[0].pSpecification.length > 45 ||
				arry[0].orderRemark.length.length > 45)
			? -150
			: -120
	); //设置次页偏移把区域向上扩
	LODOP.ADD_PRINT_HTM(40, 0, 2100, 2970, str2);
	//LODOP.SET_PRINT_STYLEA(0,"Top2Offset",-40); //这句可让次页起点向上移
	LODOP.SET_PRINT_STYLEA(0, 'LinkedItem', -1);
	LODOP.ADD_PRINT_HTM(
		1070,
		380,
		300,
		100,
		"<span tdata='pageNO' style='font-size:12px'>第##页</span>/<span tdata='pageCount' style='font-size:12px'>共##页</span>"
	);
	LODOP.SET_PRINT_STYLEA(0, 'ItemType', 1); //0代表文件
	if (s == 0) {
		LODOP.PRINT(); //直接打印
	}
	if (s == 1) {
		LODOP.PREVIEW(); //打印预览
	}
	if (s == 2) {
		LODOP.PRINT_SETUP(); //打印维护
	}
	if (s == 3) {
		LODOP.PRINT_DESIGN(); //打印设计
	}
};
export const newprintPreview1 = function (pageName, length, list) {
	LODOP = getLodop();

	LODOP.PRINT_INIT('订单'); //打印初始化
	for (let i = 0; i < length; i++) {
		var companyTilte =
			'<body>' +
			document.getElementById('companyTilte' + i).innerHTML +
			'</body>';
		var str1 =
			'<body>' +
			document.getElementById('headhtml' + i).innerHTML +
			'</body>';
		var str2 =
			'<body>' +
			document.getElementById('foothtml' + i).innerHTML +
			'</body>';
		if (i > 0) {
			LODOP.NewPage();
		}

		LODOP.ADD_PRINT_HTM(10, 0, '100%', '100%', companyTilte);
		LODOP.SET_PRINT_STYLEA(0, 'ItemType', 1); // 0代表文件
		LODOP.ADD_PRINT_HTM(105, 0, '100%', '100%', str1);
		var table_top = 242;
		var table_height = '70%';
		var fy_top = -150;

		if (pageName === '生产用料清单' || pageName === '委外用料清单') {
			var head1 = document.getElementById('head1').scrollHeight;
			var head2 = document.getElementById('head2').scrollHeight;
			if (head1 >= 55 && head2 >= 55) {
				table_top = 295;
				table_height = '67%';
				fy_top = -210;
			}
			if ((head2 == 38 && head1 == 55) || (head2 == 55 && head1 == 38)) {
				table_top = 270;
				table_height = '69%';
				fy_top = -186;
			}
			if (head1 == 38 && head2 == 38) {
				table_top = 248;
				table_height = '70%';
				fy_top = -164;
			}
			if ((head2 == 38 && head1 == 19) || (head2 == 19 && head1 == 38)) {
				table_top = 232;
				table_height = '70%';
				fy_top = -148;
			}
			if (head1 == 19 && head2 == 19) {
				table_top = 215;
				table_height = '74%';
				fy_top = -131;
			}
			if ((head1 == 19 && head2 == 55) || (head2 == 55 && head1 == 19)) {
				table_top = 258;
				table_height = '69%';
				fy_top = -174;
			}
		}

		if (list[i].length > 24) {
			LODOP.ADD_PRINT_TABLE(
				table_top,
				0,
				'100%',
				table_height,
				document.getElementById('div2' + i).innerHTML
			);
			LODOP.NewPage();
		} else {
			LODOP.ADD_PRINT_TABLE(
				table_top,
				0,
				'100%',
				table_height,
				document.getElementById('div2' + i).innerHTML
			);
		}

		LODOP.SET_PRINT_STYLEA(0, 'Offset2Top', fy_top); //设置次页偏移把区域向上扩
		LODOP.ADD_PRINT_HTM(40, 0, '100%', '100%', str2);
		LODOP.SET_PRINT_STYLEA(0, 'LinkedItem', -1);
		LODOP.ADD_PRINT_HTM(
			'98%',
			'48%',
			'100%',
			'2%',
			`<span tdata='pageNO' style='font-size:12px'>第##页</span>/<span tdata='pageCount' style='font-size:12px'>共##页</span>`
		);

		LODOP.SET_PRINT_STYLEA(0, 'ItemType', 1);
	}
	LODOP.PREVIEW(); //打印预览
};
//ljm打印
export const newprintPreview = function (pageName) {
	LODOP = getLodop();

	var companyTilte =
		'<body>' +
		document.getElementById('companyTilte').innerHTML +
		'</body>';
	var str1 =
		'<body>' + document.getElementById('headhtml').innerHTML + '</body>';
	var str2 =
		'<body>' + document.getElementById('foothtml').innerHTML + '</body>';
	LODOP.PRINT_INIT('订单'); //打印初始化
	LODOP.ADD_PRINT_HTM(10, 0, '100%', '100%', companyTilte);
	LODOP.SET_PRINT_STYLEA(0, 'ItemType', 1);
	LODOP.ADD_PRINT_HTM(105, 0, '100%', '100%', str1);
	var table_top = 242;
	var table_height = '70%';
	var fy_top = -150;
	if (pageName === '生产用料清单' || pageName === '委外用料清单') {
		var head1 = document.getElementById('head1').scrollHeight;
		var head2 = document.getElementById('head2').scrollHeight;
		if (head1 >= 55 && head2 >= 55) {
			table_top = 295;
			table_height = '67%';
			fy_top = -210;
		}
		if ((head2 == 38 && head1 == 55) || (head2 == 55 && head1 == 38)) {
			table_top = 270;
			table_height = '69%';
			fy_top = -186;
		}
		if (head1 == 38 && head2 == 38) {
			table_top = 248;
			table_height = '70%';
			fy_top = -164;
		}
		if ((head2 == 38 && head1 == 19) || (head2 == 19 && head1 == 38)) {
			table_top = 232;
			table_height = '70%';
			fy_top = -148;
		}
		if (head1 == 19 && head2 == 19) {
			table_top = 215;
			table_height = '74%';
			fy_top = -131;
		}
		if ((head1 == 19 && head2 == 55) || (head2 == 55 && head1 == 19)) {
			table_top = 258;
			table_height = '69%';
			fy_top = -174;
		}
	}
	if (
		pageName === '采购订单管理' ||
		pageName === '销售出库单' ||
		pageName === '发货通知单'
	) {
		table_top = 160;
		table_height = '70%';
		fy_top = -76;
	}
	if (
		pageName === '其他出库单' ||
		pageName === '委外领料单' ||
		pageName === '委外补料单' ||
		pageName === '委外退料单'
	) {
		table_top = 140;
		table_height = '75%';
		fy_top = -56;
	}
	if (pageName === '备料订单' || pageName === '送货单') {
		table_top = 160;
		table_height = '75%';
		fy_top = -76;
	}
	if (
		pageName === '生产入库单' ||
		pageName === '生产领料单' ||
		pageName === '生产补料单' ||
		pageName === '生产退料单'
	) {
		table_top = 84;
		table_height = '82%';
		fy_top = 0;
	}
	LODOP.ADD_PRINT_TABLE(
		table_top,
		0,
		'100%',
		table_height,
		document.getElementById('div2').innerHTML
	);
	LODOP.SET_PRINT_STYLEA(0, 'Offset2Top', fy_top); //设置次页偏移把区域向上扩
	LODOP.ADD_PRINT_HTM(40, 0, '100%', '100%', str2);
	LODOP.SET_PRINT_STYLEA(0, 'LinkedItem', -1);
	LODOP.ADD_PRINT_HTM(
		'98%',
		'48%',
		'100%',
		'2%',
		"<span tdata='pageNO' style='font-size:12px'>第##页</span>/<span tdata='pageCount' style='font-size:12px'>共##页</span>"
	);
	LODOP.SET_PRINT_STYLEA(0, 'ItemType', 1);
	LODOP.PREVIEW(); //打印预览
};

// jx 仓库 客户仓库
export const splitJointList = function (
	historyDataList,
	requestDataList,
	key,
	single,
	other
) {
	let tempList = [];
	if (
		key === 'stockList' ||
		key === 'outStockList' ||
		key === 'inStockList'
	) {
		if (single) {
			let contact = false;
			if (historyDataList[key] && historyDataList[key].length > 0) {
				requestDataList.filter((it) => {
					if (it.id === historyDataList[key][0].id) {
						contact = true;
					}
				});
			}
			if (!contact) {
				if (tempList.length === 0) {
					if (historyDataList[key]) {
						tempList.push(historyDataList[key][0]);
					}
				}
				tempList.forEach((element) => {
					if (element.id !== historyDataList[key][0].id) {
						tempList.push(historyDataList[key][0]);
					}
				});
				historyDataList.isCusHouse = true;
			}
		} else {
			historyDataList.forEach((el) => {
				let contact = false;
				if (el[key] && el[key].length > 0) {
					requestDataList.filter((it) => {
						if (it.id === el[key][0].id) {
							contact = true;
						}
					});
				}
				if (!contact) {
					if (tempList.length === 0) {
						if (el[key]) {
							tempList.push(el[key][0]);
						}
					}
					tempList.forEach((element) => {
						if (element && element.id !== el[key][0].id) {
							tempList.push(el[key][0]);
						}
					});
					el.isCusHouse = true;
				}
			});
		}
		return requestDataList.concat(tempList);
	} else if (
		key === 'customerStockList' ||
		key === 'inCustomerStockList' ||
		key === 'outCustomerStockList'
	) {
		if (single) {
			if (historyDataList[key]) {
				let contact = false;
				if (historyDataList[key] && historyDataList[key] > 0) {
					requestDataList.filter((it) => {
						if (it.id === historyDataList[key][0].id) {
							contact = true;
						}
					});
				}
				if (!contact) {
					if (tempList.length === 0) {
						if (historyDataList[key]) {
							tempList.push(historyDataList[key][0]);
						}
					}
					tempList.forEach((element) => {
						if (element.id !== historyDataList[key][0].id) {
							tempList.push(historyDataList[key][0]);
						}
					});
				}
			}
			let ifTempList = requestDataList.filter(
				(it) => it.id == tempList[0].id
			);
			if (ifTempList.length > 0) {
				return requestDataList;
			} else {
				return requestDataList.concat(tempList);
			}
		} else {
			if (other) {
				if (historyDataList[key]) {
					historyDataList.forEach((el) => {
						let contact = false;
						if (el[key] && el[key].length > 0) {
							requestDataList.filter((it) => {
								if (it.id === el[key][0].id) {
									contact = true;
								}
							});
						}
						if (!contact) {
							if (tempList.length === 0) {
								if (el[key]) {
									tempList.push(el[key][0]);
								}
							}
							tempList.forEach((element) => {
								if (element.id !== el[key][0].id) {
									tempList.push(el[key][0]);
								}
							});
							el.isCusHouse = true;
						}
					});
					return requestDataList.concat(tempList);
				} else {
					return requestDataList;
				}
			} else {
				if (historyDataList[key]) {
					historyDataList.forEach((el, ind) => {
						if (el[key] && el[key].length > 0) {
							let contact = false;
							if (requestDataList[ind]) {
								requestDataList[ind].filter((it) => {
									if (it.id === el[key][0].id) {
										contact = true;
									}
								});
								if (!contact) {
									if (!tempList[ind]) {
										tempList[ind] = [];
									}
									if (tempList[ind].length === 0) {
										tempList[ind].push(el[key][0]);
									} else {
										tempList[ind].forEach((element) => {
											if (element.id !== el[key][0].id) {
												tempList[ind].push(el[key][0]);
											}
										});
									}
									if (tempList[ind] !== undefined) {
										requestDataList[ind] = requestDataList[
											ind
										].concat(tempList[ind]);
									}
								}
							}
						}
					});
					return requestDataList;
				} else {
					return requestDataList;
				}
			}
		}
	}
};
//ljm仓库和旧仓库 + 数据去重
export const oldstocklist = function (data, type) {
	if (!type) {
		// 整合仓库和客户仓库旧数据集合data是明细数据
		let customerStockList = [];
		let stockList = [];
		if (data && data.length > 0) {
			data.forEach((it) => {
				if (it) {
					if (
						it.customerStockList &&
						it.customerStockList.length > 0
					) {
						customerStockList = customerStockList.concat(
							it.customerStockList
						);
					}
					if (it.stockList && it.stockList.length > 0) {
						stockList = stockList.concat(it.stockList);
					}
				}
			});
		}
		return {
			customerStockList: customerStockList,
			stockList: stockList,
		};
	} else {
		// 数据去重 data是去重的数字对象
		let obj = {};
		data = data.reduce((newArr, next) => {
			obj[next.id] ? '' : (obj[next.id] = true && newArr.push(next));
			return newArr;
		}, []);
		return data;
	}
};
//ljm 输入框，仅限数字输入，小数点后最多6位，小数点前最多8位
export const inputEnter = function (inputValue, empty) {
	inputValue = inputValue.replace(/[^\d.]/g, ''); // 清除"数字"和"."以外的字符 只能输入数字和小数点
	inputValue = inputValue.replace(/\.{2,}/g, '.'); // 不能连续输入两个及以上小数点
	inputValue = inputValue
		.replace('.', '$#$')
		.replace(/\./g, '')
		.replace('$#$', '.'); // 只保留第一个".", 清除多余的"."
	inputValue = inputValue.replace(/^(-)*(\d+)\.(\d\d\d\d\d\d).*$/, '$1$2.$3'); // 只能输入六位小数
	if (inputValue && inputValue.indexOf('.') < 0 && inputValue != '') {
		inputValue = parseFloat(inputValue);
		inputValue = inputValue + '';
		inputValue = inputValue.slice(0, 8);
	} // 如果没有小数点，首位不能为类似于 01、02的值
	// 输入过程中，只能输入六位小数且六位小数都为零，则清空小数点和后面的六个零（如果输入完成了只输入四个零，则在blur事件中处理）
	if (
		inputValue.indexOf('.') > 0 &&
		inputValue.length - inputValue.indexOf('.') > 6
	) {
		let str = inputValue.slice(inputValue.indexOf('.'), inputValue.length);
		if (str / 1 <= 0) {
			inputValue = inputValue.replace(str, '');
		}
	}
	if (inputValue.length > 15) {
		ElMessage.error(
			'仅限数字输入，小数点后最多6位，小数点前最多8位,请重新输入'
		);
		return empty ? '' : 0;
	} else {
		return inputValue;
	}
};

export const inputBlur = function (inputValue) {
	// 若小数点后面全是零，则清楚小数点和后面的零
	if (inputValue.indexOf('.') > 0) {
		let str = inputValue.slice(inputValue.indexOf('.'), inputValue.length);
		if (str / 1 <= 0) {
			inputValue = inputValue.replace(str, '');
		}
	}
};
