package yem.wm.cm.ht.utils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.ILocaleString;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.dataentity.metadata.IDataEntityProperty;
import kd.bos.dataentity.metadata.IDataEntityType;
import kd.bos.dataentity.metadata.dynamicobject.DynamicProperty;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.ValueMapItem;
import kd.bos.entity.property.ComboProp;
import kd.bos.entity.property.EntryProp;
import kd.bos.entity.property.LinkEntryProp;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.MetadataServiceHelper;
import yem.base.common.module.version.helper.NewVersionHelper;

/**
 * 合同条款帮助类
 * @author zhangh
 *
 */
public class ContractTemplateUtil {

	/**
	 * 获取多选基础资料的值
	 *
	 * @param entryKey 分录标识
	 * @param from 取数页面
	 * @param to 赋值页面
	 * @param name 单据标识
	 * @return
	 */
	public static DynamicObjectCollection getMaterialList(String entryKey, DynamicObject from, DynamicObject to, String key) {

		DynamicObjectCollection yemLanguagetype = from.getDynamicObjectCollection(entryKey);
		DynamicObjectCollection yemLanguagetype1 = to.getDynamicObjectCollection(entryKey);
		for (DynamicObject row : yemLanguagetype) {
			String languageName = row.getDynamicObject("fbasedataid").getString("name");
			DynamicObject bd = BusinessDataServiceHelper.loadSingle(row.getDynamicObject("fbasedataid").getDataEntityType().getName(),"id",new QFilter[]{new QFilter("name",QCP.equals,languageName)});
			DynamicObject newMaterial1 = new DynamicObject(yemLanguagetype1.getDynamicObjectType());
			newMaterial1.set("fbasedataId", bd);
			yemLanguagetype1.add(newMaterial1);
		}




//		DynamicObjectCollection entrydata = data.getDynamicObjectCollection(entryKey);
//		DynamicObjectCollection materialList = newDynamicObject.getDynamicObjectCollection("yem_material");
//		for (DynamicObject entry : entrydata) {
//			if (entry != null) {
//				DynamicObject newMaterial = new DynamicObject(materialList.getDynamicObjectType());
//				newMaterial.set("fbasedataId", entry);
//				materialList.add(newMaterial);
//			}
//		}
		return yemLanguagetype1;
	}
	/**
	 * 根据挖空字段截取字符串
	 * 
	 * @param yem_clausechina 合同条款内容
	 * @param scoopField 存储该条款中所有的挖空字段
	 */
	public static void cutOutString(String yem_clausechina, List<String> scoopField) {
		String str;
		while (yem_clausechina.contains("【")) {
			String substring = yem_clausechina.substring(yem_clausechina.indexOf("【") + 1, yem_clausechina.indexOf("】"));
			str = yem_clausechina.substring(0, yem_clausechina.indexOf("【"))
					+ yem_clausechina.substring(yem_clausechina.indexOf("】") + 1);
			if (!scoopField.contains(substring)) {
				scoopField.add(substring);
			}
			yem_clausechina = str;
		}
	}

	/**
	 * 判断该挖空字段值是否为本单的挖空字段，最终scoopFieldNew 保留非本单的挖空字段
	 * @param field 挖空字段名
	 * @param scoopFieldNew 保留非本单的挖空字段
	 * @param name
	 */
	public static void hollowFieldHasOrNo(String field, List<String> scoopFieldNew, String name) {
		MainEntityType entityType = EntityMetadataCache.getDataEntityType(name);//获取需求单据的页面数据
		List<QFilter> qFilters = new ArrayList<>();
		qFilters.add(new QFilter("yem_clausekey", QCP.equals, field));//挖空字段
		qFilters.add(new QFilter("yem_billkey.number", QCP.equals, name));//需求单据
		//根据挖空字段和需求单据来查询字段对照表，查询字段标识和id
		DynamicObject bd_clausecontrast = BusinessDataServiceHelper.loadSingle("yem_bd_clausecontrast",//字段对照表
				"id,yem_fieldkey", qFilters.toArray(new QFilter[] {}));
		if (bd_clausecontrast != null) {
			String yem_fieldkey = bd_clausecontrast.getString("yem_fieldkey");//获取字段标识
			//若是本单内字段
			if (StringUtils.isNotEmpty(yem_fieldkey)){
				boolean whether = false;
				List<IDataEntityType> entryTypes = new ArrayList<>();//存放单据体的标识
				for (IDataEntityProperty item : entityType.getProperties()) {
					//判断属性类型是否为单据体但不是子单据体
					if(item instanceof EntryProp && !(item instanceof LinkEntryProp)) {
						entryTypes.add(((EntryProp) item).getItemType());
					}
					String fieldname = item.getName();
					//若在单据头中找到匹配的标识
					if (fieldname.equals(yem_fieldkey)) {
						whether = true;
					}
				}
				if (entryTypes.size() > 0) {
					for (IDataEntityType iDataEntityType : entryTypes) {
						for (IDataEntityProperty property : iDataEntityType.getProperties()) {
							String fieldname = property.getName();
							//若在单据体内找到匹配的标识
							if (fieldname.equals(yem_fieldkey)) {
								whether = true;
							}
						}
					}
				}
				if (!whether) {
					scoopFieldNew.add(field);
				}
			} else {
				scoopFieldNew.add(field);
			}
		} else {
			scoopFieldNew.add(field);
		}
	}

	/**
	 * 构建动态分录
	 * @param field
	 * @param targetBillObj
	 * @param targetNumber 
	 */
	public static void createHollowEntry(String field, DynamicObject targetBillObj, String targetNumber) {
		List<QFilter> qFilters = new ArrayList<>();
		qFilters.add(new QFilter("yem_billkey.number", QCP.equals, targetNumber));
		qFilters.add(new QFilter("yem_clausekey", QCP.equals, field));
		DynamicObject clausecontrast = BusinessDataServiceHelper.loadSingle("yem_bd_clausecontrast", "id",
				qFilters.toArray(new QFilter[] {}));
		if (clausecontrast != null) {
			DynamicObjectCollection yem_dynamicfield = targetBillObj.getDynamicObjectCollection("yem_dynamicfield");
			DynamicObject addNew = yem_dynamicfield.addNew();
			clausecontrast = BusinessDataServiceHelper.loadSingleFromCache(clausecontrast.getPkValue(),
					"yem_bd_clausecontrast");
			addNew.set("yem_fieldname", clausecontrast);
			addNew.set("yem_fieldtype", clausecontrast.getDynamicObject("yem_fieldtype"));
			addNew.set("yem_format", clausecontrast.getString("yem_format"));
			addNew.set("yem_fieldkey", clausecontrast.getString("yem_clausekey"));
		}
	}

	/**
	 * 查询出所有的本单字段，并将其字段标识作为key，该字段关系映射表为value存入到map中
	 * @param field 挖空字段
	 * @param map 返回本单挖空字段map
	 * @param name 查询单据的表名
	 */
	public static void hollowFieldHasOrNo(String field, Map<String, DynamicObject> map, String name) {
		MainEntityType entityType = EntityMetadataCache.getDataEntityType(name);
		List<QFilter> qFilters = new ArrayList<>();
		qFilters.add(new QFilter("yem_clausekey", QCP.equals, field));
		qFilters.add(new QFilter("yem_billkey.number", QCP.equals, name));//主实体对象的number存储的为单据标识
		//查询字段对照表
		DynamicObject bd_clausecontrast = BusinessDataServiceHelper.loadSingle("yem_bd_clausecontrast",
				"id,yem_fieldkey,yem_field", qFilters.toArray(new QFilter[] {}));
		if (bd_clausecontrast != null) {
			String yem_fieldkey = bd_clausecontrast.getString("yem_fieldkey");//字段对照表中的字段标识
			if (StringUtils.isNotEmpty(yem_fieldkey)) {
				List<IDataEntityType> entryTypes = new ArrayList<>();
				for (IDataEntityProperty item : entityType.getProperties()) {
					if(item instanceof EntryProp && !(item instanceof LinkEntryProp)) {
						entryTypes.add(((EntryProp) item).getItemType());//将单据体标识加入集合中
					}
					String fieldname = item.getName();
					if (fieldname.equals(yem_fieldkey)) {
						map.put(yem_fieldkey, bd_clausecontrast);
					}
				}
				if (entryTypes.size() > 0) {
					for (IDataEntityType iDataEntityType : entryTypes) {
						for (IDataEntityProperty property : iDataEntityType.getProperties()) {
							String fieldname = property.getName();
							if (fieldname.equals(yem_fieldkey)) {
								map.put(yem_fieldkey, bd_clausecontrast);
							}
						}
					}
				}
			}
		}
	}

	public static void setEntryBillkey(Map<String, DynamicObject> map, String key, DynamicObject targetBillObj, String targetNumber) {
		DynamicObject clausecontrast = map.get(key);
		clausecontrast = BusinessDataServiceHelper.loadSingleFromCache(clausecontrast.getPkValue(),
				clausecontrast.getDataEntityType().getName());
		DynamicObjectCollection yem_billentrykey = targetBillObj.getDynamicObjectCollection("yem_billentrykey");
		DynamicObject addNew = yem_billentrykey.addNew();
		addNew.set("yem_bill", key);
		String yem_field = clausecontrast.getString("yem_field");
		String field = "";
		if (yem_field.contains(".")) {
			field = yem_field.substring(0, yem_field.indexOf("."));
		}
		if (field.equals("")) {
			DynamicProperty property = EntityMetadataCache.getDataEntityType(targetNumber).getProperty(key);
			addNew.set("yem_billfieldname", property.getDisplayName());
		}else {
			DynamicObjectCollection coll = targetBillObj.getDynamicObjectCollection(field);
			DynamicProperty property = coll.getDynamicObjectType().getProperty(key);
			addNew.set("yem_billfieldname", property.getDisplayName());
		}
		
		addNew.set("yem_entrykey", field);
		addNew.set("yem_format1", clausecontrast.getString("yem_format"));
		addNew.set("yem_clausekey", clausecontrast.getString("yem_clausekey"));
	}

	public static void bringOutContractTerm(DynamicObject targetBillObj, DynamicObjectCollection yem_contractterms, String targetNumber) {
		DynamicObjectCollection yem_clauseimport = targetBillObj.getDynamicObjectCollection("yem_clauseimport");
		yem_clauseimport.clear();
		for (DynamicObject contractterms : yem_contractterms) {
			DynamicObject addNew = yem_clauseimport.addNew();
			addNew.set("yem_termtype", contractterms.getString("yem_termbillno"));
			addNew.set("yem_clausenameeng", contractterms.getString("yem_termbillno") + contractterms.getDynamicObject("yem_clausetype").getLocaleString("name").getLocaleValue_en());
			addNew.set("yem_clausetype", contractterms.getDynamicObject("yem_termname"));
			addNew.set("yem_updatebefore", contractterms.getString("yem_clausescontent"));
			DynamicObject yem_termname = contractterms.getDynamicObject("yem_termname");
			if (yem_termname != null) {
				yem_termname = BusinessDataServiceHelper.loadSingleFromCache(yem_termname.getPkValue(), "yem_cm_contractterms");
				String yem_clausechina = yem_termname.getString("yem_clausechina");
				String yem_clauseenglish = yem_termname.getString("yem_clauseenglish");
				LocaleString locStr = new LocaleString();
				locStr.setLocaleValue_en(yem_clauseenglish);
				NewVersionHelper newVersionHelper = new NewVersionHelper(targetNumber);
				if (newVersionHelper.isChanged()) {
					targetNumber = newVersionHelper.getRequireKey();
				}
				if (Arrays.asList(new String[] {"yem_is_impcontract","yem_es_salecontract"}).contains(targetNumber)) {
					locStr.setLocaleValue_zh_CN(yem_clauseenglish);
				}else {
					locStr.setLocaleValue_zh_CN(yem_clausechina);
				}
				addNew.set("yem_clausename", locStr);
			}
			
			addNew.set("yem_updatebefore_tag", contractterms.getString("yem_clausescontent"));
			addNew.set("yem_updateafter", contractterms.getString("yem_clausescontent"));
			addNew.set("yem_updateafter_tag", contractterms.getString("yem_clausescontent"));
			addNew.set("yem_printclause", contractterms.getString("yem_clausescontent"));
			addNew.set("yem_printclause_tag", contractterms.getString("yem_clausescontent"));
		}
	}

	public static void getFieldValue2UpdateAfter(String yem_bill, DynamicObject billentrykey, DynamicObject targetBillObj, String targetNumber) {
		DynamicObjectCollection yem_clauseimport = targetBillObj.getDynamicObjectCollection("yem_clauseimport");
		for (int i = 0; i < yem_clauseimport.size(); i++) {
			DynamicObject clauseimport = yem_clauseimport.get(i);
			String yem_updatebefore = clauseimport.getString("yem_updatebefore");//修改前条款内容
			List<String> list = new ArrayList<>();
			Map<String, DynamicObject> map = getKey(targetBillObj);
			String updatebefore = yem_updatebefore;
			//截取该条款中存在的挖空字段，并用list保存
			ContractTemplateUtil.cutOutString(updatebefore, list);
			String context = yem_updatebefore;
			//处理当前行所有挖空字段的值
			for (String key : list) {
				if (map.containsKey(key)) {
					DynamicObject bill = map.get(key);
					String yem_clausekey = bill.getString("yem_clausekey");
					String yem_entrykey = bill.getString("yem_entrykey");
					Map<String, String> scoopValue = getScoopValue(yem_entrykey, bill, targetNumber, targetBillObj);
					String value = scoopValue.get("value");
					String englishValue = scoopValue.get("englishValue");
					context= setupdateValue(value, englishValue, context, yem_clausekey, targetBillObj);
					if (map.containsKey(key)) {
						map.get(key).set("yem_billcontent", value);
					}
				}
				
			}
			
			//最终结果赋值，给修改后条款赋值
			clauseimport.set("yem_updateafter", context);
			clauseimport.set("yem_updateafter_tag", context);	
		}
	}
	
	private static Map<String, DynamicObject> getKey(DynamicObject targetBillObj) {
		Map<String, DynamicObject> map = new HashMap<>();
		DynamicObjectCollection yem_billentrykey = targetBillObj.getDynamicObjectCollection("yem_billentrykey");
		for (DynamicObject billentrykey : yem_billentrykey) {
			map.put(billentrykey.getString("yem_clausekey"), billentrykey);
		}
		return map;
	}

	/**
	 *	根据传入的字段标识，获取本单上的数据，并根据其对象的类型转为为相应的格式，形成中英文双份
	 * @param yem_entrykey 分录标识（即该表单上字段标识）
	 * @param bill 单据体行
	 * @param entityId 表名标识
	 * @param dataEntity 采购订单页面数据模型
	 * @return
	 */
	public static Map<String, String> getScoopValue(String yem_entrykey, DynamicObject bill, String entityId, DynamicObject dataEntity) {
		Object fieldValue = null;
		String yem_bill = bill.getString("yem_bill");//本单标识
		NewVersionHelper newVersionHelper = new NewVersionHelper(entityId);
		if (newVersionHelper.isChanged()) {
			entityId = newVersionHelper.getRequireKey();
		}
		Map<String, String> map = new HashMap<>();
		//若tpy_entrykey不为空，则代表该填充字段为单据体下的值
		if (StringUtils.isNotEmpty(yem_entrykey)) {
			DynamicObjectCollection entryEntity = dataEntity.getDynamicObjectCollection(yem_entrykey);//获取到该单据体
			if (entryEntity.size() > 0) {
				fieldValue = entryEntity.get(0).get(yem_bill);//获取获得单据体首行的值
			}
		} else {
			fieldValue = dataEntity.get(yem_bill);//该字段没在单据头上
		}
		String value = ""; // 中文
		String englishValue = ""; // 英文
		String yem_format1 = bill.getString("yem_format1");//字段类型
		if (StringUtils.isNotEmpty(yem_format1)) {
			//字段类型为单价、数量、金额、小数
			if (yem_format1.equals("PriceProp") || yem_format1.equals("QtyProp") || yem_format1.equals("AmountProp")
					|| yem_format1.equals("DecimalProp")) {
				BigDecimal bigvalue = ((BigDecimal) fieldValue).setScale(2, BigDecimal.ROUND_HALF_UP);//将Object对象转为BigDecimal类型
				if (bigvalue.compareTo(BigDecimal.ZERO) > 0) {
					value = bigvalue + "";
					englishValue = bigvalue + "";
				}
				//字段类型为用户，货币，组织，计量单位，基础资料
			} else if (yem_format1.equals("BasedataProp") || yem_format1.equals("UserProp")
					|| yem_format1.equals("OrgProp") || yem_format1.equals("CurrencyProp")
					|| yem_format1.equals("UnitProp")) {
				DynamicObject basevalue = (DynamicObject) fieldValue;//转为动态对象
				if (basevalue != null) {
					//当字段标识为yem_contract，yem_docu_bond
					if ("yem_contract".equals(yem_bill) || "yem_docu_bond".equals(yem_bill)) {
						value = basevalue.getString("number");
						englishValue = basevalue.getString("number");
					}else if ("yem_method".equals(yem_bill)) {
						//若单据体名为yem_es_salecontract，yem_is_impcontract
						if (Arrays.asList(new String[] {"yem_es_salecontract","yem_is_impcontract"}).contains(entityId)) {
							value = basevalue.getString("yem_chinese");
							englishValue = basevalue.getString("yem_english");
						}
					} else {
						value = basevalue.getLocaleString("name").getLocaleValue_zh_CN();
						englishValue = basevalue.getLocaleString("name").getLocaleValue_en();
						if (englishValue == null) {
							englishValue = value;
						}
					}
				}
				//类型为布尔类型
			} else if (yem_format1.equals("BooleanProp")) {
				Boolean boolValue = (Boolean) fieldValue;
				if (boolValue) {
					value = "是";
					englishValue = "true";
				} else {
					value = "否";
					englishValue = "false";
				}
				//类型为下拉列表
			} else if (yem_format1.equals("ComboProp")) {
				String comvalue = (String) fieldValue;
				if (StringUtils.isNotEmpty(comvalue)) {
					MainEntityType type = MetadataServiceHelper
							.getDataEntityType(dataEntity.getDataEntityType().getName());
					ComboProp ComboProp = (ComboProp) type.findProperty(yem_bill);
					List<ValueMapItem> comboItems = ComboProp.getComboItems();//得到下拉列表的所有下拉值
					for (ValueMapItem comboItem : comboItems) {
						if (comboItem.getValue().equals(comvalue)) {
							value = comboItem.getName().getLocaleValue_zh_CN();
							englishValue = comboItem.getName().getLocaleValue_en();
						}
					}
				}
				//类型为文本
			} else if (yem_format1.equals("TextProp")) {
				if (StringUtils.isNotEmpty((String) fieldValue)) {
					value = (String) fieldValue;
					englishValue = (String) fieldValue;
				}
				//类型为多语言文本
			} else if (yem_format1.equals("MuliLangTextProp")) {
				value = ((ILocaleString) fieldValue).getLocaleValue_zh_CN();
				englishValue = ((ILocaleString) fieldValue).getLocaleValue_en();
				//类型为日期或长日期
			} else if (yem_format1.equals("DateTimeProp") || yem_format1.equals("DateProp")) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Date date = (Date) fieldValue;
				if (date != null) {
					if (Arrays.asList(new String[] {"pm_purorderbill","sm_salorder"}).contains(entityId)) {
						ZoneId zoneId = ZoneId.systemDefault();
						ZonedDateTime zonedDateTime = date.toInstant().atZone(zoneId);
						LocalDate localDate = zonedDateTime.toLocalDate();
						DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
						value = localDate.format(formatter);
					}else {
						//不是单据体下的日期，就直接日期格式化
						value = sdf.format(date);
						englishValue = sdf.format(date);
					}
					
				}
				//类型为多选基础资料
			} else if (yem_format1.equals("MulBasedataProp")) {
				DynamicObjectCollection dycollValue = (DynamicObjectCollection) fieldValue;
				List<String> chineseValue = new ArrayList<>();
				List<String> engValue = new ArrayList<>();
				for (DynamicObject dycoll : dycollValue) {
					String cnValue = dycoll.getDynamicObject("fbasedataid").getLocaleString("name")
							.getLocaleValue_zh_CN();
					String enValue = dycoll.getDynamicObject("fbasedataid").getLocaleString("name").getLocaleValue_en();
					if (!chineseValue.contains(cnValue)) {
						chineseValue.add(cnValue);
					}

					if (!engValue.contains(enValue)) {
						engValue.add(enValue);
					}
				}

				value = String.join("、", chineseValue);
				englishValue = String.join("、", engValue);
				//类型为整数类型
			}else if (yem_format1.equals("IntegerProp")) {
				Integer integer = (Integer) fieldValue;
				if (integer != 0) {
					value = integer + "";
					englishValue = integer + "";
				}
			}
		}
		map.put("value", value);
		map.put("englishValue", englishValue);
		
		return map;
	}

	/**
	 *	将挖空字段需要填充的内容值传入，并替换带有挖空字段的文本，返回挖空字段文本
	 * @param yem_content 中文填充值
	 * @param yem_contentEnglish 英文填充值
	 * @param yem_updateafter 有挖空字段的文本
	 * @param yem_fieldkey 挖空字段值
	 * @param dataEntity 合同条款对应的数据模型（采购合同数据模型）
	 * @return 替换填充字段后的值
	 */
	public static String setupdateValue(String yem_content, String yem_contentEnglish, String yem_updateafter,
		String yem_fieldkey, DynamicObject dataEntity) {
			if (yem_updateafter.contains("\n")) {
				String[] updateafter = yem_updateafter.split("\n");
				for (int j = 0; j < updateafter.length; j++) {
					String update = updateafter[j];
					//填充字段存在在该段上，中文字符串填充时，填充值不能找到，到英文时就可以找到，因此就可以区分中英文
					if (yem_content != null) {
						if (update.contains("【" + yem_fieldkey + "】") && !String.join("\n", updateafter).contains(yem_content)) {
							//将填充字段替换为填充值
							updateafter[j] = update.replace("【" + yem_fieldkey + "】", yem_content);
						} else if (update.contains("【" + yem_fieldkey + "】") && String.join("\n", updateafter).contains(yem_content)) {
							if (yem_contentEnglish != null) {
								updateafter[j] = update.replace("【" + yem_fieldkey + "】", yem_contentEnglish);
							}
						}
					}
				}
				yem_updateafter = String.join("\n", updateafter);

			}else {
				if (yem_updateafter != null && yem_content != null) {
					yem_updateafter = yem_updateafter.replace("【" + yem_fieldkey + "】", yem_content);
				}
			}
		return yem_updateafter;
	}
}

	
