package yem.wm.cm.sys.utils;


import kd.bos.bill.OperationStatus;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.AppInfo;
import kd.bos.entity.AppMetadataCache;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.exception.KDBizException;
import kd.bos.fileservice.FileItem;
import kd.bos.fileservice.FileService;
import kd.bos.fileservice.FileServiceFactory;
import kd.bos.form.*;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.id.ID;
import kd.bos.list.ListShowParameter;
import kd.bos.logorm.LogORM;
import kd.bos.orm.ORM;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.AttachmentServiceHelper;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.basedata.BaseDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.parameter.SystemParamServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
import kd.bos.util.FileNameUtils;
import yem.base.common.utils.BigDecimalUtils;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * 自营进口公共类
 * @author 86173
 *
 */
public class CommonUtils {

	public static final String[] SPECIAL_SYMBOLS = new String[] { "%", "=", "+" };
	public static final String[] SPECIAL_CHARACTERS = new String[] { "+", "/", "?", "%", "#", "&", "=" };

	/**
	 * 获取汇率
	 * 
	 * @param sourceCurrencyId
	 * @param targetCurrencyId
	 * @param orgId
	 * @param date
	 * @return
	 */
	public static BigDecimal getExchangeRate(Long exchangeRateTableId, final Long sourceCurrencyId,
			final Long targetCurrencyId, final Long orgId, Date date) {
		BigDecimal exchangeRate = BigDecimal.ONE;
		if (date == null) {
			date = new Date();
		}
		if (sourceCurrencyId == 0L || targetCurrencyId == 0L || sourceCurrencyId == targetCurrencyId) {
			return exchangeRate;
		}
		if (sourceCurrencyId.equals(targetCurrencyId)) {
			return exchangeRate;
		}
		// 汇率表为空时 取 应收初始化 汇率类型；不为空是取单据参数
		if (exchangeRateTableId == 0L) {
			if (getExrateTable(orgId) != null) {
				exchangeRateTableId = getExrateTable(orgId).getLong("id");
				exchangeRate = BaseDataServiceHelper.getExchangeRate(exchangeRateTableId, sourceCurrencyId,
						targetCurrencyId, date);
			}
		} else {
			exchangeRate = BaseDataServiceHelper.getExchangeRate(exchangeRateTableId, sourceCurrencyId,
					targetCurrencyId, date);
		}
		return exchangeRate;
	}

	/**
	 * 获取本位币
	 * 
	 * @param orgId
	 * @return
	 */
	public static DynamicObject getStandardCurrency(final long orgId) {
		final DynamicObject systemStatusCtrol = getSystemStatusCtrol(orgId);
		if (systemStatusCtrol == null) {
			return null;
		}
		return systemStatusCtrol.getDynamicObject("standardcurrency");
	}

	/**
	 * 获取汇率类型表名
	 * 
	 * @param orgId
	 * @return
	 */
	public static DynamicObject getExrateTable(final long orgId) {
		final DynamicObject systemStatusCtrol = getSystemStatusCtrol(orgId);
		if (systemStatusCtrol == null) {
			return null;
		}
		return systemStatusCtrol.getDynamicObject("exratetable");
	}

	/**
	 * 获取系统状态控制
	 * 
	 * @param orgId
	 * @return
	 */
	private static DynamicObject getSystemStatusCtrol(final long orgId) {
		final QFilter[] filters = { new QFilter("org", "=", (Object) orgId) };
		final DynamicObjectCollection CasInitColl = QueryServiceHelper.query("cas_cashmgtinit", "id", filters);
		if (CasInitColl.size() == 0) {
			return null;
		}
		final DynamicObject ArInit = BusinessDataServiceHelper
				.loadSingle((Object) ((DynamicObject) CasInitColl.get(0)).getLong("id"), "cas_cashmgtinit");
		return ArInit;
	}
	
	/**
	 * 获取系统状态控制
	 * 
	 * @param orgId
	 * @return
	 */
	public static DynamicObject getInitialization(final long orgId,final String SystemType) {
		final QFilter qFilter = new QFilter("org", QCP.equals, orgId);
		final QFilter qFilter1 = new QFilter("isfinishinit", QCP.equals, true);
		final DynamicObjectCollection CasInitColl = QueryServiceHelper.query(SystemType, "id", new QFilter[]{qFilter,qFilter1});
		if (CasInitColl.size() > 0) {
			final DynamicObject ArInit = BusinessDataServiceHelper.loadSingle((Object) ((DynamicObject) CasInitColl.get(0)).getLong("id"), SystemType);
			return ArInit;
		}
		return null;
	}

	/**
	 * 获取系统参数【布尔型】
	 * 
	 * @param orgId
	 * @param key
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static boolean getParameterBoolean(final long orgId, final String key) {
		final Object value = SystemParamServiceHelper.getAppParameter("075YJT9UL49+", "075YOP7VS1VC",
				Long.valueOf(orgId), key);
		return value != null && (boolean) value;
	}

	/**
	 * 获取系统参数【int型】
	 * 
	 * @param orgId
	 * @param key
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static int getParameterInteger(final long orgId, final String key) {
		final Object value = SystemParamServiceHelper.getAppParameter("075YJT9UL49+", "075YOP7VS1VC",
				Long.valueOf(orgId), key);
		if (value == null) {
			return 0;
		}
		return Integer.parseInt(value.toString());
	}

	/**
	 * 给基础资料字段赋值
	 * 
	 * @param model
	 * @param view
	 * @param field
	 * @param value
	 */
	public static void setValue(final IDataModel model, final IFormView view, final String field,
			final DynamicObject value) {
		model.beginInit();
		model.setValue(field, (value == null) ? null : value.getPkValue());
		model.endInit();
		view.updateView(field);
	}

	/**
	 * 获取当前登录用户主键
	 * 
	 * @return
	 */
	public static Long getCurrentUserId() {
		final Long currentUserId = Long.valueOf(RequestContext.get().getUserId());
		return currentUserId;
	}

	/**
	 * 获取当前登录用户对象
	 * 
	 * @return
	 */
	public static DynamicObject getCurrentUser() {
		final Long currentUserId = Long.valueOf(RequestContext.get().getUserId());
		return BusinessDataServiceHelper.loadSingleFromCache((Object) currentUserId, "bos_user");
	}

	/**
	 * 根据业务单据获取应用信息
	 * 
	 * @param formId
	 * @return
	 */
	public static AppInfo getBizAppByFormId(final String formId) {
		final FormConfig formConfig = FormMetadataCache.getFormConfig(formId);
		if (formConfig == null || formConfig.getAppId() == null) {
			return null;
		}
		final AppInfo appInfo = AppMetadataCache.getAppInfo(formConfig.getAppId());
		return appInfo;
	}

	/**
	 * 根据应用ID获取业务组织功能
	 * 
	 * @param appId
	 * @return
	 */
	public static String getBizAppOrgFuncByAppId(final String appId) {
		final AppInfo appInfo = AppMetadataCache.getAppInfo(appId);
		return appInfo.getOrgFunc();
	}

	/**
	 * 根据业务单据获取业务组织功能
	 * 
	 * @param formId
	 * @return
	 */
	public static String getBizAppOrgFuncByFormId(final String formId) {
		final AppInfo appInfo = getBizAppByFormId(formId);
		if (appInfo == null) {
			return null;
		}
		return appInfo.getOrgFunc();
	}

	/**
	 * 获取客户联系人内码
	 * 
	 * @param customer
	 * @return
	 */
	public static Long getLinkman(final DynamicObject customer) {
		final DynamicObjectCollection linkmans = customer.getDynamicObjectCollection("entry_linkman");
		Long customerLinkmanId = null;
		for (final DynamicObject linkman : linkmans) {
			final boolean isDefault = linkman.getBoolean("isdefault_linkman");
			if (isDefault) {
				customerLinkmanId = (long) linkman.getPkValue();
				break;
			}
		}
		return customerLinkmanId;
	}

	/**
	 * 获取客户地址
	 * 
	 * @param customer
	 * @return
	 */
	public static String getAddress(final DynamicObject customer) {
		final DynamicObjectCollection addresses = customer.getDynamicObjectCollection("entry_address");
		for (final DynamicObject addressInfo : addresses) {
			final boolean isDefault = addressInfo.getBoolean("isdefault_addr");
			if (isDefault) {
				return addressInfo.getString("addr_address");
			}
		}
		return "";
	}

	/**
	 * 批量刷新页面字段
	 * 
	 * @param view
	 * @param parm
	 */
	public static void updateView(final IFormView view, final String... parm) {
		for (final String s : parm) {
			updateView(view, s);
		}
	}

	/**
	 * 刷新页面字段
	 * 
	 * @param view
	 * @param key
	 */
	private static void updateView(final IFormView view, final String key) {
		if (!CommonUtils.isNull((Object) view.getControl(key))) {
			view.updateView(key);
		}
	}

	/**
	 * 判断对象是否为空
	 * 
	 * @param o
	 * @return
	 */
	public static boolean isNull(final Object o) {
		return o == null || (o instanceof String && ((String) o).length() == 0)
				|| (o instanceof StringBuffer && ((StringBuffer) o).length() == 0)
				|| (o instanceof List && ((List) o).size() == 0)
				|| (o instanceof Collection && ((Collection) o).size() == 0)
				|| (o instanceof Object[] && ((Object[]) o).length == 0) || (o instanceof Map && ((Map) o).size() == 0);
	}

	/**
	 * 获取公司抬头
	 */
	public static long GetCompanyInfoIdnew(long Orgid) {
		long Companyfid = 0L;
		QFilter qFilter1 = new QFilter("org", "=", Orgid);
		QFilter qFilter2 = new QFilter("yem_isdefault", "=", true);
		QFilter qFilter3 = new QFilter("status", "=", "C");
		DynamicObject[] Companyobj = BusinessDataServiceHelper.load("yem_bd_companyinfo", "id",
				new QFilter[] { qFilter1, qFilter2, qFilter3 });
		if (Companyobj != null && Companyobj.length > 0) {
			Companyfid = Companyobj[0].getLong("id");
		}
		return Companyfid;
	}

	/**
	 * 获取币别
	 * 
	 * @param CurrencyCode
	 * @return
	 */
	public static DynamicObject GetCurrencyInfoId(String CurrencyCode) {
		QFilter qFilter1 = new QFilter("number", "=", CurrencyCode);
		DynamicObject[] bills = BusinessDataServiceHelper.load("bd_currency", "id", new QFilter[] { qFilter1 });
		DynamicObject bill = null;
		for (int j = 0; j < bills.length; ++j) {
			bill = bills[j];
		}
		return bill;
	}

	/**
	 * 设置中文大写金额
	 * 
	 * @param model
	 * @param amountKey
	 *            金额
	 * @param currencyKey
	 *            币别
	 * @param wordKey
	 *            币别符合
	 */
	public static void SetAmountInWordsCN(final IDataModel model, String amountKey, String currencyKey,
			String wordKey) {
		DynamicObject currency = (DynamicObject) model.getValue(currencyKey);
		if (currency != null) {
			BigDecimal amount = BigDecimalUtils.toBigDecimal(model.getValue(amountKey));
			if (amount.compareTo(BigDecimal.ZERO)>0) {
				model.setValue(wordKey, BigDecimalUtils.digitCapital(amount.doubleValue()));
			}
		}
	}

	/**
	 * 获取当前用户部门
	 * 
	 * @return
	 */
	public static String getPurdep() {
		UserServiceHelper helper = new UserServiceHelper();
		long userId = helper.getCurrentUserId(); // 获取用户ID
		QFilter qFilter1 = new QFilter("operatorid", "=", userId);
		DynamicObject[] puroperators = BusinessDataServiceHelper.load("bd_operator", "id,operatornumber,operatorname",
				new QFilter[] { qFilter1 });
		if (puroperators != null && puroperators.length > 0) {
			DynamicObject puroperator = puroperators[0];
			puroperator = BusinessDataServiceHelper.loadSingleFromCache(puroperator.getPkValue(), "bd_operator");
			DynamicObject operatorid = (DynamicObject) puroperator.get("operatorid");
			if (null != operatorid) {
				operatorid = BusinessDataServiceHelper.loadSingleFromCache(operatorid.getPkValue(), "bos_user");
				DynamicObjectCollection entryentitys = operatorid.getDynamicObjectCollection("entryentity");
				if (entryentitys != null && entryentitys.size() == 1) {
					DynamicObject entryentity = entryentitys.get(0);
					DynamicObject purdep = entryentity.getDynamicObject("dpt");
					String purdepNme = purdep.getString("name");
					return purdepNme;
				}
			}
		}
		return null;
	}

	/**
	 * 根据上游单据信息，初始化当前单据‘上游单据审批信息分录’
	 * 
	 * @param map
	 */
	public static void setApprovalinfo(Map map, DynamicObject descBill) {
		if (!map.containsKey("srcBill")) {
			throw new KDBizException("初始化审批信息分录时，参数srcBill为空，请检查！");
		}
		if (!map.containsKey("srcBillId")) {
			throw new KDBizException("初始化审批信息分录时，参数srcBillId为空，请检查！");
		}
		if (!map.containsKey("srcEntry")) {
			throw new KDBizException("初始化审批信息分录时，参数srcEntry为空，请检查！");
		}
		if (!map.containsKey("srcApprovalnode")) {
			throw new KDBizException("初始化审批信息分录时，参数srcApprovalnode为空，请检查！");
		}
		if (!map.containsKey("srcApprovedby")) {
			throw new KDBizException("初始化审批信息分录时，参数srcApprovedby为空，请检查！");
		}
		if (!map.containsKey("srcApprovetime")) {
			throw new KDBizException("初始化审批信息分录时，参数srcApprovetime为空，请检查！");
		}
		if (!map.containsKey("descEntry")) {
			throw new KDBizException("初始化审批信息分录时，参数descEntry为空，请检查！");
		}
		if (!map.containsKey("descApprovalnode")) {
			throw new KDBizException("初始化审批信息分录时，参数descApprovalnode为空，请检查！");
		}
		if (!map.containsKey("descApprovedby")) {
			throw new KDBizException("初始化审批信息分录时，参数descApprovedby为空，请检查！");
		}
		if (!map.containsKey("descApprovetime")) {
			throw new KDBizException("初始化审批信息分录时，参数descApprovetime为空，请检查！");
		}
		String srcBill = map.get("srcBill").toString();// 上游单据标识
		long srcBillId = (long) map.get("srcBillId");// 上游单据内码
		String srcEntry = map.get("srcEntry").toString();// 上游单据审批信息分录标识
		String srcApprovalnode = map.get("srcApprovalnode").toString();// 上游单据审批信息分录-审批节点字段标识
		String srcApprovedby = map.get("srcApprovedby").toString();// 上游单据审批信息分录-审批人字段标识
		String srcApprovetime = map.get("srcApprovetime").toString();// 上游单据审批信息分录-审批日期字段标识

		String descEntry = map.get("descEntry").toString();// 下游单据审批信息分录标识
		String descApprovalnode = map.get("descApprovalnode").toString();// 下游单据审批信息分录-审批节点字段标识
		String descApprovedby = map.get("descApprovedby").toString();// 下游单据审批信息分录-审批人字段标识
		String descApprovetime = map.get("descApprovetime").toString();// 下游单据审批信息分录-审批日期字段标识

		DynamicObjectCollection descEntryObjs = descBill.getDynamicObjectCollection(descEntry);
		descEntryObjs.clear();
		DynamicObject srcObj = BusinessDataServiceHelper.loadSingle(srcBillId, srcBill);
		if (null != srcObj) {
			DynamicObjectCollection srcEntryObjs = srcObj.getDynamicObjectCollection(srcEntry);
			for (int i = 0; i < srcEntryObjs.size(); i++) {
				DynamicObject srcEntryObj = srcEntryObjs.get(i);
				DynamicObject descEntryObj = descEntryObjs.addNew();
				descEntryObj.set(descApprovalnode, srcEntryObj.get(srcApprovalnode));
				descEntryObj.set(descApprovedby, srcEntryObj.get(srcApprovedby));
				descEntryObj.set(descApprovetime, srcEntryObj.get(srcApprovetime));
			}
		}
	}

	// 附件工具类
	public static void AttachmentService(String sourceBillId, String sourceBillformId, String ExtendedbillId,
			String ExtendedbillformId, String attachmentpanelId) {
		List<Map<String, Object>> listold = AttachmentServiceHelper.getAttachmentsByExport(sourceBillformId,
				sourceBillId);
		List<Map<String, Object>> listnew = new ArrayList<>();
		for (Map<String, Object> obj : listold) {
			obj.put("lastModified", null);
			listnew.add(obj);
		}
		AttachmentServiceHelper.upload(ExtendedbillformId, ExtendedbillId, attachmentpanelId, listnew);
	}

	/**
	 * BOTP下推时 携带上游单据附件
	 * 
	 * @param bill
	 *            携带至的单据对象
	 * @param attachKey
	 *            附件面板标识
	 * @param fsourcebillid
	 *            附件来源对象ID
	 * @param sourcebillform
	 *            附件来源对象
	 * @param appId
	 *            所属应用编码 例：tp_is
	 */
	public static void botpAttachmentpanel(DynamicObject bill, String attachKey, Long fsourcebillid,
			String sourcebillform, String appId) {
		Object pkId = bill.getPkValue();
		if ((Long) pkId == 0L) {
			return;
		}
		String formId = bill.getDataEntityType().getName();
		List<Map<String, Object>> listMapAttachments = AttachmentServiceHelper.getAttachmentsByExport(sourcebillform,
				fsourcebillid);
		for (Map<String, Object> attach : listMapAttachments) {
			String Dodurl = (String) attach.get("url");
			String fileName = (String) attach.get("name");
			FileService service = FileServiceFactory.getAttachmentFileService();
			// 根据原url获取引入文件流
			InputStream in = service.getInputStream(Dodurl);

			String tenantId = RequestContext.get().getTenantId();
			String accountId = RequestContext.get().getAccountId();
			String uuid = UUID.randomUUID().toString().replace("-", "");
			// 生产相对Url
			String path = FileNameUtils.getAttachmentFileName(tenantId, accountId, appId, formId,
					replaceSpeChar(String.valueOf(pkId)), uuid + "/" + replaceSpeSymbol(fileName));
			FileItem fileItem = new FileItem(fileName, path, in);
			fileItem.setCreateNewFileWhenExists(true);
			// 上传至文件服务器
			String turl = service.upload(fileItem);

			// 文件保存至附件
			ORM orm = ORM.create();
			DynamicObject dynamicObject = orm.newDynamicObject("bos_attachment");
			Long id = Long.valueOf(orm.genLongId("bos_attachment"));
			dynamicObject.set("id", id);
			dynamicObject.set("FNUMBER", attach.get("uid"));
			dynamicObject.set("FBillType", formId);
			dynamicObject.set("FInterID", pkId);
			dynamicObject.set("FModifyTime", new Date());
			dynamicObject.set("fcreatetime", new Date());
			dynamicObject.set("FaliasFileName", fileName);
			dynamicObject.set("FAttachmentName", fileName);
			dynamicObject.set("FExtName", fileName != null ? fileName.substring(fileName.lastIndexOf(46) + 1) : "");
			dynamicObject.set("FATTACHMENTSIZE", attach.get("size"));
			dynamicObject.set("FFileId", turl);
			dynamicObject.set("FCREATEMEN", RequestContext.get().getUserId());
			dynamicObject.set("FMODIFYMEN", RequestContext.get().getUserId());
			dynamicObject.set("fattachmentpanel", attachKey);
			dynamicObject.set("fbillstatus", "1");
			orm.insert(dynamicObject);
		}
	}

	/***
	 * 附件下推携带2
	 * 
	 * @param bill
	 * @param attachKey
	 * @param fsourcebillid
	 * @param sourcebillform
	 * @param appId
	 * @param Targetbillform
	 */
	private static void botpAttachmentpanel1(DynamicObject bill, String attachKey, Long fsourcebillid,
			String sourcebillform, String appId, String Targetbillform) {
		List<Map<String, Object>> listold = AttachmentServiceHelper.getAttachmentsByExport(sourcebillform,
				fsourcebillid);
		List<Map<String, Object>> listnew = new ArrayList<>();
		// 获取文件服务器
		FileService fileService = FileServiceFactory.getAttachmentFileService();
		List<FileItem> fileItemList = new ArrayList<>(10);
		for (Map<String, Object> obj : listold) {
			String path = (String) obj.get("url");
			String fileName = (String) obj.get("name");
			RequestContext requestContext = RequestContext.get();
			String pathParam = FileNameUtils.getAttachmentFileName(requestContext.getTenantId(),
					requestContext.getAccountId(), "botpUpload", fileName);
			FileItem item = new FileItem(fileName, pathParam, fileService.getInputStream(path));
			fileItemList.add(item);

			obj.put("lastModified", null);
			obj.put("url", pathParam);
			listnew.add(obj);
		}
		FileItem[] fileItems = fileItemList.toArray(new FileItem[fileItemList.size()]);
		// 上传至文件服务器；
		fileService.upload(fileItems);
		AttachmentServiceHelper.upload(Targetbillform, bill.getPkValue(), "attachmentpanel", listnew);
	}

	private static String replaceSpeSymbol(String str) {
		for (int i = 0; i < SPECIAL_SYMBOLS.length; ++i) {
			if (str.contains(SPECIAL_SYMBOLS[i])) {
				str = str.replace(SPECIAL_SYMBOLS[i], "_");
			}
		}

		return str;
	}

	private static String replaceSpeChar(String str) {
		for (int i = 0; i < SPECIAL_CHARACTERS.length; ++i) {
			if (str.contains(SPECIAL_CHARACTERS[i])) {
				str = str.replace(SPECIAL_CHARACTERS[i], "");
			}
		}
		return str;
	}
	
	/***
	 * 设置采购员、采购组、采购部门默认值
	 * @param  model
	 */
	public static void GetUserDepInfo(IDataModel model) {
		UserServiceHelper helper = new UserServiceHelper();
		long userId = helper.getCurrentUserId(); // 获取用户ID
		QFilter qFilter1 = new QFilter("operatorid", "=", userId);
		DynamicObject[] puroperators = BusinessDataServiceHelper.load("bd_operator", "id,operatornumber,operatorname",
			new QFilter[] { qFilter1 });
		if (puroperators != null && puroperators.length > 0) {
		DynamicObject puroperator = puroperators[0];
		model.setValue("yem_operator", puroperator);
		puroperator = BusinessDataServiceHelper.loadSingleFromCache(puroperator.getPkValue(), "bd_operator");
		model.setValue("yem_department", puroperator.get("operatorgrpid"));
		DynamicObject operatorid = (DynamicObject) puroperator.get("operatorid");
		operatorid = BusinessDataServiceHelper.loadSingleFromCache(operatorid.getPkValue(), "bos_user");
		DynamicObjectCollection entryentitys = operatorid.getDynamicObjectCollection("entryentity");
		if (entryentitys != null && entryentitys.size() == 1) {
				DynamicObject entryentity = entryentitys.get(0);
				DynamicObject purdep =(DynamicObject) model.getValue("yem_department");
				if (purdep!=null) {
							
				}else {
					model.setValue("yem_department", entryentity.get("dpt"));
				}
			}
		}
	}
	
	/**
	 * 根据物料分类设置物料F7过滤
	 * @param e
	 * @param materialgroup 物料分类
	 */
	public static void beforeMaterialSelect(BeforeF7SelectEvent e, DynamicObject materialgroup) {
		if (null != materialgroup) {
			List ids = new ArrayList();
			QFilter qFilter1 = new QFilter("group.id", "=", materialgroup.getPkValue());
			DynamicObject[] groups = BusinessDataServiceHelper.load("bd_materialgroupdetail", "standard,group,material",
					new QFilter[] { qFilter1 });
			for (int i = 0; i < groups.length; i++) {
				DynamicObject material = (DynamicObject) groups[i].get("material");
				ids.add(material.getPkValue());
			}
			// 生成过滤条件对象QFilter
			QFilter qFilter = new QFilter("id", QCP.in, ids);
			// 设置列表过滤条件
			ListShowParameter showParameter = (ListShowParameter) e.getFormShowParameter();
			showParameter.getListFilterParameter().setFilter(qFilter);
		}
	}
	
	/**
	 * 根据物料、贸易类型设置金属系数维护F7过滤
	 * @param e
	 * @param yem_material
	 * @param yem_tradetype
	 */
	public static void beforeMetalcoefficientSelect(BeforeF7SelectEvent e, DynamicObject yem_material, String yem_tradetype) {
		if (null != yem_material) {
			List ids = new ArrayList();
			QFilter qFilter1 = new QFilter("enable", QCP.equals, "1");
			QFilter qFilter2 = new QFilter("status", QCP.equals, "C");
			QFilter qFilter3 = new QFilter("yem_material", QCP.equals, yem_material.getPkValue());
			QFilter qFilter4 = new QFilter("yem_tradetype", QCP.equals, yem_tradetype);
			DynamicObject[] yem_bd_metalcoefficient_s = BusinessDataServiceHelper.load("yem_bd_metalcoefficient",
					"id,name,number",new QFilter[] { qFilter1 , qFilter2 , qFilter3 , qFilter4 }, null);
			for (int i = 0; i < yem_bd_metalcoefficient_s.length; i++) {
				ids.add(yem_bd_metalcoefficient_s[i].getPkValue());
			}
			// 生成过滤条件对象QFilter
			QFilter qFilter = new QFilter("id", QCP.in, ids);
			// 设置列表过滤条件
			ListShowParameter showParameter = (ListShowParameter) e.getFormShowParameter();
			showParameter.getListFilterParameter().setFilter(qFilter);
		}
	}
	
	/**
	 * 根据物料、计量单位、基本单位获取转换率
	 * @param materialId
	 * @param srcUnitId
	 * @param desUnitId
	 * @return
	 */
	public static BigDecimal getUnitRateConv(Long materialId, Long srcUnitId, Long desUnitId) {
        BigDecimal unitRate = null;
        if (materialId == null || srcUnitId == null || desUnitId == null) {
            unitRate = BigDecimal.ZERO;
        }
        else if (srcUnitId == (long)desUnitId) {
            unitRate = BigDecimal.ONE;
        }
        else {
            final DynamicObject muConv = BaseDataServiceHelper.getMUConv(materialId, srcUnitId, desUnitId);
            if (muConv != null && muConv.getInt("numerator") != 0) {
                unitRate = new BigDecimal(muConv.getInt("numerator")).divide(new BigDecimal(muConv.getInt("denominator")), 10, 4);
            }
        }
        if (unitRate == null) {
            unitRate = BigDecimal.ZERO;
        }
        return unitRate;
    }
	
	/**
	 * 根据源计量单位、目标计量单位获取换算系数
	 * @param srcUnitId
	 * @param desUnitId
	 * @return
	 */
	public static BigDecimal getMeasureUnitConv(long srcUnitId, long desUnitId) {
        BigDecimal unitRate = null;
        if(srcUnitId == desUnitId) {
        	unitRate = BigDecimal.ONE;
        }else {
    		QFilter qFilter1 = new QFilter("enable", QCP.equals, "1");
    		QFilter qFilter2 = new QFilter("status", QCP.equals, "C");
    		QFilter qFilter3 = new QFilter("yem_srcmuid", QCP.equals, srcUnitId).and(new QFilter("yem_desmuid", QCP.equals, desUnitId));
    		QFilter qFilter4 = new QFilter("yem_srcmuid", QCP.equals, desUnitId).and(new QFilter("yem_desmuid", QCP.equals, srcUnitId));
    		QFilter qFilter5 = qFilter3.or(qFilter4);
    		DynamicObject[] yem_measureunitconv_s = BusinessDataServiceHelper.load("yem_measureunitconv",
    				"id,name,number,yem_srcmuid,yem_desmuid,yem_numerator", new QFilter[] { qFilter1 , qFilter2 , qFilter5 }, null);
    		if(null != yem_measureunitconv_s && yem_measureunitconv_s.length>0) {
    			DynamicObject yem_measureunitconv = yem_measureunitconv_s[0];
    			DynamicObject yem_srcmuid = yem_measureunitconv.getDynamicObject("yem_srcmuid");
    			long yem_srcmuid_id = yem_srcmuid.getLong("id");
    			DynamicObject yem_desmuid = yem_measureunitconv.getDynamicObject("yem_desmuid");
    			long yem_desmuid_id = yem_desmuid.getLong("id");
    			BigDecimal yem_numerator = yem_measureunitconv.getBigDecimal("yem_numerator");
    			if(yem_srcmuid_id == srcUnitId && yem_desmuid_id == desUnitId) {
    				unitRate = yem_numerator;
    			}else if(yem_srcmuid_id == desUnitId && yem_desmuid_id == srcUnitId) {
    				unitRate = BigDecimalUtils.div(BigDecimal.ONE, yem_numerator, 4);
    			}
    		}
        }
        return unitRate;
	}
	
	/***
	 * 历史作价查询
	 */
	public static void GetFormShowParameter(IFormView view,IDataModel model,String billtype,String yem_purorderno,String yem_arrivalbill,String hispricinginfo) {
		FormShowParameter bsp = new FormShowParameter();
		bsp.setStatus(OperationStatus.ADDNEW);
		bsp.getOpenStyle().setShowType(ShowType.Modal);
		Map<String, Object> entryInfo = Gethistorpriced(model,billtype,yem_purorderno,yem_arrivalbill);
		bsp.setCustomParams(entryInfo);
//		CloseCallBack callBack = new CloseCallBack(model, hispricinginfo);
//		bsp.setCloseCallBack(callBack);
		bsp.setFormId("yem_historicalpricing");
		view.showForm(bsp);
	}
	
	/***
	 * 获取历史作价金属量(动态表单引用)
	 */
	public static Map<String, Object> Gethistorpriced(IDataModel model,String billtype,String orderno,String arrandsubbill) {
		Map<String, Object> parm = new HashMap<String, Object>();
		List<Object> parmlist =new ArrayList<Object>(); 
		if(billtype.equals("yem_pricelist_Pur")) {
//			if(StringUtils.isNotEmpty(arrandsubbill)) {//判断是否有交单跟到单相关的作价单
				QFilter qFilterarr1 = new QFilter("yem_purorderno", QCP.equals, orderno);
//				QFilter qFilterarr2 = new QFilter("yem_arrivalbill", QCP.equals, arrandsubbill);
//				QFilter qFilterarr3 = new QFilter("billstatus", QCP.equals, "C");
				QFilter qFilterarr4 = new QFilter("id", QCP.not_equals, model.getValue("id"));
				List queryFields = getQuerypricelistBill();
				String selectStr = String.join(",", queryFields);
				DynamicObject[] pricelistBillColl = BusinessDataServiceHelper.load("yem_pricelist", selectStr,
						new QFilter[] { qFilterarr1 ,qFilterarr4});
				if (null != pricelistBillColl && pricelistBillColl.length > 0) {
					for (DynamicObject pricelistBill : pricelistBillColl) {
						parmlist.add(pricelistBill.getPkValue());
					}
					parm.put("hispricelistID", parmlist);
				}
//			}
		}else {
//			if(StringUtils.isNotEmpty(arrandsubbill)) {//判断是否有交单跟到单相关的作价单
				QFilter qFilterarr1 = new QFilter("yem_salorderno", QCP.equals, orderno);
				QFilter qFilterarr2 = new QFilter("yem_submitbill", QCP.equals, arrandsubbill);
//				QFilter qFilterarr3 = new QFilter("billstatus", QCP.equals, "C");
				QFilter qFilterarr4 = new QFilter("id", QCP.not_equals, model.getValue("id"));
				List queryFields = getQuerypricelistBill();
				String selectStr = String.join(",", queryFields);
				DynamicObject[] pricelistBillColl = BusinessDataServiceHelper.load("yem_pricelist", selectStr,
						new QFilter[] { qFilterarr1, qFilterarr4 });
				if (null != pricelistBillColl && pricelistBillColl.length > 0) {
					for (DynamicObject pricelistBill : pricelistBillColl) {
						parmlist.add(pricelistBill.getPkValue());
					}
					parm.put("hispricelistID", parmlist);
				}
//			}
		}
		return parm;
	}
	
	/***
	 * 查询作价信息
	 */
	public static List getQuerypricelistBill() {
		ArrayList fields = new ArrayList();
		fields.add("billno");
		fields.add("yem_purorderno");
		fields.add("yem_arrivalbill");
		fields.add("yem_salorderno");
		fields.add("yem_submitbill");
		fields.add("yem_operatmetal");
		fields.add("yem_operatmetalunit");
		fields.add("yem_pointdate");
		fields.add("yem_operatprice");
		fields.add("yem_srcentryid");
		fields.add("yem_srcsubbillid");
		fields.add("yem_currpricingqty");
		return fields;
	}
	/**
	 * 获取发票已收款的金额
	 */
	public static BigDecimal getInvoiceYSkClaimed(long invoiceID,long EntityId,DynamicObject yem_Newcurrency) {
		BigDecimal yem_invoiceclaimamt =BigDecimal.ZERO;
		if(invoiceID==0L) {
			return yem_invoiceclaimamt;
		}
		
		//收款已认领
		QFilter qFilter1 = new QFilter("yem_recognitionentity.yem_invoice.id", QCP.equals, invoiceID);
		QFilter qFilter2 = new QFilter("yem_recognitionentity.id", QCP.not_equals, EntityId);
		QFilter qFilter21 = new QFilter("billstatus", QCP.equals, "D");
		qFilter2.and(qFilter21);
		
		DynamicObject [] CasrecbillCol = BusinessDataServiceHelper.load("cas_recbill","id,billno,yem_recognitionentity.yem_invoice.id",new QFilter[] { qFilter1,qFilter2});
		for(DynamicObject Casrecbill:CasrecbillCol) {
			Casrecbill = BusinessDataServiceHelper.loadSingle(Casrecbill.getPkValue(), "cas_recbill");
			DynamicObject cascurrency = Casrecbill.getDynamicObject("currency");
			DynamicObjectCollection recognitionentityCol =  Casrecbill.getDynamicObjectCollection("yem_recognitionentity");
			for(DynamicObject recognitionentity : recognitionentityCol) {
				 DynamicObject yem_invoice = recognitionentity.getDynamicObject("yem_invoice");
				 if(yem_invoice!=null&&yem_invoice.getLong("id")==invoiceID) {
					 yem_invoice = BusinessDataServiceHelper.loadSingle(yem_invoice.getPkValue(), yem_invoice.getDynamicObjectType().getName());
					 DynamicObject yem_currency = yem_invoice.getDynamicObject("yem_currency");
					 BigDecimal yem_exrate= yem_invoice.getBigDecimal("yem_payexchangerate");
				
					 BigDecimal yem_claimamt_z= recognitionentity.getBigDecimal("yem_claimamt_z");
					 if(yem_Newcurrency.getLong("ID")== cascurrency.getLong("ID")) {
						 yem_invoiceclaimamt = yem_invoiceclaimamt.add(yem_claimamt_z);
					 }else {
						 if(yem_Newcurrency.getLong("ID")== yem_currency.getLong("ID")) {
							 yem_invoiceclaimamt =  yem_invoiceclaimamt.add(BigDecimalUtils.div(yem_claimamt_z, yem_exrate, 10));
							 
						 }else {
							 yem_invoiceclaimamt =  yem_invoiceclaimamt.add(BigDecimalUtils.multiply(yem_claimamt_z, yem_exrate, 10));
							 
						 }
						 
					 }
				 }
			 }
		}
		return yem_invoiceclaimamt;
	}
	
	/**
	 * 重算发票已付款，及已认领金额
	 */
	public static void getInvoiceCalClaimed(long invoiceID,String invoiceDy) {
		DynamicObject invoice = BusinessDataServiceHelper.loadSingle(invoiceID, invoiceDy);
		BigDecimal yem_sumtotalamount = invoice.getBigDecimal("yem_sumtotalamount");//收付款金额（合计）
		DynamicObject yem_paymentcurrency = invoice.getDynamicObject("yem_paymentcurrency");
		BigDecimal yem_invoiceclaimamtjs = CommonUtils.getInvoiceClaimed(invoiceID, 0L,yem_paymentcurrency);

	    yem_sumtotalamount = yem_sumtotalamount.abs();//退款币别转换
		BigDecimal yem_invoiceunclaimamt =BigDecimalUtils.sub(yem_sumtotalamount, yem_invoiceclaimamtjs, 10);
		
		
		DynamicObjectCollection arrorderentryCol = invoice.getDynamicObjectCollection("yem_arrorderentry");
		BigDecimal yem_invoiceclaimamtD = CommonUtils.getInvoiceYSkClaimed(invoiceID, 0L,yem_paymentcurrency);

		for(DynamicObject arrorderentry:arrorderentryCol) {
			if(invoiceDy.equals("yem_importpresentation")) {
				arrorderentry.set("yem_paymentamt", yem_invoiceclaimamtD);//交单收款
			}else {
				arrorderentry.set("yem_receiptamt", yem_invoiceclaimamtD.add(arrorderentry.getBigDecimal("yem_lastreceiptamt")));//到单退款
			}
			
		}
		if(invoiceDy.equals("yem_importpresentation")) {
			BigDecimal actpayamt = BigDecimal.ZERO;
			for(DynamicObject arrorderentry:arrorderentryCol) {
				actpayamt = actpayamt.add(arrorderentry.getBigDecimal("yem_paymentamt"));
	    		actpayamt = actpayamt.add(arrorderentry.getBigDecimal("yem_sorpaymentamt"));
	    		actpayamt = actpayamt.subtract(arrorderentry.getBigDecimal("yem_receiptamt"));
			}
			BigDecimal yem_receiptamount= invoice.getBigDecimal("yem_receiptamount");
	    	BigDecimal yem_clbalance = yem_receiptamount.compareTo(BigDecimal.ZERO)==0?BigDecimal.ZERO:yem_receiptamount.subtract(actpayamt);
	    	invoice.set("yem_clbalance", yem_clbalance);
//		}else {
//			BigDecimal actpayamt = BigDecimal.ZERO;
//			for(DynamicObject arrorderentry:arrorderentryCol) {
//				actpayamt = actpayamt.add(arrorderentry.getBigDecimal("yem_paymentamt"));
//				actpayamt = actpayamt.add(arrorderentry.getBigDecimal("yem_receiptamt"));
//	    		actpayamt = actpayamt.add(arrorderentry.getBigDecimal("yem_sorpaymentamt"));
//			}
//			BigDecimal yem_openamount= invoice.getBigDecimal("yem_openamount");
//	    	BigDecimal yem_clbalance = yem_openamount.compareTo(BigDecimal.ZERO)==0?BigDecimal.ZERO:yem_openamount.subtract(actpayamt);
//	    	invoice.set("yem_clbalance", yem_clbalance);
		}
		invoice.set("yem_amountcaimed", yem_invoiceclaimamtjs);
		invoice.set("yem_amountuncaimed", yem_invoiceunclaimamt);
		SaveServiceHelper.save(new DynamicObject[] { invoice });
		
	}
	
	
	/**
	 * 获取发票已认领的金额
	 */
	public static BigDecimal getInvoiceClaimed(long invoiceID,long EntityId,DynamicObject yem_Newcurrency) {
		BigDecimal yem_invoiceclaimamt =BigDecimal.ZERO;
		if(invoiceID==0L) {
			return yem_invoiceclaimamt;
		}
		
		//收款已认领
		QFilter qFilter1 = new QFilter("yem_recognitionentity.yem_invoice.id", QCP.equals, invoiceID);
		QFilter qFilter2 = new QFilter("yem_recognitionentity.id", QCP.not_equals, EntityId);
		
		DynamicObject [] CasrecbillCol = BusinessDataServiceHelper.load("cas_recbill","id,billno,yem_recognitionentity.yem_invoice.id",new QFilter[] { qFilter1,qFilter2});
		for(DynamicObject Casrecbill:CasrecbillCol) {
			Casrecbill = BusinessDataServiceHelper.loadSingle(Casrecbill.getPkValue(), "cas_recbill");
			DynamicObject cascurrency = Casrecbill.getDynamicObject("currency");
			DynamicObjectCollection recognitionentityCol =  Casrecbill.getDynamicObjectCollection("yem_recognitionentity");
			for(DynamicObject recognitionentity : recognitionentityCol) {
				 DynamicObject yem_invoice = recognitionentity.getDynamicObject("yem_invoice");
				 if(yem_invoice!=null&&yem_invoice.getLong("id")==invoiceID) {
					 yem_invoice = BusinessDataServiceHelper.loadSingle(yem_invoice.getPkValue(), yem_invoice.getDynamicObjectType().getName());
					 DynamicObject yem_currency = yem_invoice.getDynamicObject("yem_currency");
					 BigDecimal yem_exrate= yem_invoice.getBigDecimal("yem_payexchangerate");
				
					 BigDecimal yem_claimamt_z= recognitionentity.getBigDecimal("yem_claimamt_z");
					 if(yem_Newcurrency.getLong("ID")== cascurrency.getLong("ID")) {
						 yem_invoiceclaimamt = yem_invoiceclaimamt.add(yem_claimamt_z);
					 }else {
						 if(yem_Newcurrency.getLong("ID")== yem_currency.getLong("ID")) {
							 yem_invoiceclaimamt =  yem_invoiceclaimamt.add(BigDecimalUtils.div(yem_claimamt_z, yem_exrate, 10));
							 
						 }else {
							 yem_invoiceclaimamt =  yem_invoiceclaimamt.add(BigDecimalUtils.multiply(yem_claimamt_z, yem_exrate, 10));
							 
						 }
						 
					 }
				 }
			 }
		}
		
		//冲销单重新认领
		QFilter qFilter5 = new QFilter("yem_invoice.id", QCP.equals, invoiceID);
		QFilter qFilter6 = new QFilter("billstatus", QCP.equals, "B");
		QFilter qFilter51 = new QFilter("yem_billtype.number", QCP.equals, "yem_cas_reversalorder_CR");
		DynamicObject [] reversalorderCol2 = BusinessDataServiceHelper.load("yem_cas_reversalorder","id,billstatus,yem_invoice.id",new QFilter[] {qFilter51, qFilter5,qFilter6});
		for(DynamicObject reversalorder:reversalorderCol2) {
			reversalorder = BusinessDataServiceHelper.loadSingle(reversalorder.getPkValue(), "yem_cas_reversalorder");
			BigDecimal yem_amountcaimed= reversalorder.getBigDecimal("yem_amountcaimed");
			DynamicObject cascurrency = reversalorder.getDynamicObject("yem_currency");
			DynamicObject yem_invoice = reversalorder.getDynamicObject("yem_invoice");
			if(yem_invoice!=null&&yem_invoice.getLong("id")==invoiceID) {
				yem_invoice = BusinessDataServiceHelper.loadSingle(yem_invoice.getPkValue(), yem_invoice.getDynamicObjectType().getName());
				DynamicObject yem_currency = yem_invoice.getDynamicObject("yem_currency");
				BigDecimal yem_exrate= yem_invoice.getBigDecimal("yem_payexchangerate");
				if(yem_Newcurrency.getLong("ID")== cascurrency.getLong("ID")) {
					yem_invoiceclaimamt = yem_invoiceclaimamt.add(yem_amountcaimed);
				}else {
					if(yem_Newcurrency.getLong("ID")== yem_currency.getLong("ID")) {
						yem_invoiceclaimamt =  yem_invoiceclaimamt.add(BigDecimalUtils.div(yem_amountcaimed, yem_exrate, 10));
					 
					}else {
						yem_invoiceclaimamt =  yem_invoiceclaimamt.add(BigDecimalUtils.multiply(yem_amountcaimed, yem_exrate, 10));
					 
					}
				 
				}
			}

		}
		return yem_invoiceclaimamt;
		
	}
	
	/**
	 * 获取订单已认领的金额(结算币别)
	 */
	public static BigDecimal getOrderClaimed(long orderID,long EntityId,String yem_claimtype,DynamicObject yem_Newcurrency) {
		BigDecimal yem_orderclaimamt =BigDecimal.ZERO;
		if(orderID==0L) {
			return yem_orderclaimamt;
		}
		
		//收款已认领
		QFilter qFilter01 = new QFilter("yem_recognitionentity.yem_claimtype", QCP.equals, yem_claimtype);
		QFilter qFilter1 = new QFilter("yem_recognitionentity.yem_order.id", QCP.equals, orderID);
		QFilter qFilter2 = new QFilter("yem_recognitionentity.id", QCP.not_equals, EntityId);
		DynamicObject [] CasrecbillCol = BusinessDataServiceHelper.load("cas_recbill","id,billno,yem_recognitionentity.yem_order.id,yem_recognitionentity.yem_claimtype",new QFilter[] {qFilter01, qFilter1,qFilter2});
		for(DynamicObject Casrecbill:CasrecbillCol) {
			Casrecbill = BusinessDataServiceHelper.loadSingle(Casrecbill.getPkValue(), "cas_recbill");
			DynamicObject cascurrency = Casrecbill.getDynamicObject("currency");
			DynamicObjectCollection recognitionentityCol =  Casrecbill.getDynamicObjectCollection("yem_recognitionentity");
			for(DynamicObject recognitionentity : recognitionentityCol) {
				DynamicObject yem_order = recognitionentity.getDynamicObject("yem_order");
				 if(yem_order!=null&&yem_order.getLong("id")==orderID&&recognitionentity.getString("yem_claimtype").equals(yem_claimtype)) {
					 yem_order = BusinessDataServiceHelper.loadSingle(yem_order.getPkValue(), yem_order.getDynamicObjectType().getName());
					 BigDecimal yem_exrate= recognitionentity.getBigDecimal("yem_exrate");
					 DynamicObject yem_currency = yem_order.getDynamicObject("yem_currency");
					 BigDecimal yem_claimamt_z= recognitionentity.getBigDecimal("yem_claimamt_z");
					 if(yem_Newcurrency.getLong("ID")== cascurrency.getLong("ID")) {
						 yem_orderclaimamt = yem_orderclaimamt.add(yem_claimamt_z);
					 }else {
						 
						 if(yem_Newcurrency.getLong("ID")== yem_currency.getLong("ID")) {
							
							 yem_orderclaimamt =  yem_orderclaimamt.add(BigDecimalUtils.div(yem_claimamt_z, yem_exrate, 10));
						 }else {
							 
							 yem_orderclaimamt =  yem_orderclaimamt.add(BigDecimalUtils.multiply(yem_claimamt_z, yem_exrate, 10));
						 }
					 }

				 }
			 }
		}
	
		//冲销单重新认领
		QFilter qFilter05 = new QFilter("yem_claimtype", QCP.equals, yem_claimtype);
		QFilter qFilter5 = new QFilter("yem_order.id", QCP.equals, orderID);
		QFilter qFilter6 = new QFilter("billstatus", QCP.equals, "B");
		QFilter qFilter71 = new QFilter("yem_billtype.number", QCP.equals, "yem_cas_reversalorder_CR");
		DynamicObject [] reversalorderCol2 = BusinessDataServiceHelper.load("yem_cas_reversalorder","id,billstatus,yem_order.id",new QFilter[] { qFilter05,qFilter5,qFilter6,qFilter71});
		for(DynamicObject reversalorder:reversalorderCol2) {
			reversalorder = BusinessDataServiceHelper.loadSingle(reversalorder.getPkValue(), "yem_cas_reversalorder");
			DynamicObject cascurrency = reversalorder.getDynamicObject("yem_currency");
			BigDecimal yem_exrate= reversalorder.getBigDecimal("yem_exrate");
			BigDecimal yem_amountcaimed= reversalorder.getBigDecimal("yem_amountcaimed");
			
			DynamicObject yem_order = reversalorder.getDynamicObject("yem_order");
			if(yem_order!=null&&yem_order.getLong("id")==orderID) {
				yem_order = BusinessDataServiceHelper.loadSingle(yem_order.getPkValue(), yem_order.getDynamicObjectType().getName());
				DynamicObject yem_currency = yem_order.getDynamicObject("yem_currency");
				
				if(yem_Newcurrency.getLong("ID")== cascurrency.getLong("ID")) {
					yem_orderclaimamt = yem_orderclaimamt.add(yem_amountcaimed);
				}else {
					
					if(yem_Newcurrency.getLong("ID")== yem_currency.getLong("ID")) {
						
						yem_orderclaimamt =  yem_orderclaimamt.add(BigDecimalUtils.div(yem_amountcaimed, yem_exrate, 10));
					}else {
						
						yem_orderclaimamt =  yem_orderclaimamt.add(BigDecimalUtils.multiply(yem_amountcaimed, yem_exrate, 10));
					}
				}
			}
			
		}
		
		return yem_orderclaimamt;
		
	}
	
	/**
	 * 获取冲销单已重新认定金额
	 */
	public static Map<String,BigDecimal> getClaimedmap(long yem_sourcebillid,long billid) {
		Map<String,BigDecimal> Claimedmap = new HashMap<String,BigDecimal>();
		BigDecimal yem_amountcaimed =BigDecimal.ZERO;
		BigDecimal yem_claimedhandling =BigDecimal.ZERO;
		BigDecimal yem_claimedcashdis =BigDecimal.ZERO;
		BigDecimal yem_amtreceiclaimed =BigDecimal.ZERO;
		BigDecimal yem_dint =BigDecimal.ZERO;
		if(yem_sourcebillid==0L) {
			return Claimedmap;
		}
		QFilter qFilter1 = new QFilter("yem_sourcebillid", QCP.equals, yem_sourcebillid);
		QFilter qFilter2 = new QFilter("id", QCP.not_equals, billid);
		DynamicObject [] reversalorderCol = BusinessDataServiceHelper.load("yem_cas_reversalorder","id,billno,yem_sourcebillid",new QFilter[] { qFilter1,qFilter2});
		for(DynamicObject reversalorder:reversalorderCol) {
			reversalorder = BusinessDataServiceHelper.loadSingle(reversalorder.getPkValue(), reversalorder.getDynamicObjectType().getName());
			yem_amountcaimed =yem_amountcaimed.add(reversalorder.getBigDecimal("yem_amountcaimed"));
			yem_claimedhandling =yem_claimedhandling.add(reversalorder.getBigDecimal("yem_claimedhandling"));
			yem_claimedcashdis =yem_claimedcashdis.add(reversalorder.getBigDecimal("yem_claimedcashdis"));
			yem_amtreceiclaimed =yem_amtreceiclaimed.add(reversalorder.getBigDecimal("yem_amtreceiclaimed"));
			yem_dint =yem_dint.add(reversalorder.getBigDecimal("yem_dint"));
			Claimedmap.put("yem_amountcaimed", yem_amountcaimed);
			Claimedmap.put("yem_claimedhandling", yem_claimedhandling);
			Claimedmap.put("yem_claimedcashdis", yem_claimedcashdis);
			Claimedmap.put("yem_amtreceiclaimed", yem_amtreceiclaimed);
			Claimedmap.put("yem_dint", yem_dint);
		}
		return Claimedmap;
		
	}
	
	/**
	 * 获取当前销售订单路径
	 * @param bill
	 */
	public static String getFrontPath(DynamicObject bill) {
		String path = bill.getDynamicObject("org").getString("name");
		long id = bill.getLong("id");
		QFilter qFilter = new QFilter("yem_orderid_s", QCP.equals, id);
		DynamicObject [] yem_purpinmatbottable_s = BusinessDataServiceHelper.load("yem_purpinmatbottable","id,billno,billstatus,yem_orderid_s,yem_orderid_p",new QFilter[] { qFilter });
		if(null != yem_purpinmatbottable_s && yem_purpinmatbottable_s.length>0) {
			for(int i=0;i<yem_purpinmatbottable_s.length;i++) {
				DynamicObject yem_purpinmatbottable = yem_purpinmatbottable_s[i];
				long yem_orderid_p = yem_purpinmatbottable.getLong("yem_orderid_p");
				DynamicObject yem_purchaseorder = BusinessDataServiceHelper.loadSingle(yem_orderid_p, "yem_purchaseorder");
				long yem_saleorderid = yem_purchaseorder.getLong("yem_saleorderid");
				if(yem_saleorderid != 0L) {
					DynamicObject yem_salesorder = BusinessDataServiceHelper.loadSingle(yem_saleorderid, "yem_salesorder");
					path = getFrontPath(yem_salesorder) + "→" + path;
				}else {
					String str = "(供应商)";
					String supplier = yem_purchaseorder.getDynamicObject("yem_cus_supplier").getString("name");
					if(path.length()>5 && path.substring(0, 5).equals(str)) {
						path = str + supplier + ";" + path;
					}else {
						path = str + supplier + "→" + path;
					}
				}
			}
		}
		return path;
	}
	
	/**
	 * 设置其他费用分录字段显示隐藏
	 * @param bill
	 * @param view
	 */
	public static void set_otherexpensesentry_visible(DynamicObject bill,IFormView view) {
		String name = bill.getDynamicObjectType().getName();
		if("yem_purchaseorder".equals(name) || "yem_salesorder".equals(name) || "yem_is_arrivalorder".equals(name) || "yem_importpresentation".equals(name)) {
			DynamicObject yem_currency = bill.getDynamicObject("yem_currency");
			long yem_currency_id = yem_currency==null?0L:yem_currency.getLong("id");
			String yem_currency_number = yem_currency==null?"":yem_currency.getString("number");
			DynamicObject yem_paymentcurrency = bill.getDynamicObject("yem_paymentcurrency");
			long yem_paymentcurrency_id = yem_paymentcurrency==null?0L:yem_paymentcurrency.getLong("id");
			String yem_paymentcurrency_number = yem_paymentcurrency==null?"":yem_paymentcurrency.getString("number");
			if(yem_currency_id == yem_paymentcurrency_id) {
				view.setVisible(false, "yem_feepriceexclud");//不含税费用单价（计价币别）
				view.setVisible(false, "yem_feeamtexclud");//不含税费用金额（计价币别）
				view.setVisible(false, "yem_expenseprice");//含税费用单价（计价币别）
				view.setVisible(false, "yem_expenseamt");//含税费用金额（计价币别）
				if("CNY".equals(yem_currency_number)) {
					view.setVisible(true, "yem_feepriceexclud_p");//不含税费用单价（收款币别）
					view.setVisible(true, "yem_feeamtexclud_p");//不含税费用金额（收款币别）
					view.setVisible(true, "yem_expenseprice_p");//含税费用单价（收款币别）
					view.setVisible(true, "yem_expenseamt_p");//含税费用金额（收款币别）
				}else {
					view.setVisible(true, "yem_feepriceexclud_p");//不含税费用单价（收款币别）
					view.setVisible(true, "yem_feeamtexclud_p");//不含税费用金额（收款币别）
					view.setVisible(false, "yem_expenseprice_p");//含税费用单价（收款币别）
					view.setVisible(false, "yem_expenseamt_p");//含税费用金额（收款币别）
				}
			}else {
				if("CNY".equals(yem_currency_number)) {
					view.setVisible(true, "yem_feepriceexclud");//不含税费用单价（计价币别）
					view.setVisible(true, "yem_feeamtexclud");//不含税费用金额（计价币别）
					view.setVisible(true, "yem_expenseprice");//含税费用单价（计价币别）
					view.setVisible(true, "yem_expenseamt");//含税费用金额（计价币别）
				}else {
					view.setVisible(true, "yem_feepriceexclud");//不含税费用单价（计价币别）
					view.setVisible(true, "yem_feeamtexclud");//不含税费用金额（计价币别）
					view.setVisible(false, "yem_expenseprice");//含税费用单价（计价币别）
					view.setVisible(false, "yem_expenseamt");//含税费用金额（计价币别）
				}
				if("CNY".equals(yem_paymentcurrency_number)) {
					view.setVisible(true, "yem_feepriceexclud_p");//不含税费用单价（收款币别）
					view.setVisible(true, "yem_feeamtexclud_p");//不含税费用金额（收款币别）
					view.setVisible(true, "yem_expenseprice_p");//含税费用单价（收款币别）
					view.setVisible(true, "yem_expenseamt_p");//含税费用金额（收款币别）
				}else {
					view.setVisible(true, "yem_feepriceexclud_p");//不含税费用单价（收款币别）
					view.setVisible(true, "yem_feeamtexclud_p");//不含税费用金额（收款币别）
					view.setVisible(false, "yem_expenseprice_p");//含税费用单价（收款币别）
					view.setVisible(false, "yem_expenseamt_p");//含税费用金额（收款币别）
				}
			}
			if("CNY".equals(yem_paymentcurrency_number)) {
				view.setVisible(true, "yem_taxratefee");//税率（%）
				view.setVisible(true, "yem_taxamountfee");//税额
			}else {
				view.setVisible(false, "yem_taxratefee");//税率（%）
				view.setVisible(false, "yem_taxamountfee");//税额
			}
		}
	}

	public static void writeInLogin(Map<String,String> datamap) {
		String opname = datamap.get("opname");
		String APInumber = datamap.get("APInumber");
		String APIname = datamap.get("APIname");
		String Status = datamap.get("Status");
		String Message = datamap.get("Message");
		String OrderNumber = datamap.get("OrderNumber");
		String stringJson = datamap.get("stringJson");

		// 根据实体名构建元数据并创建DynamicObject
		MainEntityType entityType = EntityMetadataCache.getDataEntityType("tpv_qcclog");
		DynamicObject dynamicObject = new DynamicObject(entityType);
		dynamicObject.getDataEntityType().getPrimaryKey().setValueFast(dynamicObject, ID.genLongId());
		dynamicObject.set("username", getCurrentUser().getString("name"));
		dynamicObject.set("opname", opname);
		dynamicObject.set("tpv_apinumber", APInumber);
		dynamicObject.set("opdesc", APIname);
		dynamicObject.set("opdate", new Date());
		dynamicObject.set("tpv_qccordernumber", OrderNumber);
		if(Status.equals(ConstantUtils.Status_200)){
			dynamicObject.set("tpv_description", Status+Message);
			dynamicObject.set("tpv_description_tag", stringJson);
		} else if (Status.equals(ConstantUtils.Status_404)) {
			dynamicObject.set("tpv_description", Status+"同步异常");
			dynamicObject.set("tpv_description_tag", Message);
		}else {
			dynamicObject.set("tpv_description", Status+Message);
			dynamicObject.set("tpv_description_tag", Message);
		}

		// 批量插入，需要保证objects中为同一个单据类型的DynamicObject
		List<DynamicObject> objects = new ArrayList<>();
		objects.add(dynamicObject);

		// 初始化LogORM实例
		LogORM logORM = LogORM.create();
		// 批量插入
		logORM.insert(objects);
	}
}