/*
 * @Author: zzy 411037547@qq.com
 * @Date: 2022-05-09 18:09:42
 * @LastEditors: cclu 1106109051@qq.com
 * @LastEditTime: 2025-03-12 10:40:03
 * @FilePath: \cloud-platform\src\services\options\index.ts
 * @Description: 基础信息相关通用接口
 */

import type {
	TreeNodeDto,
	TreeSelectModel
} from '@/utils/format';
import {
	formateField,
	formateTreeField,
	getTreeSelectOption,
	tableList,
	wrapTreeNode
} from '@/utils/format';
import request from '@/utils/request';
import session from '@/utils/session';
import type { CommonTypeModel, FieldParamsModel } from './typings';
import useRequest from "@ahooksjs/use-request";
import moment from "moment/moment";
import { synchroBehaviorRecord } from "@/services/user";

/* 获取服务区列表 */
export async function getServerpartOption(ProvinceCode?: number | string,
	ServerpartCodes?: string, ShowWholePower?: boolean): Promise<{
		label: string; value: string | number
	}[]> {

	const serverpartOptions = session.get(`${ProvinceCode || ''}serverpartOptions`);
	if (serverpartOptions) {
		return serverpartOptions;
	}
	const data = await request(`/BaseInfo/GetServerpartDDL?ProvinceCode=${ProvinceCode || ''}&
		ServerpartCodes=${ServerpartCodes || ''}&ShowWholePower=${ShowWholePower || false}`, {
		method: 'GET',
	});
	if (data.Result_Code !== 100) {
		return [];
	}
	const options = formateField(data.Result_Data.List);
	session.set(`${ProvinceCode || ''}serverpartOptions`, options);
	return options;
}

/* 获取服务区门店列表 */
export async function getServerpartShopOpt(
	ServerpartId: string | number, ShowWholePower?: boolean): Promise<{
		label: string; value: string | number
	}[]> {

	const data = await request(`/BaseInfo/GetServerpartShopDDL?ServerpartId=${ServerpartId}&ShowWholePower=${ShowWholePower || false}`, {
		method: 'GET',
	});
	if (data.Result_Code !== 100) {
		return [];
	}
	const options = formateField(data.Result_Data.List);
	// session.set('serverpartOptions', options);
	return options;
}

export async function getFieldEnumTreeNoSession(params: any) {
	const data = await request(`/FrameWork/GetFieldEnumTree`, {
		method: 'GET',
		params,
	});
	if (data.Result_Code !== 100) {
		return [];
	}

	const options = wrapTreeNode(data.Result_Data.List);
	return [...options];
}


// 新枚举方法
export async function getFieldGetFieEnumList(params: any) {
	const data = await request(`/Dictionary/GetFieEnumList`, {
		method: 'GET',
		params,
	});
	if (data.Result_Code !== 100) {
		return [];
	}

	return data.Result_Data.List
}

/* 获取枚举列表 */
export async function getFieldEnumTree(params: FieldParamsModel) {
	const sessionName = `${params.sessionName ? params.sessionName : params.FieldExplainField}Tree`;
	const FieldExplain = session.get(sessionName);
	// if (FieldExplain && !params?.noStorge) {
	// 	return FieldExplain;
	// }

	const data = await request(`/FrameWork/GetFieldEnumTree`, {
		method: 'GET',
		params,
	});
	if (data.Result_Code !== 100) {
		return [];
	}

	const options = params.notformate ? formateTreeField(data.Result_Data.List) : wrapTreeNode(data.Result_Data.List);
	session.set(sessionName, options);
	// const oneList = getName(options)
	// session.set(`${sessionName}One`,oneList);
	return [...options];
}


/* 获取枚举列表 */
export async function getFieldEnum(params: FieldParamsModel): Promise<{ label: string; value: string | number }[]> {
	// const FieldExplain = session.get(params.sessionName ? params.sessionName : params.FieldExplainField);
	// if (FieldExplain) {
	// 	return [...FieldExplain];
	// }
	const data = await request(`/FrameWork/GetFieldEnumByField`, {
		method: 'GET',
		params,
	});
	if (data.Result_Code !== 100) {
		return [];
	}

	const options = params.notformate ? data.Result_Data.List : formateField(data.Result_Data.List);
	// session.set(params.sessionName ? params.sessionName : params.FieldExplainField, options);
	return options;
}

// 服务区树对象类
export interface ServerpartTree {
	label: string; // 名称 ,
	value: number; // 数值（对应数据表id） ,
	type: number; // 数据类型 , 0 区域 1 服务区
	ico: string; // 图标地址 ,
	children?: ServerpartTree[]
}

/* 获取服务区树形列表 */
export async function getServerpartTree(ProvinceCode?: number | string, ServerpartCodes?: string,
	ShowWholePower?: boolean, ShowSPRegion?: boolean, ShowRoyalty?: boolean | false, ShowCompactCount?: boolean | false, StatisticsType?: number): Promise<ServerpartTree[]> {
	if (!ShowWholePower) {
		const serverpartTree = session.get(`${ProvinceCode}`);
		if (serverpartTree) {
			return serverpartTree;
		}
	}
	// ShowRoyalty 无论传入什么都是false
	const data = await request(`/BaseInfo/GetServerpartTree?
		ProvinceCode=${ProvinceCode || ''}&ServerpartCodes=${ServerpartCodes || ''}&
		ShowWholePower=${ShowWholePower || false}&ShowWholePower=${ShowSPRegion || true}&
		ShowRoyalty=${false}&ShowCompactCount=${ShowCompactCount || false}&StatisticsType=${StatisticsType || ''}`, {
		method: 'GET',
	});

	console.log('djsiadjsakdjsalkjfoidhifsa', data);

	if (data.Result_Code !== 100) {
		return [];
	}

	if (!ShowWholePower) {
		session.set(`${ProvinceCode}`, data.Result_Data.List);
	}
	return data.Result_Data.List;
}


// 获取业主列表
export async function getOnwer(params?: any): Promise<CommonTypeModel[]> {
	const ownerUnit = session.get(`ownerUnit`);
	if (ownerUnit) {
		return ownerUnit;
	}
	const data = await request('/BaseInfo/BindingOwnerUnitDDL', {
		method: 'GET',
		params
	})

	if (data.Result_Code !== 100) {
		return []
	}
	session.set(`ownerUnit`, data.Result_Data.List);
	return data.Result_Data.List
}

// 获取商户列表无缓存
export async function getMerchantTreeNosessoin(params?: any) {
	const data = await request('/BaseInfo/BindingMerchantTree', {
		method: 'GET',
		params
	})

	if (data.Result_Code !== 100) {
		return []
	}

	const treeTable = wrapTreeNode(data.Result_Data.List);
	session.set(`MerchantTree`, treeTable);
	return [...treeTable];

}

// 获取商户列表
export async function getMerchantTree(params?: any) {
	const merchantTree = session.get(`MerchantTree`);
	if (merchantTree) {
		return merchantTree;
	}
	const data = await request('/BaseInfo/BindingMerchantTree', {
		method: 'GET',
		params
	})

	if (data.Result_Code !== 100) {
		return []
	}

	const treeTable = wrapTreeNode(data.Result_Data.List);
	session.set(`MerchantTree`, treeTable);
	return [...treeTable];

}

// 根据参数处查询门店 返回数据为区域+服务区+门店树格式
export async function getSPRegionShopTree(
	provinceCode?: number | string, ServerpartId?: string, ServerpartCodes?: string,
	ServerpartShopId?: string, BusinessState?: string, BusinessType?: string,
	ShowState?: boolean | false, ShowWholePower?: boolean | false,
	ShowShortName?: boolean | false, SortStr?: string, ShowRoyalty?: boolean | false, ShowUnpaidExpense?: boolean | false
): Promise<[]> {
	if (!ShowWholePower) {
		const serverpartShopTree = session.get(`${getSPRegionShopTree}`);
		if (serverpartShopTree) {
			return serverpartShopTree;
		}
	}

	const data = await request(`/BaseInfo/GetSPRegionShopTree?
		ProvinceCode=${provinceCode || ''}&ServerpartCodes=${ServerpartCodes || ''}&
		ServerpartId=${ServerpartId || ''}&ServerpartShopId=${ServerpartShopId || ''}&
		BusinessState=${BusinessState || ''}&BusinessType=${BusinessType || ''}&
		ShowState=${ShowState || false}&ShowWholePower=${ShowWholePower || false}&
		ShowShortName=${ShowShortName || false}&SortStr=${SortStr}&
		ShowRoyalty=${ShowRoyalty}&ShowUnpaidExpense=${ShowUnpaidExpense}`, {
		method: 'GET',
	})

	if (data.Result_Code !== 100) {
		return [];
	}

	const tree = await wrapTreeNode(data.Result_Data.List)

	if (!ShowWholePower) {
		session.set(`${getSPRegionShopTree}`, tree);
	}
	return tree;
}

// 去掉缓存的
// 根据参数处查询门店 返回数据为区域+服务区+门店树格式
export async function getSPRegionShopTreeUnCache(
	provinceCode?: number | string, ServerpartId?: string, ServerpartCodes?: string,
	ServerpartShopId?: string, BusinessState?: string, BusinessType?: string,
	ShowState?: boolean | false, ShowWholePower?: boolean | false,
	ShowShortName?: boolean | false, SortStr?: string, ShowRoyalty?: boolean | false, ShowUnpaidExpense?: boolean | false
): Promise<[]> {

	const data = await request(`/BaseInfo/GetSPRegionShopTree?
		ProvinceCode=${provinceCode || ''}&ServerpartCodes=${ServerpartCodes || ''}&
		ServerpartId=${ServerpartId || ''}&ServerpartShopId=${ServerpartShopId || ''}&
		BusinessState=${BusinessState || ''}&BusinessType=${BusinessType || ''}&
		ShowState=${ShowState || false}&ShowWholePower=${ShowWholePower || false}&
		ShowShortName=${ShowShortName || false}&SortStr=${SortStr}&
		ShowRoyalty=${ShowRoyalty}&ShowUnpaidExpense=${ShowUnpaidExpense}`, {
		method: 'GET',
	})

	if (data.Result_Code !== 100) {
		return [];
	}

	const tree = await wrapTreeNode(data.Result_Data.List)

	return tree;
}

// 拿到服务区门店的树
export async function handleGetServiceShopTreeList(params: any) {
	const data = await request('/BaseInfo/GetSPRegionShopTree', {
		method: 'GET',
		params
	})
	if (data.Result_Code !== 100) {
		return {
			data: [],
			otherData: '',
			current: 1,
			pageSize: 20,
			total: 0,
			success: true,
		};
	}
	const tree = await wrapTreeNode(data.Result_Data.List)
	return tree;
}


// 根据参数处查询门店 返回数据为服务区+门店树格式
export async function getServerpartShopTree(
	provinceCode?: number | string, ServerpartId?: string, ServerpartCodes?: string,
	ServerpartShopId?: string, BusinessType?: string, ShowWholePower?: boolean | false
): Promise<[]> {
	if (!ShowWholePower) {
		const serverpartShopTree = session.get(`${getServerpartShopTree}`);
		if (serverpartShopTree) {
			return serverpartShopTree;
		}
	}

	const data = await request(`/BaseInfo/GetServerpartShopTree?
		ProvinceCode=${provinceCode || ''}&ServerpartCodes=${ServerpartCodes || ''}&
		ServerpartId=${ServerpartId || ''}&ServerpartShopId=${ServerpartShopId || ''}&
		BusinessType=${BusinessType || ''}&ShowWholePower=${ShowWholePower || false}`, {
		method: 'GET',
	})

	if (data.Result_Code !== 100) {
		return [];
	}

	const tree = await wrapTreeNode(data.Result_Data.List)

	session.set(`${getServerpartShopTree}`, tree);
	return tree;
}

// 获取用户（商家类型）所有服务区门店树 用于商户账号经营报表分析筛选
export async function getUserShopTree(UserId?: number, notShowShop?: boolean) {
	if (!UserId) {
		return []
	}
	const userShopTree = session.get(`userShopTree-${notShowShop ? 1 : 0}`);
	if (userShopTree) {
		return userShopTree
	}
	const data = await request(`/FrameWork/GetMerchantShopTree?UserId=${UserId}&ShowShop=${!notShowShop}`, {
		method: 'GET',
	})

	if (data.Result_Code !== 100) {
		return [];
	}

	const tree = await wrapTreeNode(data.Result_Data.List)

	session.set(`userShopTree-${notShowShop ? 1 : 0}`, tree);
	return tree
}

// 获取商品类型树数据
export async function getCommodityTypeTree(params?: {
	provinceCode?: number | string | undefined, ShowWholePower?: boolean | false
}) {
	const data = await request(`/BaseInfo/GetNestingCOMMODITYTYPETree?PROVINCE_CODE=${params?.provinceCode}`, {
		method: 'GET',
		params
	});

	if (data.Result_Code !== 100) {
		return []
	}
	const treeTable = wrapTreeNode(data.Result_Data.List);

	return [...treeTable];
}

// 获取经营业态树数据
export async function getBusinessTradeTree(params?: {
	provinceCode?: number | string | undefined, ownerUnitId?: number, ShowWholePower?: boolean | false
}) {
	const data = await request(`/BaseInfo/GetBusinessTradeIdTree`, {
		method: 'GET',
		params
	});

	if (data.Result_Code !== 100) {
		return []
	}
	const treeTable = wrapTreeNode(data.Result_Data.List);

	return [...treeTable];
}

// 获取解密数据
export async function getCoopMerchantsDDL(ProvinceCode?: number | undefined, OwnerUnitId?: number | undefined,
	CoopMerchantsState?: number | undefined, ServerpartId?: number | undefined, CoopMerchantsName?: string) {
	const data = await request(`/Merchants/GetCoopMerchantsDDL?ProvinceCode=${ProvinceCode || ''}&OwnerUnitId=${OwnerUnitId || ''}&
		CoopMerchantsState=${CoopMerchantsState || ''}&ServerpartId=${ServerpartId || ''}&CoopMerchantsName=${CoopMerchantsName || ''}`, {
		method: 'GET',
	},
	);

	if (data.Result_Code !== 100) {
		return data.Result_Desc;
	}

	return tableList(data.Result_Data);
}

// 获取解密数据
export async function getDecryptStr(EncryptedStr: string) {
	const data = await request(
		`/Common/GetDecryptStr?EncryptedStr=${EncryptedStr}`, {
		method: 'GET',
	},
	);

	if (data.Result_Code !== 100) {
		return data.Result_Desc;
	}

	return data.Result_Data;
}


export const getName = (list: any[]) => {
	const option: any = []
	list.forEach(async (item: any, index: number) => {
		option.push({ ico: item.ico, index: item.index, key: item.key, label: item.label, type: item.type, value: item.value })
		if (item.children && item.children.length > 0) {
			const childrenList: any[] = getName(item.children)
			if (index === 3) {
				console.log('childrenList', childrenList)
			}
			if (childrenList && childrenList.length > 0) {
				childrenList.forEach((res => {
					option.push(res)
				}))
			}
		}

	})
	return option
}

// 枚举根据value 输出对应的label
// fieldName 要查的那个枚举   value 是对应的值
export function getFieldEnumName(fieldName: string, value: any) {

	const fieldList = session.get(`${fieldName}TreeOne`);
	if (fieldList) {
		let name: string = ''
		fieldList.forEach((item: any) => {
			if (item.value === Number(value)) {
				name = item.label
			}
		})
		if (name) {
			return name
		}
	} else {
		const list = session.get(`${fieldName}Tree`);
		const newList = getName(list)
		session.set(`${fieldName}TreeOne`, newList);
		return getFieldEnumName(fieldName, value)
	}
}
export const fmoney = (s: number, n?: number) => {
	/*
	 * 参数说明：
	 * s：要格式化的数字
	 * n：保留几位小数
	 * */
	n = n > 0 && n <= 20 ? n : s.toString().indexOf('.') === -1 ? 0 : s.toString().indexOf('.') > -1 ? s.toString().split('.')[1].length : 2;
	let fuhao = ''; // 如果数字小于零则值为-
	if (s < 0) {
		s = Math.abs(s);
		fuhao = '-'
	}
	s = `${parseFloat((`${s}`).replace(/[^\d\.-]/g, "")).toFixed(n)}`;
	const l = s.split(".")[0].split("").reverse();
	const r = s.split(".")[1];
	let t = "";
	for (let i = 0; i < l.length; i++) {
		t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
	}
	if (n === 0) {
		return s
	}
	return `${fuhao + [...t].reverse().join("")}.${r}`;

}

export const noDecimal = (s: number) => {
	let fuhao = ''; // 如果数字小于零则值为-
	if (s < 0) {
		s = Math.abs(s);
		fuhao = '-'
	}
	s = `${parseFloat((`${s}`).replace(/[^\d\.-]/g, ""))}`
	const l = s.split(".")[0].split("").reverse(); const r = s.split(".")[1];
	let t = ''
	for (let i = 0; i < l.length; i++) {
		t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
	}
	return fuhao + [...t].reverse().join("")
}

// 将枚举数组变成枚举对象
export const handleGetFieldObj = (list: any) => {
	if (list && list.length > 0) {
		const obj: any = {}
		list.forEach((item: any) => {
			obj[item.value] = item.label
		})
		return obj
	}
	return ''

}

// 不四舍五入 保留两位小数 的方法 不会出现千分号
export const getMoney = (money: any) => {
	const str: string = String(money)
	if (str.indexOf('.') === -1) {
		return Number(str)
	}
	const index: number = str.indexOf('.')
	const newNumber: string = str.slice(0, index)
	const smallNumber: string = str.slice(index, index + 3)
	return Number(newNumber + smallNumber)
}


// 给数组赋值上序号 都是1 1 1 的
export const handleChangeIndexList = (list: any) => {
	const res: any = JSON.parse(JSON.stringify(list))
	res.forEach((item: any, index: number) => {
		item.index = index + 1
		if (item.children && item.children.length > 0) {
			item.children.forEach((subItem: any, subIndex: number) => {
				subItem.index = subIndex + 1
				if (subItem.children && subItem.children.length > 0) {
					subItem.children.forEach((thirdItem: any, thirdIndex: number) => {
						thirdItem.index = thirdIndex + 1
					})
				}
			})
		}
	})
	return res
}


// 吧 类似与20240320093550 这样的时间格式变成正常的时间格式
export const handleGetDate = (value: string) => {
	const str = value.toString()
	if (str) {
		const y: string = str.slice(0, 4)
		const m: string = str.slice(4, 6)
		const d: string = str.slice(6, 8)

		const h: string = str.slice(8, 10)
		const min: string = str.slice(10, 12)
		const s: string = str.slice(12, 14)
		return `${y}/${m}/${d} ${h}:${min}:${s}`
	}
	return ''
}


// 根据时间去判断收银状态
// 如 实时稽查校验页面可以用到
// time 为传入的时间 min 为有效期是几分钟
export const handleGetCashierStatus = (time: any, min: number) => {
	const selectTimeStr: string = moment(time).format('YYYY-MM-DD HH:mm:ss')
	const timeNumber: number = new Date(selectTimeStr).getTime()
	const nowTimeNumber: number = new Date().getTime()

	return timeNumber > nowTimeNumber || timeNumber + 60 * 1000 * min > nowTimeNumber;

}


// 调用日志的接口
export const handleCallLogs = () => {
	const logObj: any = session.get('moduleObj')
	synchroBehaviorRecord({
		...logObj,
		BEHAVIORRECORD_TIME: moment().format('YYYY-MM-DD HH:mm:ss'),
		BEHAVIORRECORD_DESC: '操作查询',
		BEHAVIORRECORD_TYPE: 2000
	})
}

// 判断外面包着合计 通过片区 服务区 一层一层下来的 的时候
// 当只选择一个服务区的时候 把 片区和合计去掉的然后显示的方法
export const handleChangeTableData = (isOnlyArea: boolean, isOnlyService: boolean, list: any) => {
	let res: any = []
	if (isOnlyArea && isOnlyService) {
		list.forEach((item: any) => {
			item.children.forEach((subItem: any) => {
				res = subItem.children
			})
		})
		return res
	}
	if (isOnlyArea && !isOnlyService) {
		list.forEach((item: any) => {
			res = item.children
		})
		return res
	}
	return list
}


// 把 合计 片区 服务区 层级的 拿到最里面的服务区数组的方法
export const handleGetServerPartList = (list: any) => {
	const res: any = []
	if (list && list.length > 0) {
		list.forEach((item: any) => {
			if (item.children && item.children.length > 0) {
				item.children.forEach((subItem: any) => {
					subItem.children.forEach((thirdItem: any) => {
						res.push(thirdItem)
					})
				})
			}
		})
		return res
	}
	return []
}

// 数组去重
export const unique = (arr: any) => {
	if (!Array.isArray(arr)) {
		return
	}
	const array = [];
	for (let i = 0; i < arr.length; i++) {
		if (array.indexOf(arr[i]) === -1) {
			array.push(arr[i])
		}
	}
	return array;
}



// 传入年份月份  如果传入月份大于今天 那么就输出昨天 别的时间 想同月份 反昨天 之前的时间 反月份最后一天
// 时间格式YYYY-MM
export const handleGetEndDateMonth = (time: any) => {
	// 现在要传月份的 也要传入到具体日期
	// 这样的话就要判断结束月份的时间 最大只能是昨天 所以要做判断
	// 输出结果
	let res: any = {}
	const nowDate = new Date()
	const nowY: number = nowDate.getFullYear()
	const nowM: number = nowDate.getMonth() + 1
	const selectDate = new Date(time)
	const selectY: number = selectDate.getFullYear()
	const selectM: number = selectDate.getMonth() + 1
	if (nowY === selectY && nowM === selectM) {
		res = moment().subtract(1, 'days').format('YYYY-MM-DD')
	} else if (nowY === selectY && nowM < selectM) {
		res = moment().subtract(1, 'days').format('YYYY-MM-DD')
	} else {
		res = moment(time[1]).endOf('months').format('YYYY-MM-DD')
	}
	return res
}

export const getFractionalPart = (number: number) => {
	return number - Math.floor(number);
}


// 不保留 直接截取两位小数
export const truncateDecimal = (num: number) => {
	if (!num && num !== 0) {
		return 0
	}
	// 先用 toFixed 保留两位小数以消除精度问题
	const fixedNum = parseFloat(num.toFixed(10));
	// 将数字转换为字符串
	let strNum = fixedNum.toString();

	// 找到小数点的位置
	const dotIndex = strNum.indexOf('.');

	// 如果有小数点且小数点后有至少两位，则截取
	if (dotIndex !== -1) {
		strNum = strNum.substring(0, dotIndex + 3);
	}

	// 转换回数字类型
	return parseFloat(strNum);
}

// 若有小数保留两位小数 没有小数不保留
export const formatNumber = (num: number) => {
	// 判断是否是小数
	if (num % 1 !== 0) {
		return num.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
	}
	return num.toLocaleString(); // 使用千分号，不保留小数位

}


// 把可能是带千分号的数字 变为数字
export const parseThousandSeparatedNumber = (str: string) => {
	if (!str) return 0; // 如果字符串为空，返回0
	const cleaned = str.replace(/,/g, ""); // 移除千分号
	return parseFloat(cleaned); // 转换为数字
};

// 保留数字两位小数 不四舍五入 没有小数补齐00
export const formatToTwoDecimalPlaces = (num: number) => {
	if (typeof num !== 'number' || isNaN(num) || num === 0) {
		return '0.00'
	}

	// 转换为字符串处理整数和小数部分
	let [integerPart, decimalPart] = num.toString().split('.');

	// 补零逻辑
	if (!decimalPart) {
		decimalPart = '00';
	} else if (decimalPart.length < 2) {
		decimalPart = decimalPart.padEnd(2, '0');
	} else {
		decimalPart = decimalPart.substring(0, 2);
	}

	// 添加千分位
	integerPart = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',');

	return `${integerPart}.${decimalPart}`;
}


// 保留两位小数  不满两位小数的用0补齐 有千分号
export const handleFormatNumber = (value: number) => {
	// 强制转换为 number
	const num = Number(value);
	// 确保输入是一个数字
	if (isNaN(num)) return num.toString();

	// 如果输入为0，直接返回 '0.00'
	if (num === 0) return '0.00';

	// 先处理千分号格式，保留两位小数
	let [integer, decimal] = num.toFixed(2).split('.'); // 保留两位小数

	// 处理千分号
	integer = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ',');

	// 返回格式化后的数字
	return `${integer}.${decimal}`;
}