package yem.wm.cm.ht.form;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.bill.OperationStatus;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.dataentity.entity.OrmLocaleValue;
import kd.bos.dataentity.metadata.dynamicobject.DynamicProperty;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.AfterDeleteRowEventArgs;
import kd.bos.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.CloseCallBack;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.ShowType;
import kd.bos.form.control.Control;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.TextEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.list.ListShowParameter;
import kd.bos.metadata.dao.MetaCategory;
import kd.bos.metadata.dao.MetadataDao;
import kd.bos.metadata.entity.EntityItem;
import kd.bos.metadata.entity.EntityMetadata;
import kd.bos.metadata.entity.commonfield.DateRangeField;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
import yem.base.common.module.version.helper.NewVersionHelper;
import yem.base.common.utils.YEM;
import yem.wm.cm.ht.utils.ContractTemplateUtil;
import yem.wm.cm.ht.utils.NumberChineseUtil;

/**
 * 正式合同插件
 * @author zhangh
 *
 */
public class ContractTermsFormPlugin extends AbstractBillPlugIn implements BeforeF7SelectListener{
	@Override
	public void registerListener(EventObject e) {
		((TextEdit)this.getControl("yem_content")).addButtonClickListener(this);
		((BasedataEdit)this.getControl("yem_template")).addBeforeF7SelectListener(this);
		((BasedataEdit)this.getControl("yem_templateother")).addBeforeF7SelectListener(this);
	}


	@Override
	public void afterCreateNewData(EventObject e) {
		super.afterCreateNewData(e);
		this.getView().setVisible(false,"yem_templatename");//默认设置模板名称为不可见
	}

	@Override
	public void afterDoOperation(AfterDoOperationEventArgs e) {
		super.afterDoOperation(e);
		String operateKey = e.getOperateKey();
		OperationResult operationResult = e.getOperationResult();
		if(operateKey != null && operationResult != null && operationResult.isSuccess()) {
			switch (operateKey) {
			case "submit":
			case "audit":
			case "unaudit":
				this.getView().invokeOperation("refresh");//数据加载后执行刷新操作
				break;
			default:
				break;
			}
		}
	}
	
	@Override
	public void propertyChanged(PropertyChangedArgs e) {
		String key = e.getProperty().getName();
		ChangeData[] changeSet = e.getChangeSet();
		int rowIndex = changeSet[0].getRowIndex();//修改单据体的行数
		switch (key) {
		case "yem_templatetype"://模板类型
			this.setTemplateVisible();
			break;
		case "yem_revise"://模板修订
			this.setTemplateNameVisible();
			break;
		case "yem_template"://我方合同模板
			this.updateTemplateColor("#FFFFFF");//在修改之前对上次选择的合同模板所对应的挖空字段背景颜色还原
			this.buildEntry();//构建本单的和非本单的挖空字段分录
			//buildDynamicEntry();//根据合同模板构建非本单的挖空字段分录
			//this.buildDynamicBillEntry();//构建本单分录字段标识
			this.bringOutContractTerm(key);//根据合同模板带出合同条款
			this.setTemplateVisible();//根据模板修订类型，选择页面可见性
			break;
		case "yem_updatebefore"://商品分类，合同条款，修改后条款
			this.changAdjustTrue(e, rowIndex);//调整修改后后条款之，是否调整改为true
			String yem_updatebefore = (String) this.getModel().getValue("yem_updatebefore", rowIndex);
			this.getModel().setValue("yem_updatebefore_tag", yem_updatebefore, rowIndex);
			this.updateBeforeValue(rowIndex, yem_updatebefore);//修改后条款内容发生改变，在替换挖空字段后将值赋给打印条款内容
			break;
		case "yem_updatebefore_tag":
			String yem_updateafter_tag = (String) this.getModel().getValue("yem_updatebefore_tag", rowIndex);
			this.getModel().setValue("yem_updatebefore", yem_updateafter_tag, rowIndex);//商品分类，合同条款，修改后条款
			break;
		case "yem_change"://合同条款内容是否修改
			this.changeColourSetting(rowIndex);//若修改了模板信息，则行改变背景颜色
			break;
		case "yem_changenum"://商品分类，合同条款，调整次数
			this.changeColourSetting(rowIndex);
			break;
		case "yem_contentvalue"://内容值（非本单）
			this.updateAfterValue(rowIndex);//改变合同动态中的内容值
			break;
		case "yem_englishcontent"://英文内容值（非本单）
			this.setChinaContent(rowIndex);//挖空字段英文内容值发生改变，给中文内容值的英文框赋值
			break;
		case "yem_fieldtype"://商品分类，挖空字段，字段类型
			this.setLockContent(rowIndex);//合同动态中的【字段类型】基础资料为基础资料、下拉列表、日期等字段类型，锁定内容值
			break;
		case "yem_clausetype"://商品分类，合同条款，合同条款
			this.changeClauseType(rowIndex);//新增行添加合同条款携带相关信息
			break;
		default:
			break;
		}
		//更改本单内的挖空字段值
		DynamicObjectCollection yem_billentrykey = this.getModel().getEntryEntity("yem_billentrykey");//商品分录，挖空字段单据体
		//遍历挖空字段取出本单标识，若该标识和此次更改数据标识相同，则代表更改数据为挖空字段值，执行挖空字段回填
		for (DynamicObject billentrykey : yem_billentrykey) {
			String yem_bill = billentrykey.getString("yem_bill");
			if (yem_bill.equals(key)) {
				this.getFieldValue2UpdateAfter(yem_bill, billentrykey);//挖空字段值改变给修改后条款赋值
			}
			//给挖空字段添加背景值
			this.backgroundColor(billentrykey, "#e5e5e5");
		}
	}

	/**
	 * 构建本单和非本单的挖空字段
	 */
	private void buildEntry() {

		//从文本字段中截取挖空字段
		List<String> scoopField = this.getHollowFieldList();
		//构建本单的挖空字段
		Map<String, DynamicObject> map = new HashMap<>();//存储本单存在的挖空字段
		if (scoopField.size() > 0) {
			for (String field : scoopField) {
				this.hollowFieldHasOrNo(field, map);//获取挖空字段中的本单字段，并字段标识作为key，value为查询到的整体字段映射表数据
			}
		}
		this.getModel().deleteEntryData("yem_billentrykey");
		if (map.size() > 0) {
			for (String key : map.keySet()) {
				setEntryBillkey(map, key);//给实体对象赋值吧？
			}
		}

		//构建非本单的挖空字段
		List<String> list = getHollowFieldInBell();//得到本单挖空字段
		//删除scoopField中包含strings的内容
		Iterator<String> iterator = scoopField.iterator();
		while(iterator.hasNext()){
			String s = iterator.next();
			if(list.contains(s)){
				iterator.remove();
			}
		}
		//清空上次模板中构建的非本单挖空字段数据
		this.getModel().deleteEntryData("yem_dynamicfield");
		for(String field : scoopField) {
			this.createHollowEntry(field);//构建非本单的挖空分录
		}
	}

	/**
	 * 获取本单的挖空字段
	 * @return list接收我方模板中存在的本单挖空字段
	 */
	public List<String> getHollowFieldInBell(){
		DynamicObjectCollection yemBillentrykey = this.getModel().getEntryEntity("yem_billentrykey");
		List<String> list = new ArrayList<>();//保存本单的挖空字段值
		for (DynamicObject dynamicObject : yemBillentrykey) {
			String string1 = dynamicObject.getString("yem_clausekey");//获取本单挖空字段的挖空字段值
			list.add(string1);
		}

		return list;
	}

	/**
	 * 构建本单分录字段标识
	 */
	public void buildDynamicBillEntry() {
		List<String> scoopField = this.getHollowFieldList();//从文本字段中截取挖空字段
		Map<String, DynamicObject> map = new HashMap<>();//存储本单存在的挖空字段
		if (scoopField.size() > 0) {
			for (String field : scoopField) {
				this.hollowFieldHasOrNo(field, map);//获取挖空字段中的本单字段，并字段标识作为key，value为查询到的整体字段映射表数据
			}
		}
		this.getModel().deleteEntryData("yem_billentrykey");
		if (map.size() > 0) {
			for (String key : map.keySet()) {
				setEntryBillkey(map, key);//给实体对象赋值吧？
			}
		}
	}


	/**
	 * 根据合同模板构建合同动态字段分录
	 */
	public void buildDynamicEntry() {
		List<String> scoopField = this.getHollowFieldList();//从文本字段中截取挖空字段
		List<String> scoopFieldNew = new ArrayList<>();//存储非本单的挖空字段值
		//若我方合同模板中存在挖空字段
		if (scoopField.size() > 0) {
			for (String field : scoopField) {
				this.hollowFieldHasOrNo(field, scoopFieldNew);//判断该挖空字段值是否为本单的挖空字段，最终scoopFieldNew 保留非本单的挖空字段
			}
		}
		//清空上次模板中构建的非本单挖空字段数据
		this.getModel().deleteEntryData("yem_dynamicfield");
		if (scoopFieldNew.size() > 0) {
			for (String field : scoopFieldNew) {
				this.createHollowEntry(field);//构建非本单的挖空分录
			}
		}
	}


	private void setTemplateNameVisible() {
		IFormView view = this.getView();
		Object revise = this.getModel().getValue("yem_revise");
		Object template = this.getModel().getValue("yem_template");
		if("A".equals(revise) && template != null ) {
			view.setVisible(true,"yem_templatename");
		}else {
			view.setVisible(false,"yem_templatename");
		}
	}

	/**
	 * 根据模板类型内容值选择性展示数据
	 */
	private void setTemplateVisible() {
		IFormView view = this.getView();
		Object value = this.getModel().getValue("yem_templatetype");
		List<String> list1 = new ArrayList<>();
		List<String> list2 = new ArrayList<>();
		list1.add("yem_template");//我方合同模板
		list1.add("yem_contracttype");//合同类型
		list1.add("yem_revise");//模板修订
		list1.add("yem_contracttype");//模板修订
		list1.add("yem_updateterm");//修改合同条款
		list1.add("yem_clausemodify");//是否修改
		list2.add("yem_templateother");

		//根据条款类型选择可见的页面元素
		List<String> list = list1;
		if ("B".equals(value)) {
			list1 = list2;
			list2 = list;
		}
		//设置可见性
		for (String s : list1) {
			view.setVisible(true,s);
		}
		for (String s : list2) {
			view.setVisible(false,s);
		}
	}


	@Override
	public void afterDeleteRow(AfterDeleteRowEventArgs e) {
		if (StringUtils.equals("yem_clauseimport", e.getEntryProp().getName())){
			// 在此添加业务逻辑
			int[] rowIndexs = e.getRowIndexs();
			//删除后的单据体
			DynamicObjectCollection yemClauseimport = this.getModel().getEntryEntity("yem_clauseimport");
			//删除的不为最后一行情况
			if(yemClauseimport.size() != rowIndexs[0]){
				for (int i = rowIndexs[0]; i<yemClauseimport.size(); i++){
					DynamicObject dynamicObject = yemClauseimport.get(i);
					String number = NumberChineseUtil.format(i+2,false,false);
					String string = dynamicObject.getString("yem_termtype");
					String content = string.split("、")[1];
					this.getModel().setValue("yem_termtype",number + "、" + content ,i);
				}
			}

		}
	}


	/**
	 * 新增行添加合同条款携带相关信息（疑惑）
	 * @param rowIndex
	 */
	private void changeClauseType(int rowIndex) {
		DynamicObject yem_clausetype = (DynamicObject) this.getModel().getValue("yem_clausetype", rowIndex);//商品分类，合同条款，合同条款
		if (yem_clausetype != null) {
			yem_clausetype = BusinessDataServiceHelper.loadSingleFromCache(yem_clausetype.getPkValue(),
					yem_clausetype.getDynamicObjectType().getName());
			DynamicObject clausetype = yem_clausetype.getDynamicObject("yem_clausetype");//条款类型
			String yem_clausecontentchina = yem_clausetype.getString("yem_clausecontentchina_tag");//条款内容(中文)
			String yem_clausecontentenglish = yem_clausetype.getString("yem_clausecontentenglish_tag");//条款内容(英文)
			String entityId = this.getView().getEntityId();
			NewVersionHelper newVersionHelper = new NewVersionHelper(entityId);
			if (newVersionHelper.isChanged()) {
				entityId = newVersionHelper.getRequireKey();
			}
			String content = yem_clausecontentchina;
			if (!Arrays.asList(new String[] {"pm_purorderbill","sm_salorder"}).contains(entityId)) {
				content = yem_clausecontentchina + "\n" + yem_clausecontentenglish;
			}
			List<String> scoopField = new ArrayList<>();
			String hollowField = content;
			if (StringUtils.isNotEmpty(hollowField)) {
				//截取该条款中存在的挖空字段，并用list保存
				ContractTemplateUtil.cutOutString(hollowField, scoopField);
			}
			List<String> scoopFieldNew = new ArrayList<>();
			DynamicObjectCollection yem_dynamicfield = this.getModel().getEntryEntity("yem_dynamicfield");
			List<String> yem_fieldkey = yem_dynamicfield.stream().map(x->x.getString("yem_fieldkey")).collect(Collectors.toList());
			if (scoopField.size() > 0) {
				for (String field : scoopField) {
					if (!yem_fieldkey.contains(field)) {
						this.hollowFieldHasOrNo(field, scoopFieldNew);
					}
				}
			}
			if (scoopFieldNew.size() > 0) {
				for (String field : scoopFieldNew) {
					if (!yem_fieldkey.contains(field)) {
						this.createHollowEntry(field);//构建动态挖空字段
					}
				}
			}
			Map<String, DynamicObject> map = new HashMap<>();
			if (scoopField.size() > 0) {
				for (String field : scoopField) {
					this.hollowFieldHasOrNo(field, map);
				}
			}
			DynamicObjectCollection yem_billentrykey = this.getModel().getEntryEntity("yem_billentrykey");
			List<String> yem_bill = yem_billentrykey.stream().map(x->x.getString("yem_bill")).collect(Collectors.toList());
			if (map.size() > 0) {
				for (String key : map.keySet()) {
					if (!yem_bill.contains(key)) {
						setEntryBillkey(map, key);
					}
				}
			}
			String name = clausetype.getString("name");
			String format = NumberChineseUtil.format(rowIndex + 2, false, false);
			name = format + "、" + clausetype.getString("yem_clausename");
			this.getModel().beginInit();
			this.getModel().setValue("yem_termtype", name, rowIndex);
			this.getModel().setValue("yem_clausename", clausetype.getLocaleString("name"), rowIndex);
			this.getModel().setValue("yem_clausenameeng", name + clausetype.getLocaleString("name").getLocaleValue_en(), rowIndex);
			this.getModel().setValue("yem_printclause", content, rowIndex);
			this.getModel().setValue("yem_printclause_tag", content, rowIndex);
			this.getModel().setValue("yem_updatebefore", content, rowIndex);
			this.getModel().setValue("yem_updatebefore_tag", content, rowIndex);
			this.getModel().setValue("yem_updateafter", content, rowIndex);
			this.getModel().setValue("yem_updateafter_tag", content, rowIndex);
			this.getModel().endInit();
			this.getView().updateView("yem_clauseimport");
			
			DynamicObjectCollection billentrykey = this.getModel().getEntryEntity("yem_billentrykey");
			for (DynamicObject entrykey : billentrykey) {
				String bill = entrykey.getString("yem_bill");
				getFieldValue2UpdateAfter(bill, entrykey);
			}
		}
	}

	/**
	 *本单挖空字段赋值
	 * @param map 本单的挖空字段标识和字段映射表
	 * @param key 字段标识
	 */
	private void setEntryBillkey(Map<String, DynamicObject> map, String key) {
		//字段映射表对象
		DynamicObject clausecontrast = map.get(key);
		clausecontrast = BusinessDataServiceHelper.loadSingleFromCache(clausecontrast.getPkValue(), clausecontrast.getDataEntityType().getName());
		int row = this.getModel().createNewEntryRow("yem_billentrykey");//创建一行本单挖空字段分录
		this.getModel().setValue("yem_bill", key, row);
		String yem_field = clausecontrast.getString("yem_field");//字段全称
		String field = "";
		//为单据体下的字段，或者复杂实体的子属性如 billentry.owner
		if (yem_field.contains(".")) {
			field = yem_field.substring(0, yem_field.indexOf("."));//只获取点之前的数据
		}
		//若单据体标识为空，则代表不是单据体下数据
		if (field.equals("")) {
			DynamicProperty property = EntityMetadataCache.getDataEntityType(this.getView().getEntityId()).getProperty(key);
			this.getModel().setValue("yem_billfieldname", property.getDisplayName(), row);//给字段名称赋值，获取property.getDisplayName()
		}else {
			//得到该单据体动态对象
			DynamicObjectCollection coll = this.getModel().getDataEntity(true).getDynamicObjectCollection(field);
			DynamicProperty property = coll.getDynamicObjectType().getProperty(key);
			this.getModel().setValue("yem_billfieldname", property.getDisplayName(), row);
		}
		this.getModel().setValue("yem_entrykey", field, row);//给分录标识赋值，只有两次层时才有值，记录其分录名
		this.getModel().setValue("yem_format1", clausecontrast.getString("yem_format"), row);//字段类型，显示格式
		this.getModel().setValue("yem_clausekey", clausecontrast.getString("yem_clausekey"), row);//字段对照,挖空字段
	}

	/**
	 * 挖空字段英文内容值发生改变，给中文内容值的英文框赋值
	 * @param rowIndex
	 */
	private void setChinaContent(int rowIndex) {
		String yem_englishcontent = (String) this.getModel().getValue("yem_englishcontent", rowIndex);
		if (YEM.isNotEmpty(yem_englishcontent)) {
			LocaleString local = new LocaleString();
			OrmLocaleValue yem_contentvalue = (OrmLocaleValue) this.getModel().getValue("yem_contentvalue", rowIndex);
			local.setLocaleValue_zh_CN(yem_contentvalue.getLocaleValue_zh_CN());
			local.setLocaleValue_en(yem_englishcontent);
			this.getModel().setValue("yem_contentvalue", local, rowIndex);
		}
	}

	/**
	 * 在修改之前对上次选择的合同模板中所对应的本单挖空字段背景颜色还原
	 * @param color
	 */
	private void updateTemplateColor(String color) {
		//挖空字段本单字段
		IDataModel model = this.getModel();
		DynamicObjectCollection yem_billentrykey = model.getEntryEntity("yem_billentrykey");//本单挖空字段单据体
		for (DynamicObject billentrykey : yem_billentrykey) {
			backgroundColor(billentrykey, color);
		}
	}

	/**
	 * 给挖空字段添加背景值
	 * @param billentrykey 本单挖空字段的单据体动态对象
	 * @param color 设置的颜色
	 */
	private void backgroundColor(DynamicObject billentrykey, String color) {
		IFormView view = this.getView();
		String yem_bill = billentrykey.getString("yem_bill");//得到上次模板本单的挖空字段标识
		String idByNumber = MetadataDao.getIdByNumber(this.getView().getEntityId(), MetaCategory.Entity);
		EntityMetadata meta = (EntityMetadata) MetadataDao.readRuntimeMeta(idByNumber, MetaCategory.Entity);
		List<EntityItem<?>> items = meta.getItems();
		for (EntityItem<?> entityItem : items) {
			//是否为日期范围字段
			if (entityItem instanceof DateRangeField) {
				DateRangeField item = (DateRangeField) entityItem;
				String startDateFieldKey = item.getStartDateFieldKey();//开始时间
				String endDateFieldKey = item.getEndDateFieldKey();//结束时间
				//当上次模板的数据与此次获取到数据一致时
				if (yem_bill.equals(startDateFieldKey) || yem_bill.equals(endDateFieldKey)) {
					yem_bill = item.getKey();//获取日期范围本单标识
				}
			}
		}
		String yem_entrykey = billentrykey.getString("yem_entrykey");//获取单据体下的分录名
		if (!"".equals(yem_entrykey)) {
			YEM.changeCellColor(view, yem_entrykey, yem_bill, 0, color);
		} else {
			YEM.changeCtlColor(view, yem_bill, color);
		}

	}

	/**
	 * 合同动态中的【字段类型】基础资料为基础资料、下拉列表、日期等字段类型，锁定内容值
	 * @param rowIndex
	 */
	private void setLockContent(int rowIndex) {
		DynamicObject yem_fieldtype = (DynamicObject) this.getModel().getValue("yem_fieldtype", rowIndex);
		if (yem_fieldtype != null) {
			//获取挖空字段
			String yem_keytype = yem_fieldtype.getString("yem_keytype");
			List<String> keytype = Arrays.asList(new String[]{"ComboProp","BasedataProp","UnitProp","UserProp","OrgProp","CurrencyProp","MulBasedataProp","DateTimeProp"});
			//若当前类型不是基础资料，下拉列表，日期这三种类型，则就锁定内容区
			if (keytype.contains(yem_keytype)) {
				this.getView().setEnable(false, rowIndex, "yem_contentvalue");
			}else {
				//锁定挖空字段内容值
				this.getView().setEnable(true, rowIndex, "yem_contentvalue");
			}
		}
	}

	/**
	 * 修改前条款内容发生改变，将值赋给修改后内容
	 * @param rowIndex
	 */
	private void updateBeforeValue(int rowIndex, String yem_updatebefore) {
		List<String> list = new ArrayList<>();
		DynamicObject dataEntity = this.getModel().getDataEntity(true);
		Map<String, DynamicObject> map = getKey();//获取挖空字段单据体内容（本单）
		String updatebefore = yem_updatebefore;
		DynamicObjectCollection yem_dynamicfield = this.getModel().getEntryEntity("yem_dynamicfield");//非本单的挖空字段单据体
		//map集合结构为key为挖空标识，value为本行动态对象
		Map<String, DynamicObject> collect = yem_dynamicfield.stream().collect(Collectors.toMap(x->x.getString("yem_fieldkey"), y->y));
		//截取该条款中存在的挖空字段，并用list保存
		ContractTemplateUtil.cutOutString(updatebefore, list);
		//在给打印条款赋值前，需要先将挖空字段空替换
		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 = ContractTemplateUtil.getScoopValue(yem_entrykey, bill, this.getView().getEntityId(), dataEntity);
				String value = scoopValue.get("value");
				String englishValue = scoopValue.get("englishValue");
				//给单据体赋值
				yem_updatebefore= ContractTemplateUtil.setupdateValue(value, englishValue, yem_updatebefore, yem_clausekey, dataEntity);
			}
			//若是非本单的挖空字段
			if (collect.containsKey(key)) {
				//获得挖空字段内容值
				DynamicObject bill = collect.get(key);
				String value = bill.getLocaleString("yem_contentvalue").getLocaleValue_zh_CN();
				String englishValue = bill.getLocaleString("yem_contentvalue").getLocaleValue_en();
				if (YEM.isNotEmpty(value)) {
					//修改挖空字段值
					yem_updatebefore= ContractTemplateUtil.setupdateValue(value, englishValue, yem_updatebefore, key, dataEntity);
				}
			}
		}
		//更改打印条款的内容值
		this.getModel().setValue("yem_updateafter", yem_updatebefore, rowIndex);//为打印条款赋值
		this.getModel().setValue("yem_updateafter_tag", yem_updatebefore, rowIndex);
	}

	/**
	 * 改变非本单挖空字段的内容值后，会动态将合同条款所对应的挖空字段进行填充
	 */
	public void updateAfterValue(int rowIndex) {
		DynamicObject tpv_dynamicfield = this.getModel().getEntryRowEntity("yem_dynamicfield", rowIndex);
		String tpv_content = tpv_dynamicfield.getLocaleString("yem_contentvalue").getLocaleValue_zh_CN();
		String tpv_contentEnglish = tpv_dynamicfield.getLocaleString("yem_contentvalue").getLocaleValue_en();
		String tpv_fieldkey = tpv_dynamicfield.getString("yem_fieldkey");
		DynamicObjectCollection tpv_clauseimport = this.getModel().getEntryEntity("yem_clauseimport");
		for (int i = 0; i < tpv_clauseimport.size(); i++) {
			DynamicObject clauseimport = tpv_clauseimport.get(i);
			String tpv_updateafter = clauseimport.getString("yem_updatebefore");
			if (tpv_updateafter.contains(tpv_fieldkey)) {
				String printContent = ContractTemplateUtil.setupdateValue(tpv_content, tpv_contentEnglish, tpv_updateafter, tpv_fieldkey, null);
				//this.getModel().setValue("yem_change", true, i);
				this.getModel().setValue("yem_updateafter",printContent,i);//为打印条款赋值
			}
		}
	}


	/**
	 * 动态字段的挖空内容（非本单）
	 * @return 
	 */
	private Map<String, DynamicObject> getDynamicKey() {
		Map<String, DynamicObject> map = new HashMap<>();
		DynamicObjectCollection yem_billentrykey = this.getModel().getEntryEntity("yem_dynamicfield");
		for (DynamicObject billentrykey : yem_billentrykey) {
			map.put(billentrykey.getString("yem_fieldkey"), billentrykey);
		}
		return map;
	}

	/**
	 * 挖空字段值改变给修改后条款赋值
	 * @param fieldkey 本单的挖空字段标识
	 * @param billentrykey 挖空字段单据体行
	 */
	public void getFieldValue2UpdateAfter(String fieldkey, DynamicObject billentrykey) {
		
		DynamicObject dataEntity = this.getModel().getDataEntity(true);
		DynamicObjectCollection yem_clauseimport = dataEntity.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();//获取挖空字段（本单）
			Map<String, DynamicObject> dynamicKey = getDynamicKey();//获取挖空字段（非本单）
			String updatebefore = yem_updatebefore;
			ContractTemplateUtil.cutOutString(updatebefore, list);//截取字符串获取挖空字段值
			String context = yem_updatebefore;
			//处理当前行所有挖空字段的值，（list为单据行的挖空字段）
			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");//分录标识（若本单字段为单据体下的信息，则改值就是单据体对应的标识）
					//this.getView().getEntityId() 表名标识
					//根据挖空字段标识，获取本单挖空字段的挖空值
					Map<String, String> scoopValue = ContractTemplateUtil.getScoopValue(yem_entrykey, bill, this.getView().getEntityId(), dataEntity);
					String value = scoopValue.get("value");//得到中文值
					String englishValue = scoopValue.get("englishValue");//得到英文值
					//更改挖空字段对应的中英文挖空值（使用replace替换）
					context= ContractTemplateUtil.setupdateValue(value, englishValue, context, yem_clausekey, dataEntity);
					if (map.containsKey(key)) {
						//对本单挖空字段的，所赋予的挖空值进行填充，否则不知道该字段赋予了何值
						this.getModel().setValue("yem_billcontent", value, map.get(key).getInt("seq") - 1);//给字段内容赋值，每个挖空字段占据一行。
					}
				}
				//挖空字段值为非本单字段
				if (dynamicKey.containsKey(key)) {
					DynamicObject bill = dynamicKey.get(key);
					//非本单的挖空值只有用户填充后才能获取到，换言之就直接从挖空字段非本单数据区获取
					String yem_contentvalue = bill.getString("yem_contentvalue");//获取非本单挖空字段的填充值
					if (YEM.isNotEmpty(yem_contentvalue)) {
						String value = bill.getLocaleString("yem_contentvalue").getLocaleValue_zh_CN();
						String englishValue = bill.getLocaleString("yem_contentvalue").getLocaleValue_en();
						//更改挖空字段对应的挖空值
						context = ContractTemplateUtil.setupdateValue(value, englishValue, context, key, dataEntity);
					}
				}
			}
			//最终结果赋值，给修改后条款赋值
			this.getModel().setValue("yem_updateafter", context, i);
			this.getModel().setValue("yem_updateafter_tag", context, i);
		}
	}



	/**
	 * 获取合同条款中的内容
	 */
	public Map<String, DynamicObject> getKey() {
		Map<String, DynamicObject> map = new HashMap<>();
		DynamicObjectCollection yem_billentrykey = this.getModel().getEntryEntity("yem_billentrykey");//挖空字段单据体
		for (DynamicObject billentrykey : yem_billentrykey) {
			map.put(billentrykey.getString("yem_clausekey"), billentrykey);//key 字段对照条款标识
		}
		return map;
	}

	/**
	 * 获取挖空字段中的本单字段
	 * 
	 * @param field
	 * @param map
	 */
	public Map<String, DynamicObject> hollowFieldHasOrNo(String field, Map<String, DynamicObject> map) {
		String name = this.getModel().getDataEntityType().getName();//获取表名
		ContractTemplateUtil.hollowFieldHasOrNo(field, map, name);
		return map;
	}

	/**
	 * 是否调整为true之后，行改变背景颜色
	 * 
	 * @param rowIndex
	 */
	public void changeColourSetting(int rowIndex) {
		Boolean yem_change = (Boolean) this.getModel().getValue("yem_change", rowIndex);
		List<String> fieldList = Arrays
				.asList(new String[] { "yem_termtype", "yem_updatebefore", "yem_updateafter", "yem_change", "yem_clausename" });
		//若修改按钮勾选上，则对条款类型，修改前，修改后，是否改变，条款名称进行背景颜色改变
		if (yem_change) {
			for (String field : fieldList) {
				//YEM.changeCellColor(this.getView(),"yem_clauseimport","#FFFFCC", , rowIndex, this.getView());
				YEM.changeRowColor(this.getView(),"yem_clauseimport",rowIndex,"#FFC125","#000000");
			}
		} else {
			for (String field : fieldList) {
				YEM.changeRowColor(this.getView(),"yem_clauseimport",rowIndex,"#FFFFFF","#000000");
				//TwoOpenCommFuncUtil.changeFrameColour(field, "rgba(240,232,229,0.8)", "yem_clauseimport", rowIndex,
			}
		}
		// add by 2023/6/6  lib   分录是否调整影响表头条款修改字段，审批流配置标志需要
		int rows = this.getView().getModel().getEntryRowCount("yem_clauseimport"); //合同条款分录
		Boolean clausemodify = false;
		for (int i= 0; i< rows;i++) {
			if ((Boolean) this.getModel().getValue("yem_change", i)) clausemodify = true;
		}
		//若有条款进行了修改，则勾选上表头中条款修改按钮，
		this.getView().getModel().setValue("yem_clausemodify", clausemodify);
	}

	/**
	 * 调整修改后条款之后，是否调整改为true
	 * 
	 * @param e
	 * @param rowIndex
	 */
	public void changAdjustTrue(PropertyChangedArgs e, int rowIndex) {
		String yem_updatebefore = (String) this.getModel().getValue("yem_updatebefore", rowIndex);//修改后条款
		String yem_printclause = (String) this.getModel().getValue("yem_printclause", rowIndex);//修改前条款
		//合同条款修改前后内容对比，是否一致进行判断
		if (yem_updatebefore.equals(yem_printclause)) {
			this.getModel().setValue("yem_change", false, rowIndex);//为是否调整字段赋值
		}else {
			this.getModel().setValue("yem_change", true, rowIndex);
		}
	}

	/**
	 * 根据合同模板带出合同条款
	 */
	public void bringOutContractTerm(String key) {
		DynamicObject yem_template = (DynamicObject) this.getModel().getValue("yem_template");
		//删除上个合同模板合同条款单据体中内容
		this.getModel().deleteEntryData("yem_clauseimport");



		if (yem_template != null) {
			//查询我方模板表中数据，获取我方合同模板中，单据体信息
			yem_template = BusinessDataServiceHelper.loadSingleFromCache(yem_template.getPkValue(),"yem_cm_contracttemplate");
			//读取语言呈现顺序字段给正式合同给字段赋值（作用：生成相应模板时候知道上一个模板中语言的先后顺序）
			this.getModel().setValue("yem_clousorder",yem_template.getString("yem_clouseorder"));
			//携带出我方合同模板中的语言类型，为正式合同赋值
			DynamicObjectCollection yemLanguagetype = yem_template.getDynamicObjectCollection("yem_languagetype");
			DynamicObjectCollection yemLanguagetype1 = this.getModel().getDataEntity(true).getDynamicObjectCollection("yem_languagetype");
			yemLanguagetype1.clear();
			for (DynamicObject row : yemLanguagetype) {
				String languageName = row.getDynamicObject("fbasedataid").getString("name");
				DynamicObject bd = BusinessDataServiceHelper.loadSingle("hbss_languagetype","id",new QFilter[]{new QFilter("name",QCP.equals,languageName)});
				DynamicObject newMaterial1 = new DynamicObject(yemLanguagetype.getDynamicObjectType());
				newMaterial1.set("fbasedataId", bd);
				yemLanguagetype1.add(newMaterial1);
			}
			this.getView().updateView("yem_languagetype");

			//遍历我方模板中单据体的数据
			DynamicObjectCollection yem_contractterms = yem_template.getDynamicObjectCollection("yem_contractterms");
			for (DynamicObject contractterms : yem_contractterms) {
				this.getModel().beginInit();
				int row = this.getModel().createNewEntryRow("yem_clauseimport");//合同条款内容
				//为采购合同的合同条款分录赋值
				this.getModel().setValue("yem_termtype", contractterms.getString("yem_termbillno"), row);//条款类型
				//条款英文名称
				this.getModel().setValue("yem_clausenameeng", contractterms.getString("yem_termbillno") + contractterms.getDynamicObject("yem_clausetype").getLocaleString("name").getLocaleValue_en(), row);
				this.getModel().setValue("yem_clausetype", contractterms.getDynamicObject("yem_termname"), row);//合同条款
				this.getModel().setValue("yem_updatebefore", contractterms.getString("yem_clausescontent"), row);//修改后条款
				DynamicObject yem_termname = contractterms.getDynamicObject("yem_termname");//条款库
				if (yem_termname != null) {
					//查询该条合同条款条款名称
					String yem_clausechina = null;
					String yem_clauseenglish = null;
					yem_termname = BusinessDataServiceHelper.loadSingleFromCache(yem_termname.getPkValue(), "yem_cm_contractterms");
					DynamicObjectCollection subentryentity = yem_termname.getDynamicObjectCollection("yem_entryentity");
					for (DynamicObject r : subentryentity) {
						if ("汉语".equals(r.getDynamicObject("yem_languagetype").getString("name"))) {
							yem_clausechina = r.getString("yem_clause");
						}else {
							yem_clauseenglish = r.getString("yem_clause");
						}
					}

					LocaleString locStr = new LocaleString();
					locStr.setLocaleValue_en(yem_clauseenglish);
					String entityId = this.getView().getEntityId();//当前表名（采购合同表名）
					NewVersionHelper newVersionHelper = new NewVersionHelper(entityId);
					if (newVersionHelper.isChanged()) {
						entityId = newVersionHelper.getRequireKey();
					}
					if (Arrays.asList(new String[] {"yem_is_impcontract","yem_es_salecontract"}).contains(entityId)) {
						locStr.setLocaleValue_zh_CN(yem_clauseenglish);
					}else {
						locStr.setLocaleValue_zh_CN(yem_clausechina);
					}
					this.getModel().setValue("yem_clausename", locStr, row);//条款名称赋值
				}
				String string = contractterms.getString("yem_clausescontent");
				this.getModel().setValue("yem_updatebefore_tag",string, row);
				this.getModel().setValue("yem_updateafter", string, row);//修改前
				this.getModel().setValue("yem_updateafter_tag", string, row);
				this.getModel().setValue("yem_printclause", string, row);//打印内容
				this.getModel().setValue("yem_printclause_tag", string, row);
				this.getModel().endInit();
			}
		}
		//获取挖空字段单据体，虽然刚导入我方模板时，挖空字段大部分值需要我们手工录入，但是本单数据有些在特定情况下已经赋值了，因此需要在此判断，给能赋值的字段提前赋值。
		DynamicObjectCollection yem_billentrykey = this.getModel().getEntryEntity("yem_billentrykey");
		for (DynamicObject billentrykey : yem_billentrykey) {
			String yem_bill = billentrykey.getString("yem_bill");//本单标识（采购合同字段的标识），map中key
			getFieldValue2UpdateAfter(yem_bill, billentrykey);//根据标识和单据体信息去本单查询数据并修改挖空字段的值
		}
		this.getView().updateView("yem_clauseimport");
	}

	/**
	 * 从文本字段中截取挖空字段
	 * 
	 * @return 我方模板合同条款库中所有的挖空字段
	 */
	public List<String> getHollowFieldList() {
		DynamicObject yem_template = (DynamicObject) this.getModel().getValue("yem_template");//我方合同
		List<String> scoopField = new ArrayList<>();
		if (yem_template != null) {
			yem_template = BusinessDataServiceHelper.loadSingleFromCache(yem_template.getPkValue(), "yem_cm_contracttemplate");//我方合同模板动态对象
			DynamicObjectCollection yem_contractterms = yem_template.getDynamicObjectCollection("yem_contractterms");
			for (DynamicObject contractterms : yem_contractterms) {
				DynamicObject yem_termname = contractterms.getDynamicObject("yem_termname");//条款库
				if (yem_termname != null) {
					String yem_clausechina = contractterms.getString("yem_clausescontent");//合同条款内容
					if (StringUtils.isNotEmpty(yem_clausechina)) {
						ContractTemplateUtil.cutOutString(yem_clausechina, scoopField);//以中括号截取字符串
					}
				}
			}
		} else {
			this.getModel().deleteEntryData("yem_dynamicfield");//清空非本单挖空字段值
		}
		return scoopField;
	}

	/**
	 * 构建挖空分录
	 * @param field 挖空字段名
	 */
	public void createHollowEntry(String field) {
		List<QFilter> qFilters = new ArrayList<>();
		String name = this.getModel().getDataEntityType().getName();
		//根据需求单据与条款字段标识（挖空字段）作为依据查询字段表
		qFilters.add(new QFilter("yem_billkey.number", QCP.equals, name));
		qFilters.add(new QFilter("yem_clausekey", QCP.equals, field));
		DynamicObject clausecontrast = BusinessDataServiceHelper.loadSingle("yem_bd_clausecontrast", "id,yem_fieldtype",
				qFilters.toArray(new QFilter[] {}));
		//判空处理
		if (clausecontrast != null) {
			//查询到具体的数据
			clausecontrast = BusinessDataServiceHelper.loadSingleFromCache(clausecontrast.getPkValue(),"yem_bd_clausecontrast");
			int row = this.getModel().createNewEntryRow("yem_dynamicfield");//商品分录下的挖空字段
			//为非本单的挖空字段赋值
			this.getModel().setValue("yem_fieldname", clausecontrast, row);//挖空字段名

			//非本单字段类型赋值
			DynamicObject yemFieldtype = clausecontrast.getDynamicObject("yem_fieldtype");
			this.getModel().setValue("yem_fieldtype", yemFieldtype, row);//挖空字段类型

		 	//this.getModel().setValue("yem_format", clausecontrast.getString("yem_format"), row);//挖空字段类型（作废）
			this.getModel().setValue("yem_fieldkey", clausecontrast.getString("yem_clausekey"), row);//挖空字段的字段标识
		}
	}

	/**
	 * 判读挖空字段是否在本单据中是否存在，如果存在，在挖空字段集合中删除
	 * 
	 * @param field
	 * @param scoopFieldNew
	 */
	public void hollowFieldHasOrNo(String field, List<String> scoopFieldNew) {
		String name = this.getModel().getDataEntityType().getName();
		ContractTemplateUtil.hollowFieldHasOrNo(field, scoopFieldNew, name);//判读挖空字段是否在本单据中是否存在，如果存在，在挖空字段集合中删除
	}

	



	@Override
	public void click(EventObject e) {
		String key = ((Control) e.getSource()).getKey();
		switch (key) {
		case "yem_content":
			this.skipControlForm(e);
			break;
		default:
			break;
		}
	}

	/**
	 * 根据合同动态中的字段类型跳转动态表单
	 * @param e
	 */
	public void skipControlForm(EventObject e) {
		int index = this.getModel().getEntryCurrentRowIndex("yem_dynamicfield");
		DynamicObject yem_dynamicfield = this.getModel().getEntryRowEntity("yem_dynamicfield", index);
		DynamicObject yem_fieldtype = yem_dynamicfield.getDynamicObject("yem_fieldtype");//拿到字段类型
		if (yem_fieldtype != null) {
			yem_fieldtype = BusinessDataServiceHelper.loadSingleFromCache(yem_fieldtype.getPkValue(), "yem_bd_fieldtype");
			String yem_keytype = yem_fieldtype.getString("yem_keytype");
			if (StringUtils.isNotEmpty(yem_keytype)) {
				switch (yem_keytype) {
				case "ComboProp":
					this.skipPullDownList(yem_fieldtype);//跳转下拉列表控件
					break;
				
				case "BasedataProp":
				case "UnitProp":
				case "UserProp":
				case "OrgProp":
				case "CurrencyProp":
				case "MulBasedataProp":
					this.skipInitialValue(yem_fieldtype);//跳转基础资料
					break;
				
				case "DateTimeProp":
					this.skipDateControl(yem_fieldtype);//跳转日期控件
					break;

				default:
					break;
				}
			}
		}
	}

	/**
	 * 跳转日期控件
	 * @param yem_fieldtype
	 */
	public void skipDateControl(DynamicObject yem_fieldtype) {
		FormShowParameter showParameter = new FormShowParameter();
		showParameter.setStatus(OperationStatus.ADDNEW);
		showParameter.getOpenStyle().setShowType(ShowType.Modal);
		showParameter.setFormId("md_forexquote_date");
		showParameter.setCloseCallBack(new CloseCallBack(this, "md_forexquote_date"));
		this.getView().showForm(showParameter);
	}

	/**
	 * 跳转基础资料
	 * @param yem_fieldtype
	 */
	public void skipInitialValue(DynamicObject yem_fieldtype) {
		//获取字段类型中主实体对象
		DynamicObject yem_billkey = yem_fieldtype.getDynamicObject("yem_billkey");
		if (yem_billkey != null) {
			FormShowParameter showParameter = new FormShowParameter();
			showParameter.setStatus(OperationStatus.ADDNEW);
			showParameter.getOpenStyle().setShowType(ShowType.Modal);
			showParameter.setCustomParam("billkey", yem_billkey.getString("number"));
			showParameter.setFormId("yem_cm_basedata");
			showParameter.setCloseCallBack(new CloseCallBack(this, "yem_cm_basedata"));
			this.getView().showForm(showParameter);
		}
	}

	/**
	 * 跳转下拉列表控件
	 * @param yem_fieldtype
	 */
	public void skipPullDownList(DynamicObject yem_fieldtype) {
		//获取下拉分录对象
		DynamicObjectCollection yem_pulldownentry = yem_fieldtype.getDynamicObjectCollection("yem_pulldownentry");
		List<Map<String, Object>> list = new ArrayList<>();
		//获取下拉列表值，并存入map集合
		for (DynamicObject pulldownentry : yem_pulldownentry) {
			Map<String, Object> map = new HashMap<>();
			map.put("EnName", pulldownentry.getLocaleString("yem_fcaption").getLocaleValue_en());
			map.put("CnName", pulldownentry.getLocaleString("yem_fcaption").getLocaleValue_zh_CN());
			map.put("Value", pulldownentry.getString("yem_fvalue"));
			map.put("ImageKey", "");
			if (map.size() > 0){
				list.add(map);
			}
		}
		
		if (list.size() > 0) {
			FormShowParameter showParameter = new FormShowParameter();
			showParameter.setStatus(OperationStatus.ADDNEW);
			showParameter.getOpenStyle().setShowType(ShowType.Modal);
			showParameter.setFormId("yem_cm_comboitemssel");
			showParameter.setCustomParam("comboProp", list);
			showParameter.setCloseCallBack(new CloseCallBack(this, "yem_cm_comboitemssel"));
			this.getView().showForm(showParameter);
		}
	}
	
	@Override
	public void closedCallBack(ClosedCallBackEvent e) {
		String key = e.getActionId();
		Object returnData = e.getReturnData();
		switch (key) {
		case "yem_cm_basedata":
			this.backBasedValue(returnData);
			break;
		case "md_forexquote_date":
			this.backDateValue(returnData);
			break;
		case "yem_cm_comboitemssel":
			this.backPullDownValue(returnData);
			break;

		default:
			break;
		}
	}

	/**
	 * 跳转下拉列表控件，返回数据
	 * @param returnData
	 */
	public void backPullDownValue(Object returnData) {
		DynamicObject data = (DynamicObject) returnData;
		if (data != null) {
			int index = this.getModel().getEntryCurrentRowIndex("yem_dynamicfield");
			LocaleString local = new LocaleString();
			String yem_fcaptionCn = data.getLocaleString("yem_fcaption").getLocaleValue_zh_CN();
			String yem_fcaptionEn = data.getLocaleString("yem_fcaption").getLocaleValue_en();
			String yem_englishcontent = (String) this.getModel().getValue("yem_englishcontent", index);
			if (YEM.isNotEmpty(yem_englishcontent)) {
				yem_fcaptionEn = yem_englishcontent;
			}
			local.setLocaleValue_zh_CN(yem_fcaptionCn);
			local.setLocaleValue_en(yem_fcaptionEn);
			DynamicObject yem_dynamicfield = this.getModel().getEntryRowEntity("yem_dynamicfield", index);
			yem_dynamicfield.set("yem_contentvalue", local);
			this.getView().updateView("yem_dynamicfield");
			this.getView().setEnable(false, index, "yem_contentvalue");
			this.updateCasule(yem_dynamicfield, yem_fcaptionCn, yem_fcaptionEn);
		}
	}

	/**
	 * 合同动态分录中点击文本框按钮，弹出框回填信息之后，修改合同条款分录中的值
	 * @param yem_dynamicfield
	 * @param yem_fcaptionCn
	 * @param yem_fcaptionEn
	 */
	public void updateCasule(DynamicObject yem_dynamicfield, String yem_fcaptionCn, String yem_fcaptionEn) {
		String yem_fieldkey = yem_dynamicfield.getString("yem_fieldkey");
		DynamicObject dataEntity = this.getModel().getDataEntity(true);
		DynamicObjectCollection yem_clauseimport = this.getModel().getEntryEntity("yem_clauseimport");
		for (int i = 0; i < yem_clauseimport.size(); i++) {
			DynamicObject clauseimport = yem_clauseimport.get(i);
			String yem_updatebefore = clauseimport.getString("yem_updatebefore");
			if (yem_updatebefore.contains(yem_fieldkey)) {
				List<String> list = new ArrayList<>();
				Map<String, DynamicObject> map = getKey();
				Map<String, DynamicObject> dynamicKey = getDynamicKey();
				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 = ContractTemplateUtil.getScoopValue(yem_entrykey, bill, this.getView().getEntityId(), dataEntity);
						String value = scoopValue.get("value");
						String englishValue = scoopValue.get("englishValue");
						context= ContractTemplateUtil.setupdateValue(value, englishValue, context, yem_clausekey, dataEntity);
					}
					
					if (dynamicKey.containsKey(key)) {
						DynamicObject bill = dynamicKey.get(key);
						String yem_contentvalue = bill.getString("yem_contentvalue");
						if (YEM.isNotEmpty(yem_contentvalue)) {
							String value = bill.getLocaleString("yem_contentvalue").getLocaleValue_zh_CN();
							String englishValue = bill.getLocaleString("yem_contentvalue").getLocaleValue_en();
							context = ContractTemplateUtil.setupdateValue(value, englishValue, context, key, dataEntity);
						}
					}
				}
				context = ContractTemplateUtil.setupdateValue(yem_fcaptionCn, yem_fcaptionEn, context, yem_fieldkey, dataEntity);
				
				this.getModel().setValue("yem_updateafter", context, i);
				this.getModel().setValue("yem_updateafter_tag", context, i);
			}
		}
		
	}

	/**
	 * 跳转日期控件，返回数据
	 * @param returnData
	 */
	public void backDateValue(Object returnData) {
		Date data = (Date) returnData;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		int index = this.getModel().getEntryCurrentRowIndex("yem_dynamicfield");
		if (data != null) {
			LocaleString local = new LocaleString();
			String yem_fcaptionCn = "";
			String yem_fcaptionEn = "";
			String entityId = this.getView().getEntityId();
			if (Arrays.asList(new String[] {"pm_purorderbill","sm_salorder"}).contains(entityId)) {
				ZoneId zoneId = ZoneId.systemDefault();
				ZonedDateTime zonedDateTime = data.toInstant().atZone(zoneId);
				LocalDate localDate = zonedDateTime.toLocalDate();
				DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
				yem_fcaptionCn = localDate.format(formatter);
				local.setLocaleValue_zh_CN(yem_fcaptionCn);
				local.setLocaleValue_en(yem_fcaptionEn);
			}else {
				yem_fcaptionCn = sdf.format(data);
				yem_fcaptionEn = sdf.format(data);
				String yem_englishcontent = (String) this.getModel().getValue("yem_englishcontent", index);
				if (YEM.isNotEmpty(yem_englishcontent)) {
					yem_fcaptionEn = yem_englishcontent;
				}
				local.setLocaleValue_zh_CN(yem_fcaptionCn);
				local.setLocaleValue_en(yem_fcaptionEn);
			}
			DynamicObject yem_dynamicfield = this.getModel().getEntryRowEntity("yem_dynamicfield", index);
			yem_dynamicfield.set("yem_contentvalue", local);
			this.getView().updateView("yem_dynamicfield");
			this.getView().setEnable(false, index, "yem_contentvalue");
			this.updateCasule(yem_dynamicfield, yem_fcaptionCn, yem_fcaptionEn);
		}
	}

	/**backPullDownValue
	 * 跳转基础资料控件，返回数据
	 * @param returnData
	 */
	@SuppressWarnings("unchecked")
	public void backBasedValue(Object returnData) {
		int index = this.getModel().getEntryCurrentRowIndex("yem_dynamicfield");
		List<DynamicObject> list = (List<DynamicObject>) returnData;
		if (list != null) {
			List<String> CnValue = new ArrayList<>();
			List<String> EnValue = new ArrayList<>();
			List<String> basedid = new ArrayList<>();
			for (DynamicObject bill : list) {
				CnValue.add(bill.getLocaleString("yem_fcaption").getLocaleValue_zh_CN());
				EnValue.add(bill.getLocaleString("yem_fcaption").getLocaleValue_en());
				basedid.add(bill.getString("yem_baseid"));
			}
			String yem_englishcontent = (String) this.getModel().getValue("yem_englishcontent", index);
			if (YEM.isNotEmpty(yem_englishcontent)) {
				EnValue.clear();
				EnValue.add(yem_englishcontent);
			}
			LocaleString local = new LocaleString();
			local.setLocaleValue_zh_CN(String.join("、", CnValue));
			local.setLocaleValue_en(String.join("、", EnValue));
			DynamicObject yem_dynamicfield = this.getModel().getEntryRowEntity("yem_dynamicfield", index);
			yem_dynamicfield.set("yem_contentvalue", local);
			yem_dynamicfield.set("yem_baseid", String.join("、", basedid));
			this.getView().updateView("yem_dynamicfield");
			this.getView().setEnable(false, index, "yem_contentvalue");
			this.updateCasule(yem_dynamicfield, String.join("、", CnValue), String.join("、", EnValue));
		}
	}

	@Override
	public void beforeF7Select(BeforeF7SelectEvent e) {
		String name = e.getProperty().getName();
		switch (name) {
		case "yem_template":
			//case "yem_templateother":
//			trmplateF7Filter(e);
			break;
		default:
			break;
		}
	}

	/**
	 * 对我方合同模板根据部门进行过滤
	 * @param e
	 */
	public void trmplateF7Filter(BeforeF7SelectEvent e) {
		ListShowParameter showParameter = (ListShowParameter) e.getFormShowParameter();
		showParameter.getListFilterParameter().getQFilters().clear();
		long currentUserId = UserServiceHelper.getCurrentUserId();//获得当前登录用户
		DynamicObject adminorg = BusinessDataServiceHelper.loadSingle("bos_adminorg", "id", new QFilter[] {new QFilter("number", QCP.equals, "Gent")});
		DynamicObject bos_user = BusinessDataServiceHelper.loadSingleFromCache(currentUserId, "bos_user");
		if (bos_user != null) {
			List<Long> dept = new ArrayList<>();//当前用户所加入的部门id
			DynamicObjectCollection entryentity = bos_user.getDynamicObjectCollection("entryentity");
			for (DynamicObject row : entryentity) {
				dept.add(row.getDynamicObject("dpt").getLong("id"));
			}
			if (dept.size() > 0 && !dept.contains(adminorg.getLong("id"))) {
				QFilter qFilter = new QFilter("yem_dept", QCP.in, dept).or(new QFilter("yem_sharedscope.fbasedataid.id", QCP.in, dept));
				showParameter.getListFilterParameter().setFilter(qFilter);
			}
			//根据贸易类型过滤合同模板
			Object value = this.getModel().getValue("yem_tradetype1");
			QFilter qFilter = new QFilter("yem_tradetype",QCP.equals,value);
			showParameter.getListFilterParameter().setFilter(qFilter);


		}
	}


	@Override
	public void afterBindData(EventObject e) {
		this.changeBillEmptyAdjust();
		DynamicObjectCollection yem_clauseimport = this.getModel().getEntryEntity("yem_clauseimport");
		for (int i = 0; i < yem_clauseimport.size(); i++) {
			DynamicObject clauseimport = yem_clauseimport.get(i);
			if (clauseimport.getBoolean("yem_change")) {
				changeColourSetting(i);
			}
		}

		DynamicObjectCollection yem_dynamicfield = this.getModel().getEntryEntity("yem_dynamicfield");
		for (int rowIndex = 0; rowIndex < yem_dynamicfield.size(); rowIndex++) {
			this.setLockContent(rowIndex);
		}
	}

	/**
	 * 变更单清空合同条款中的是否调整字段
	 */
	public void changeBillEmptyAdjust() {
		String name = this.getModel().getDataEntityType().getName();
		NewVersionHelper newVersionHelper = new NewVersionHelper(name);
		if (newVersionHelper.isChanged()) {
			DynamicObjectCollection yem_clauseimport = this.getModel().getEntryEntity("yem_clauseimport");
			for (int i = 0; i < yem_clauseimport.size(); i++) {
				this.getModel().setValue("yem_change", false, i);
				this.getModel().setValue("yem_changenum", 1, i);
			}
		}
	}

}
