package yem.wm.cm.ht.op;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;



import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.args.BeforeOperationArgs;
import kd.bos.exception.KDBizException;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.coderule.CodeRuleServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
import yem.base.common.module.version.helper.NewVersionHelper;
import yem.base.common.utils.DynamicObjectUtil;


/**
 * 合同模板反写合同条款库
 * @author zhangh
 *
 */
public class ContractTemplateAuditOp extends AbstractOperationServicePlugIn {

	@Override
	public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
		String key = e.getOperationKey();
		switch (key) {
		case "audit":
			DynamicObject[] dataEntity = e.getDataEntities();
			for (DynamicObject data : dataEntity) {
				String name = data.getDataEntityType().getName();//拿到单据标识
				data = BusinessDataServiceHelper.loadSingleFromCache(data.getPkValue(), name);

				this.updateContractTermData(data);
				NewVersionHelper newVersionHelper = new NewVersionHelper(data.getDataEntityType().getName());
				if (newVersionHelper.isChanged()) {
					//若打开了是否新增模板
					if (data.getBoolean("yem_newtemplate")){
						this.createTemplate(data);
					} else {
						OperationServiceHelper.executeOperate("effectchange", name, new DynamicObject[] { data }, OperateOption.create());
						DynamicObject bill = BusinessDataServiceHelper.loadSingleFromCache(data.getLong("yem_masterid"), newVersionHelper.getRequireKey());
						bill.set("billstatus", "C");
						SaveServiceHelper.save(new DynamicObject[] { bill });
					}
				}
			}
			break;
		default:
			break;
		}
	}

	/**
	 * 审核新增合同模板
	 * @param data
	 */
	private void createTemplate(DynamicObject data) {
		if (data.getBoolean("yem_newtemplate")) {
			List<QFilter> qFilters = new ArrayList<>();
			String yem_templatename =  data.getString("yem_templatename");
			qFilters.add(new QFilter("yem_templatename", QCP.equals,yem_templatename));
			NewVersionHelper newVersionHelper = new NewVersionHelper(data.getDataEntityType().getName());
			if (newVersionHelper.isChanged()) {
				qFilters.add(new QFilter("id", QCP.not_equals, data.getLong("yem_masterid")));
			} else {
				qFilters.add(new QFilter("id", QCP.not_equals, data.getPkValue()));
			}
			//查询我方合同模板，判断给合同编号是否被占用
			DynamicObject contracttemplate = BusinessDataServiceHelper.loadSingle("yem_cm_contracttemplate",
					"id,billno", qFilters.toArray(new QFilter[] {}));
			if (contracttemplate == null) {
				DynamicObject newDynamicObject = BusinessDataServiceHelper.newDynamicObject("yem_cm_contracttemplate");
				//拷贝对象数据 分录清空全覆盖 主键清空
				DynamicObjectUtil.copyDynamicObject(data, newDynamicObject);
				newDynamicObject.set("billstatus", "C");
				String number = CodeRuleServiceHelper.getNumber("yem_cm_contracttemplate", newDynamicObject, null);
				newDynamicObject.set("billno", number);
				newDynamicObject.set("yem_version", 1);
				newDynamicObject.set("yem_masterid", null);
				newDynamicObject.set("yem_newtemplate", false);
				DynamicObjectCollection yem_contractterms = newDynamicObject.getDynamicObjectCollection("yem_contractterms");
				for (DynamicObject contractterms : yem_contractterms) {
					//是否调整按钮
					contractterms.set("yem_adjust", false);
				}
				OperationServiceHelper.executeOperate("save", "yem_cm_contracttemplate",
						new DynamicObject[] { newDynamicObject }, OperateOption.create());

				data.set("yem_effective", true);
				data.set("yem_changedate", new Date());
				data.set("yem_effectdate", new Date());
				data.set("yem_changeman", UserServiceHelper.getCurrentUserId());
				data.set("yem_effector", UserServiceHelper.getCurrentUserId());
				SaveServiceHelper.save(new DynamicObject[] { data });
				
				DynamicObject bill = BusinessDataServiceHelper.loadSingleFromCache(data.getLong("yem_masterid"), newVersionHelper.getRequireKey());
				bill.set("yem_version", data.getBigDecimal("yem_version"));
				SaveServiceHelper.save(new DynamicObject[] { bill });
			} else {
				throw new KDBizException(String.format("合同模板审核生成新的合同模板时，模板名称不允许重复，请变更模板名称。"));
			}

		}
	}

	private void updateContractTermData(DynamicObject data) {
		//A新增 B覆盖 C单次修改
		String yem_amend = data.getString("yem_amend");
		if (StringUtils.isNotEmpty(yem_amend)) {
			//合同条款分录
			DynamicObjectCollection yem_contractterms = data.getDynamicObjectCollection("yem_contractterms");//合同条款分类
			for (DynamicObject contractterms : yem_contractterms) {
				boolean yem_adjust = contractterms.getBoolean("yem_adjust");
				if (yem_adjust) {
					if (yem_amend.equals("A")) {
						this.createTermData(data, contractterms);
					} else if(yem_amend.equals("B")){
						this.updateTermData(data, contractterms);
						updateHistoryTemplate(data,contractterms);
					}
				}
			}
		}
	}

	/**
	 * 修改历史的合同模板
	 * @param data
	 * @param contractterms 
	 */
	private void updateHistoryTemplate(DynamicObject data, DynamicObject contractterms) {
		String yem_tradetype = data.getString("yem_tradetype");
		DynamicObject yem_termname = contractterms.getDynamicObject("yem_termname");
		if (yem_termname != null) {
			Long termname = yem_termname.getLong("id");
			yem_termname = BusinessDataServiceHelper.loadSingleFromCache(termname, yem_termname.getDynamicObjectType().getName());
			List<QFilter> qFilters = new ArrayList<>();
			qFilters.add(new QFilter("yem_contractterms.yem_termname", QCP.equals, termname));
			qFilters.add(new QFilter("billstatus", QCP.equals, "C"));
			qFilters.add(new QFilter("id", QCP.not_equals, data.getLong("id")));
			DynamicObject[] cm_contracttemplate = BusinessDataServiceHelper.load("yem_cm_contracttemplate", "id", qFilters.toArray(new QFilter[] {}));
			for (DynamicObject contracttemplate : cm_contracttemplate) {
				// add by lib  合同模板变更审批流中报 找不到 yem_contractterms
				contracttemplate = BusinessDataServiceHelper.loadSingleFromCache(contracttemplate.getPkValue(),contracttemplate.getDynamicObjectType().getName());
				// add by lib end
				DynamicObjectCollection yem_contractterms = contracttemplate.getDynamicObjectCollection("yem_contractterms");
				for (DynamicObject oldcontractterms : yem_contractterms) {
					DynamicObject yem_oldtermname = oldcontractterms.getDynamicObject("yem_termname");
					if (yem_oldtermname != null && yem_oldtermname.getLong("id") == termname) {
						oldcontractterms.set("yem_clausetype", yem_termname.getDynamicObject("yem_clausetype"));
						LocaleString locStr = new LocaleString();
						locStr.setLocaleValue_zh_CN(yem_termname.getString("yem_clausechina"));
						locStr.setLocaleValue_en(yem_termname.getString("yem_clauseenglish"));
						oldcontractterms.set("yem_clausename", locStr);
						DynamicObject yem_clausetype = yem_termname.getDynamicObject("yem_clausetype");
						oldcontractterms.set("yem_termbillno", yem_clausetype.getString("yem_clausename"));
						if (StringUtils.isNotEmpty(yem_tradetype)) {
							if (yem_tradetype.equals("A")) {
								String yem_clauseschina = yem_termname.getString("yem_clausecontentchina") + "\n" + yem_termname.getString("yem_clausecontentenglish");
								oldcontractterms.set("yem_clausescontent", yem_clauseschina);
								oldcontractterms.set("yem_clausescontent_tag", yem_clauseschina);
								oldcontractterms.set("yem_contentbefore", yem_clauseschina);
								oldcontractterms.set("yem_contentbefore_tag", yem_clauseschina);
							} else {
								oldcontractterms.set("yem_clausescontent", yem_termname.getString("yem_clausecontentchina"));
								oldcontractterms.set("yem_clausescontent_tag", yem_termname.getString("yem_clausecontentchina"));
								oldcontractterms.set("yem_contentbefore", yem_termname.getString("yem_clausecontentchina"));
								oldcontractterms.set("yem_contentbefore_tag", yem_termname.getString("yem_clausecontentchina"));
							}
						}
					}
				}
			}
			SaveServiceHelper.save(cm_contracttemplate);
		}
		
	}

	/**
	 * 修改合同条款库
	 * 
	 * @param data
	 * @param contractterms
	 */
	private void updateTermData(DynamicObject data, DynamicObject contractterms) {
		DynamicObject yem_termname = contractterms.getDynamicObject("yem_termname");// 获取合同条款库
		if (yem_termname != null) {
			yem_termname = BusinessDataServiceHelper.loadSingleFromCache(yem_termname.getPkValue(), "yem_cm_contractterms");
			this.setData(data, contractterms, yem_termname, false);
		}
	}

	/**
	 * 
	 * @param data 合同模板主实体
	 * @param contractterms 合同模板分录实体
	 * @param yem_termname  合同条款库实体
	 * @param changeOrNew 新增或者修改
	 */
	private void setData(DynamicObject data, DynamicObject contractterms, DynamicObject yem_termname,
			boolean changeOrNew) {
		yem_termname.set("org", data.getDynamicObject("org"));
		yem_termname.set("yem_org", data.getDynamicObject("yem_org"));
		yem_termname.set("yem_dept", data.getDynamicObject("yem_dept"));
		String yem_tradetype = data.getString("yem_tradetype");
		yem_termname.set("yem_foreigntrade", yem_tradetype);
		yem_termname.set("yem_clausetype", contractterms.getDynamicObject("yem_clausetype"));
		String yem_clauseschina = contractterms.getString("yem_clausescontent");

		if (yem_tradetype.equals("A")) {
			String[] clauseschina = yem_clauseschina.split("\n");
			yem_termname.set("yem_clausecontentchina", clauseschina[0]);
			yem_termname.set("yem_clausecontentchina_tag", clauseschina[0]);
			yem_termname.set("yem_clausecontentenglish", clauseschina[1]);
			yem_termname.set("yem_clausecontentenglish_tag", clauseschina[1]);
			yem_termname.set("yem_clausechina",
					contractterms.getLocaleString("yem_clausename").getLocaleValue_zh_CN());
			yem_termname.set("yem_clauseenglish",
					contractterms.getLocaleString("yem_clausename").getLocaleValue_en());
		} else {
			yem_termname.set("yem_clausecontentchina", yem_clauseschina);
			yem_termname.set("yem_clausecontentchina_tag", yem_clauseschina);
			yem_termname.set("yem_clausechina",
					contractterms.getLocaleString("yem_clausename").getLocaleValue_zh_CN());
		}
		yem_termname.set("billstatus", "C");
		OperationServiceHelper.executeOperate("save", "yem_cm_contractterms", new DynamicObject[] { yem_termname },
				OperateOption.create());

		contractterms.set("yem_termname", yem_termname);
		SaveServiceHelper.save(new DynamicObject[] { data });
	}

	/**
	 * 新增合同条款库
	 * 
	 * @param data 合同模板实体
	 * @param contractterms 合同模板分录实体
	 */
	private void createTermData(DynamicObject data, DynamicObject contractterms) {
		DynamicObject cm_contractterms = BusinessDataServiceHelper.newDynamicObject("yem_cm_contractterms");
		this.setData(data, contractterms, cm_contractterms, true);
	}
}
