package com.yem.ensign.common;

import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import kd.bos.cache.CacheFactory;
import kd.bos.cache.TempFileCache;
import kd.bos.entity.*;
import kd.bos.form.*;
import kd.bos.form.control.AttachmentPanel;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.plugin.IFormPlugin;
import kd.bos.list.ListShowParameter;
import kd.bos.algo.DataSet;
import kd.bos.algo.Row;
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.db.DB;
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.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;

/**
 * 公共类
 * @author 86173
 *
 */
public class CommonUtils {

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

	/**
	 * 获取汇率
	 * @param sourceCurrencyId 源币别ID
	 * @param targetCurrencyId 目标币别ID
	 * @param orgId 组织ID
	 * @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 组织ID
	 * @return 本位币对象
	 */
	public static DynamicObject getStandardCurrency(final long orgId) {
		final DynamicObject systemStatusCtrol = getSystemStatusCtrol(orgId);
		if (systemStatusCtrol == null) {
			return null;
		}
		return systemStatusCtrol.getDynamicObject("standardcurrency");
	}

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

	/**
	 * 获取出纳系统状态控制
	 * @param orgId 组织ID
	 * @return 系统状态对象
	 */
	private static DynamicObject getSystemStatusCtrol(final long orgId) {
		final QFilter[] filters = { new QFilter("org", QCP.equals, (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 组织ID
	 * @param SystemType 业务对象标识
	 * @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 组织ID
	 * @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 组织ID
	 * @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 应用ID
	 * @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);
	}

	/**
	 * 获取默认公司抬头
	 * @param Orgid 组织ID
	 * @return
	 */
	public static long GetCompanyInfoId(long Orgid) {
		List<Object> params = new ArrayList<>();
		StringBuffer sql = new StringBuffer();
		sql.append(" select FID,fisdefault from tp_bd_companyinfo  ");
		sql.append(" where fstatus='C'  ");
		sql.append(" and fuseorg='" + Orgid + "'");
		DataSet data = DB.queryDataSet("", ConstantUtils.KZKF, sql.toString());
		long fid = 0;
		while (data.hasNext()) {
			Row row = data.next();
			if (fid == 0 || row.get("fisdefault").toString().equals("1")) {
				fid = row.getLong("FID");
			}
		}
		return fid;
	}

	/**
	 * 获取公司抬头
	 */
	public static long GetCompanyInfoIdnew(long Orgid) {
		long Companyfid = 0L;
		QFilter qFilter1 = new QFilter("org", QCP.equals, Orgid);
		QFilter qFilter2 = new QFilter("tpv_isdefault", QCP.equals, true);
		QFilter qFilter3 = new QFilter("status", QCP.equals, "C");
		DynamicObject[] Companyobj = BusinessDataServiceHelper.load("tpv_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", QCP.equals, 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));
			}
		}
	}

	/**
	 * 将源单附件同步到目标单
	 * @param sourceBillId 源单对象ID
	 * @param sourceBillformId 源单表单标识
	 * @param ExtendedbillId 目标单对象ID
	 * @param ExtendedbillformId 目标单表单标识
	 * @param attachmentpanelId 目标单附件控件标识
	 */
	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 附件来源对象ID
	 * @param sourcebillform 附件来源对象
	 * @param appId 所属应用编码 例：tp_is
	 * @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);
	}

	/**
	 * 将字符串中固定符号替换成'_'
	 * @param str 字符串
	 * @return
	 */
	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;
	}

	/**
	 * 去除字符串中固定符号
	 * @param str 字符串
	 * @return
	 */
	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("tpv_operator", puroperator);
		puroperator = BusinessDataServiceHelper.loadSingleFromCache(puroperator.getPkValue(), "bd_operator");
		model.setValue("tpv_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("tpv_department");
				if (purdep!=null) {
							
				}else {
					model.setValue("tpv_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 tpv_material 物料分类
	 * @param tpv_tradetype 贸易类型
	 */
	public static void beforeMetalcoefficientSelect(BeforeF7SelectEvent e, DynamicObject tpv_material, String tpv_tradetype) {
		if (null != tpv_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("tpv_material", QCP.equals, tpv_material.getPkValue());
			QFilter qFilter4 = new QFilter("tpv_tradetype", QCP.equals, tpv_tradetype);
			DynamicObject[] tpv_bd_metalcoefficient_s = BusinessDataServiceHelper.load("tpv_bd_metalcoefficient",
					"id,name,number",new QFilter[] { qFilter1 , qFilter2 , qFilter3 , qFilter4 }, null);
			for (int i = 0; i < tpv_bd_metalcoefficient_s.length; i++) {
				ids.add(tpv_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 物料ID
	 * @param srcUnitId 源计量单位ID
	 * @param desUnitId 目标计量单位ID
	 * @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 源计量单位ID
	 * @param desUnitId 目标计量单位ID
	 * @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("tpv_srcmuid", QCP.equals, srcUnitId).and(new QFilter("tpv_desmuid", QCP.equals, desUnitId));
    		QFilter qFilter4 = new QFilter("tpv_srcmuid", QCP.equals, desUnitId).and(new QFilter("tpv_desmuid", QCP.equals, srcUnitId));
    		QFilter qFilter5 = qFilter3.or(qFilter4);
    		DynamicObject[] tpv_measureunitconv_s = BusinessDataServiceHelper.load("tpv_measureunitconv",
    				"id,name,number,tpv_srcmuid,tpv_desmuid,tpv_numerator", new QFilter[] { qFilter1 , qFilter2 , qFilter5 }, null);
    		if(null != tpv_measureunitconv_s && tpv_measureunitconv_s.length>0) {
    			DynamicObject tpv_measureunitconv = tpv_measureunitconv_s[0];
    			DynamicObject tpv_srcmuid = tpv_measureunitconv.getDynamicObject("tpv_srcmuid");
    			long tpv_srcmuid_id = tpv_srcmuid.getLong("id");
    			DynamicObject tpv_desmuid = tpv_measureunitconv.getDynamicObject("tpv_desmuid");
    			long tpv_desmuid_id = tpv_desmuid.getLong("id");
    			BigDecimal tpv_numerator = tpv_measureunitconv.getBigDecimal("tpv_numerator");
    			if(tpv_srcmuid_id == srcUnitId && tpv_desmuid_id == desUnitId) {
    				unitRate = tpv_numerator;
    			}else if(tpv_srcmuid_id == desUnitId && tpv_desmuid_id == srcUnitId) {
    				unitRate = BigDecimalUtils.div(BigDecimal.ONE, tpv_numerator, 4);
    			}
    		}
        }
        return unitRate;
	}

	/**
	 * 弹出动态表单
	 * @param view 界面模型对象
	 * @param values 参数集合
	 * @param plugin 父界面插件
	 * @param actionId 回调标识
	 * @param formId 动态表单标识
	 */
	public static void showForm(IFormView view, Map<String, Object> values, IFormPlugin plugin,String actionId,String formId){
		FormShowParameter fsp = new FormShowParameter();
		fsp.setStatus(OperationStatus.ADDNEW);
		fsp.getOpenStyle().setShowType(ShowType.Modal);
		fsp.setCustomParams(values);
		CloseCallBack callBack = new CloseCallBack(plugin, actionId);
		fsp.setCloseCallBack(callBack);
		fsp.setFormId(formId);
		view.showForm(fsp);
	}

	/**
	 * 获取界面附件集合
	 * @param view 界面模型对象
	 * @param attachmentpanel 附件控件标识
	 * @return
	 */
	public static List<Map<String, Object>> getAttachmentData(IFormView view,String attachmentpanel){
		AttachmentPanel att = view.getControl(attachmentpanel);
		List<Map<String, Object>> attachmentData = att.getAttachmentData();
		return attachmentData;
	}

	/**
	 * 上传动态表单附件
	 * @param bill 业务单据对象
	 * @param returnData 动态表单返回数据
	 * @param attachmentpanel 附件控件标识
	 */
	public static void uploadFile(DynamicObject bill,List<Map<String, Object>> returnData,String attachmentpanel){
		if(null != returnData){
			for (Map<String, Object> map : returnData) {
				String url = (String) map.get("url");
				String name = (String) map.get("name");
				if (url.contains("configKey=redis.serversForCache&id=tempfile")) {
					url= uploadTempFile(url,name);
					map.put("url", url);
				}
				map.put("creator", UserServiceHelper.getCurrentUserId());
				map.put("modifytime", new Date().getTime());
			}
			AttachmentServiceHelper.upload(bill.getDynamicObjectType().getName(), bill.getPkValue(),attachmentpanel, returnData);
		}
	}

	/**
	 * 上传临时文件到服务器中
	 * @param url 附件url
	 * @param name 附件名称
	 * @return
	 */
	public static String uploadTempFile(String url, String name) {
		TempFileCache cache = CacheFactory.getCommonCacheFactory().getTempFileCache();
		InputStream in = cache.getInputStream(url);
		FileService service = FileServiceFactory.getAttachmentFileService();
		FileService fs = FileServiceFactory.getAttachmentFileService();
		RequestContext requestContext = RequestContext.get();
		String uuid = UUID.randomUUID().toString().replace("-", "");
		// 生成文件路径-上传附件时远程服务器需要存储文件的位置
		String pathParam = FileNameUtils.getAttachmentFileName(requestContext.getTenantId(),
				requestContext.getAccountId(), uuid, name);
		FileItem fileItem = new FileItem(name, pathParam, in);
		// cache.remove(url);
		// 上传附件到文件服务器
		String downUrl =service.upload(fileItem);
		return downUrl;
	}
}
