package yem.wm.cm.ht.op;

import java.util.ArrayList;
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.utils.StringUtils;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.AfterOperationArgs;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.DeleteServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import yem.wm.cm.ht.utils.ContractTemplateUtil;
import yem.wm.cm.ht.utils.NumberChineseUtil;


/**
 * 选择是否生成新的模板后，在审核时自动生成相应的模板
 * @author zhangh
 *
 */
public class Contract2ClauseAuditOp extends AbstractOperationServicePlugIn{
	
	@Override
	public void onPreparePropertys(PreparePropertysEventArgs e) {
		List<String> fieldKeys = e.getFieldKeys();
		fieldKeys.add("yem_updateterm");
		fieldKeys.add("yem_clauseimport");
		fieldKeys.add("yem_change");
		fieldKeys.add("yem_revise");
		fieldKeys.add("yem_templatename");
	}

	@Override
	public void afterExecuteOperationTransaction(AfterOperationArgs e) {
		String key = e.getOperationKey();
		switch (key) {
		case "audit":
			if (this.getOperationResult().isSuccess()) {
				DynamicObject[] dataentity = e.getDataEntities();
				//data为每个单据信息
				for (DynamicObject data : dataentity) {
					data = BusinessDataServiceHelper.loadSingleFromCache(data.getPkValue(), data.getDataEntityType().getName());
					this.createContractClauseData(data);//修改合同条款库
					this.createContractTemplateData(data);//修改合同模板
				}
			}
			break;
		default:
			break;
		}
	}

	/**
	 * 审核生成(修改合同模板)
	 * @param data
	 */
	public void createContractTemplateData(DynamicObject data) {
		String yem_revise = data.getString("yem_revise");//采购合同，模板修改
		//A新模板，B覆盖模板，C单次修改
		if (StringUtils.isNotEmpty(yem_revise)) {
			if (yem_revise.equals("A")) {
				this.createTemplateData(data);
			}else if (yem_revise.equals("B")) {
				this.updateTemplateData(data);
			}
		}
	}

	/**
	 * 修改合同模板
	 * @param data
	 */
	public void updateTemplateData(DynamicObject data) {
		DynamicObject yem_template = data.getDynamicObject("yem_template");
		if (yem_template != null) {
			yem_template = BusinessDataServiceHelper.loadSingleFromCache(yem_template.getPkValue(), "yem_cm_contracttemplate");
			this.produceTemplateData(data, yem_template, false);
		}
	}
	
	/**
	 * 新增合同模板
	 * @param data
	 */
	public void createTemplateData(DynamicObject data) {
		//获取保存新模板的模板名
		String yem_templatename = data.getString("yem_templatename");
		DynamicObject contracttemplate = BusinessDataServiceHelper.loadSingle("yem_cm_contracttemplate", "id", new QFilter[] {new QFilter("yem_templatename", QCP.equals, yem_templatename)});
		//若新模板名称在我方合同模板库不存在，则可以新建
		if (contracttemplate == null) {
			DynamicObject yem_template = BusinessDataServiceHelper.newDynamicObject("yem_cm_contracttemplate");
			this.produceTemplateData(data, yem_template, true);
		}
	}

	/**
	 * 创建合同模板数据
	 * @param data  合同实体
	 * @param yem_template 合同模板实体
	 * @param result 新增还是修改
	 */
	public void produceTemplateData(DynamicObject data, DynamicObject yem_template, boolean result) {
		yem_template.set("billstatus", "C");//单据状态设置为已审核
		yem_template.set("org", data.getDynamicObject("org"));
		yem_template.set("yem_org", data.getDynamicObject("yem_department"));  //需要修改
		yem_template.set("yem_dept", data.getDynamicObject("yem_department"));
		yem_template.set("yem_templatetype", data.getString("yem_templatetype"));//模板类型
		String templatename = data.getString("yem_templatename");
		yem_template.set("yem_templatename",templatename );//模板名称
		yem_template.set("yem_contracttype", data.getDynamicObject("yem_template").getString("yem_contracttype"));//合同类型
		yem_template.set("yem_tradetype", data.getString("yem_tradetype1"));//贸易类型
		yem_template.set("yem_status", "A");//状态：A有效   B冻结
		yem_template.set("yem_clouseorder",data.getString("yem_clousorder"));//语言呈现顺序
		ContractTemplateUtil.getMaterialList("yem_languagetype",data,yem_template,null);//语言类型进行反写
		DynamicObject yemTemplate1 = data.getDynamicObject("yem_template");
		ContractTemplateUtil.getMaterialList("yem_material",yemTemplate1,yem_template,null);//物料类型进行反写
		yem_template.set("yem_version","1");//版本号
		yem_template.set("yem_amend","C");//条款修改控制

		//我方合同模板分录修改和生成
		yem_template.getDynamicObjectCollection("yem_contractterms").clear();//清除原分录
		this.templateAdjustmentEntry(data, yem_template, result);
		OperationServiceHelper.executeOperate("save", "yem_cm_contracttemplate",
				new DynamicObject[]{yem_template}, OperateOption.create());
		data.set("yem_templateid", yem_template.getPkValue());//给采购合同合同模板id赋值
		SaveServiceHelper.save(new DynamicObject[] {data});
	}

	/**
	 * 合同模板分录修改和生成
	 * @param data 原单的数据
	 * @param yem_template 新创的我方模板动态对象
	 * @param result 新增还是修改
	 */
	private void templateAdjustmentEntry(DynamicObject data, DynamicObject yem_template, boolean result) {
		//是否新增模板
		yem_template.set("yem_newtemplate",true);
		//合同条款内容
		DynamicObjectCollection yem_clauseimport = data.getDynamicObjectCollection("yem_clauseimport");
		//我方合模板的合同分录(单据体内赋值）
		DynamicObjectCollection yem_contractterms = yem_template.getDynamicObjectCollection("yem_contractterms");
		int i = 2;//条款编号
		for (DynamicObject clauseimport : yem_clauseimport) {
			DynamicObject yem_clausetype = clauseimport.getDynamicObject("yem_clausetype");//合同条款库对象
			DynamicObject contractterms = new DynamicObject(yem_contractterms.getDynamicObjectType());//根据单据体数据类型创建单据体行动态对象
			DynamicObject clausetype = null;
			if (yem_clausetype != null) {
				yem_clausetype = BusinessDataServiceHelper.loadSingleFromCache(yem_clausetype.getPkValue(), "yem_cm_contractterms");
				contractterms.set("yem_termname", yem_clausetype);
				 clausetype = yem_clausetype.getDynamicObject("yem_clausetype");//条款类型对象
				contractterms.set("yem_clausetype", clausetype);
			}
			//条款名称
			//contractterms.set("yem_clausename", clauseimport.getString("yem_clausename"));
			//正式条款类型编号
			String format = NumberChineseUtil.format(i++, false, false);
			if (clausetype != null) {
				contractterms.set("yem_termbillno", format + "、" + clausetype.getString("name").split("、")[1]);
			}
			//修改前条款赋值
			String updatebefore = clauseimport.getString("yem_updatebefore_tag");
			contractterms.set("yem_contentbefore", updatebefore);
			contractterms.set("yem_contentbefore_tag", updatebefore);
			//修改后条款赋值
			contractterms.set("yem_clausescontent", updatebefore);
			contractterms.set("yem_clausescontent_tag", updatebefore);
			String[] text = null;
			if (updatebefore.contains("\n")){
				text = updatebefore.split("\n");
			}
			DynamicObjectCollection subentryentity = contractterms.getDynamicObjectCollection("yem_subentryentity");
			//获取单据头中语言类型多选资料中填写的种类
			List<DynamicObject> list = new ArrayList<>();
			DynamicObjectCollection languagetype = data.getDynamicObjectCollection("yem_languagetype");
			for (DynamicObject object : languagetype) {
				list.add(object.getDynamicObject("fbasedataid"));
			}
			//使语言顺序与list集合存储顺序一致
			String order = data.getString("yem_clousorder");
			if(list.size() > 1) {
				if (!(("1".equals(order) && "英语".equals(list.get(0).getString("name"))) || ("0".equals(order) && "汉语".equals(list.get(0).getString("name"))))) {
					DynamicObject obj = list.get(0);
					list.add(0, list.get(1));
					list.add(0, obj);
				}
			}
			//给我方合同模板条款赋值，保证子分录语言顺序与单据体行上要求顺序一致
			for (int j=0; j<list.size(); j++) {
				DynamicObject dynamicObject = subentryentity.addNew();
				if("汉语".equals(list.get(j).getString("name"))) {
					dynamicObject.set("yem_clausename", clauseimport.getLocaleString("yem_clausename").getLocaleValue_zh_CN());//条款名称
				}else {
					dynamicObject.set("yem_clausename", clauseimport.getLocaleString("yem_clausename").getLocaleValue_en());//条款名称
				}
				dynamicObject.set("yem_largetextfield",text[j]);//条款内容
				dynamicObject.set("yem_language",list.get(j).getString("name"));//语言
			}
			yem_contractterms.add(contractterms);
		}
	}


	/**
	 * 审核生成(修改)合同条款库
	 * @param data 采购合同单据信息
	 */
	public void createContractClauseData(DynamicObject data) {
		//修改合同条款 A存为新条款   B覆盖原有条款
		String yem_updateterm = data.getString("yem_updateterm");
		if (StringUtils.isNotEmpty(yem_updateterm)) {
			if (yem_updateterm.equals("A")) {
				this.createClausedata(data);
			}else if (yem_updateterm.equals("B")) {
				this.updateClauseData(data);
			}
		}
	}

	/**
	 * 修改合同条款库
	 * @param data
	 */
	public void updateClauseData(DynamicObject data) {
		DynamicObjectCollection yem_clauseimport = data.getDynamicObjectCollection("yem_clauseimport");
		for (DynamicObject clauseimport : yem_clauseimport) {
			if (clauseimport.getBoolean("yem_change")) {
				DynamicObject yem_clausetype = clauseimport.getDynamicObject("yem_clausetype");
				if (yem_clausetype == null) {
					DynamicObject newDynamicObject = BusinessDataServiceHelper.newDynamicObject("yem_cm_contractterms");
					this.produceClauseData(data,clauseimport, newDynamicObject, true);
				}else {
					yem_clausetype = BusinessDataServiceHelper.loadSingleFromCache(yem_clausetype.getPkValue(), "yem_cm_contractterms");
					this.produceClauseData(data,clauseimport, yem_clausetype, false);
				}
			}
		}
	}

	/**
	 * 生成合同条款库
	 * @param data 采购合同单据信息
	 */
	public void createClausedata(DynamicObject data) {
		//获取采购合同的合同条款信息
		DynamicObjectCollection yem_clauseimport = data.getDynamicObjectCollection("yem_clauseimport");
		for (DynamicObject clauseimport : yem_clauseimport) {
			//对修改的条款，在条款库中创建新条款
			if (clauseimport.getBoolean("yem_change")) {
				//创建一个合同条款库动态对象
				DynamicObject yem_cm_contractterms = BusinessDataServiceHelper.newDynamicObject("yem_cm_contractterms");
				this.produceClauseData(data, clauseimport, yem_cm_contractterms, true);
			}
		}
	}



	/**
	 * 创建合同条款库数据
	 * @param data  合同实体
	 * @param clauseimport  合同合同条款库分录实体
	 * @param yem_clausetype  合同条款库实体 
	 * @param result 新增还是修改
	 */
	public void produceClauseData(DynamicObject data, DynamicObject clauseimport, DynamicObject yem_clausetype, boolean result) {
		yem_clausetype.set("billstatus", "C");
		DynamicObject org = data.getDynamicObject("org");
		yem_clausetype.set("org", org);
		DynamicObject yemDepartment = data.getDynamicObject("yem_department");
		yem_clausetype.set("yem_org",yemDepartment );// 需要修改
		DynamicObject yemDepartment1 = data.getDynamicObject("yem_department");
		yem_clausetype.set("yem_dept",yemDepartment1);
		yem_clausetype.set("yem_version","1");

		
		DynamicObject oldclausetype = clauseimport.getDynamicObject("yem_clausetype");//合同条款库基础资料
		if (oldclausetype == null) {
			String yem_termtype = clauseimport.getString("yem_termtype");//获取条款类型
			//根据合同类型作为查询条件查询条款类型
			DynamicObject bd_typeclause = BusinessDataServiceHelper.loadSingle("yem_bd_typeclause", "id", new QFilter[] {new QFilter("name", QCP.equals, yem_termtype)});
			//若查询结果为空，则代表用户修改了条款内容（新建一个条款类型单据数据）
			if (bd_typeclause == null) {
				bd_typeclause = BusinessDataServiceHelper.newDynamicObject("yem_bd_typeclause");
				if (StringUtils.isNotEmpty(yem_termtype) && yem_termtype.contains("、")) {
					bd_typeclause.set("yem_chinanum", yem_termtype.split("、")[0]);
					bd_typeclause.set("yem_clausename", yem_termtype.split("、")[1]);
					bd_typeclause.set("name", yem_termtype);
					bd_typeclause.set("enable", "1");
					bd_typeclause.set("status", "C");
					OperationServiceHelper.executeOperate("save", "yem_bd_typeclause", new DynamicObject[] {bd_typeclause}, OperateOption.create());
				}
			}
			//给条款赋值前判断条款是否已经修改，若已经修改则新建一个条跨类型，否则使用查出来的条款
			yem_clausetype.set("yem_clausetype", bd_typeclause);
		}else {
			//查询合同条款库
			oldclausetype = BusinessDataServiceHelper.loadSingleFromCache(oldclausetype.getPkValue(), "yem_cm_contractterms");
			yem_clausetype.set("yem_clausetype", oldclausetype.getDynamicObject("yem_clausetype"));
		}
		//拿到多语言条款内容值
		String yem_updateafter = clauseimport.getString("yem_updatebefore");
		String[] updateafter = yem_updateafter.split("\n");
		yem_clausetype.set("yem_libclauselname",clauseimport.getDynamicObject("yem_clausetype").getString("yem_libclauselname"));
		//获取单据头中语言类型多选资料中填写的种类
		List<DynamicObject> list = new ArrayList<>();
		DynamicObjectCollection languagetype = data.getDynamicObjectCollection("yem_languagetype");
		for (DynamicObject object : languagetype) {
			list.add(object.getDynamicObject("fbasedataid"));
		}
		//将多语言条款顺序调整为先中文后英文
		String order = data.getString("yem_clousorder");
		if ("1".equals(order)) {
			String cache = updateafter[0];
			updateafter[0] = updateafter[1];
			updateafter[1] = cache;
		}
		//合同条款库分录赋值
		DynamicObjectCollection entryentity = yem_clausetype.getDynamicObjectCollection("yem_entryentity");
		entryentity.clear();//清空原有分录中的内容
		for (DynamicObject row : list) {
			DynamicObject dynamicObject = entryentity.addNew();
			if ("汉语".equals(row.getString("name"))) {
				dynamicObject.set("yem_clausecontent", updateafter[0]);//中文条款赋值
				dynamicObject.set("yem_clausecontent_tag", updateafter[0]);
				//条款名称赋值
				dynamicObject.set("yem_clause", clauseimport.getLocaleString("yem_clausename").getLocaleValue_zh_CN());

			}else {
				dynamicObject.set("yem_clausecontent", updateafter[1]);//英文条款内容赋值
				dynamicObject.set("yem_clausecontent_tag", updateafter[1]);
				//英文条款名称赋值
				dynamicObject.set("yem_clause", clauseimport.getLocaleString("yem_clausename").getLocaleValue_en());
			}
			dynamicObject.set("yem_languagetype",row);//语言类型赋值
		}
		yem_clausetype.set("yem_foreigntrade",data.getString("yem_tradetype1"));//贸易性质赋值

		OperationServiceHelper.executeOperate("save", "yem_cm_contractterms",
				new DynamicObject[] { yem_clausetype }, OperateOption.create());
		clauseimport.set("yem_clausetype", yem_clausetype);
		SaveServiceHelper.save(new DynamicObject[] { data });
	}
}
