package yem.wm.cm.ht.form;

import java.util.ArrayList;
import java.util.EventObject;
import java.util.List;


import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.control.Control;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.list.ListShowParameter;
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.wm.cm.ht.utils.NumberChineseUtil;


/**
 * 我方合同模板
 * @author zhangh
 *
 */
public class ContractTemplateFromPlugin extends AbstractBillPlugIn implements BeforeF7SelectListener{
	@Override
	public void registerListener(EventObject e) {
		String[] control = {"yem_dept","yem_termname","yem_sharedscope"};
		for (String s : control) {
			Control yemDept = this.getControl(s);
			if (yemDept != null) {
				((BasedataEdit) yemDept).addBeforeF7SelectListener(this);
			}
		}
		this.addItemClickListeners(new String[]{"advcontoolbarap"});
	}

	@Override
	public void afterCopyData(EventObject e) {
		DynamicObjectCollection yem_contractterms = this.getModel().getEntryEntity("yem_contractterms");//合同条款分录
		for (DynamicObject contractterms : yem_contractterms) {
			contractterms.set("yem_clausescontent", contractterms.getString("yem_contentbefore_tag"));//合同条款，修改后条款
			contractterms.set("yem_clausescontent_tag", contractterms.getString("yem_contentbefore_tag"));
		}
	}

	@Override
	public void afterCreateNewData(EventObject e) {
		super.afterCreateNewData(e);
		//将汉语字段默认为语言类型	字段的默认值
		DynamicObjectCollection languagetypea = (DynamicObjectCollection)this.getModel().getValue("yem_languagetype");
		DynamicObject bd = BusinessDataServiceHelper.loadSingle("hbss_languagetype","id",new QFilter[]{new QFilter("name",QCP.equals,"汉语")});
		DynamicObject newMaterial = new DynamicObject(languagetypea.getDynamicObjectType());
		newMaterial.set("fbasedataId", bd);
		languagetypea.add(newMaterial);
		this.getView().updateView("yem_languagetype");



	}

	@Override
	public void propertyChanged(PropertyChangedArgs e) {
		String name = e.getProperty().getName();
		int rowIndex = this.getModel().getEntryCurrentRowIndex("yem_contractterms");//合同条款单据体分录
		switch (name) {
		case "yem_termname"://条款库
			this.setTermData(e);//将条款名称中的信息携带到分录信息中
			break;
		case "yem_clausetype"://条款类型
			this.setNewTermBillno();//根据序号和条款类型给条款正式编号赋值
			break;
		case "yem_contentbefore_tag":
			String yem_contentbefore = (String) this.getModel().getValue("yem_contentbefore_tag", rowIndex);
			this.getModel().setValue("yem_contentbefore", yem_contentbefore, rowIndex);//修改前条款
			break;
		case "yem_largetextfield":
			this.updateParentContent(rowIndex);
			this.setIsChange(rowIndex);//修改前条款和修改后条款不一致，是否调整改为true
			break;
		default:
		break;
		}
	}

	/**
	 * 当子单据体的内容进行修改时，会同步修改父单据体中内容
	 */
	private void updateParentContent(int rowIndex) {
		Object value = this.getModel().getValue("yem_clausescontent");
		//排除给子单据体赋值导致值改变的情况
		if(value != null) {
			DynamicObjectCollection parentryentity = this.getModel().getDataEntity(true).getDynamicObjectCollection("yem_contractterms");
			DynamicObject dynamicObject = parentryentity.get(rowIndex);
			DynamicObjectCollection yemSubentryentity = this.getModel().getEntryEntity("yem_subentryentity");
			String content = null;
			for (DynamicObject row : yemSubentryentity) {
				if(content == null) {
					content = row.getString("yem_largetextfield");
				}else{
					content += "\n" +  row.getString("yem_largetextfield");
				}
			}
			dynamicObject.set("yem_clausescontent",content);
			dynamicObject.set("yem_clausescontent_tag",content);
			this.getView().updateView("yem_contractterms");
		}
	}


	/**
	 * 修改前条款和修改后条款不一致，是否调整改为true
	 */
	private void setIsChange(int row) {
		String yem_contentbefore = (String) this.getModel().getValue("yem_contentbefore", row);
		String yem_clausescontent = (String) this.getModel().getValue("yem_clausescontent", row);
		yem_clausescontent = yem_clausescontent.trim();
		yem_contentbefore = yem_contentbefore.trim();
		//判断修改前和修改后的内容是否相同
		if (StringUtils.equals(yem_contentbefore, yem_clausescontent)) {
			this.getModel().setValue("yem_adjust", false, row);
		}else {
			this.getModel().setValue("yem_adjust", true, row);//打开是否调整按钮
		}
	}

	/**
	 * 创建分录给条款库赋值时，会根据单据头上的字段值对条款库的不同语言条款进行筛选，同时对其顺序进行相应的排列
	 */
	private void setTermData(PropertyChangedArgs e) {
		ChangeData[] changeSet = e.getChangeSet();
		IDataModel model = this.getModel();
		int index = changeSet[0].getRowIndex();
		DynamicObject yem_termname = (DynamicObject) model.getValue("yem_termname", index);//获取条款库资料对象
		if (yem_termname != null) {
			//查询合同条款库分录
			yem_termname = BusinessDataServiceHelper.loadSingleFromCache(yem_termname.getPkValue(),"yem_cm_contractterms");//查询合同条款库表
			DynamicObjectCollection entryentity = yem_termname.getDynamicObjectCollection("yem_entryentity");//合同条款库的分录
			//获取单据头中语言类型多选资料中填写的种类
			List<String> list = new ArrayList<>();
			DynamicObjectCollection languagetype = this.getModel().getDataEntity(true).getDynamicObjectCollection("yem_languagetype");
			for (DynamicObject object : languagetype) {
				DynamicObject language = object.getDynamicObject("fbasedataid");
				list.add(language.getString("name"));
			}
			//在合同条款库中筛选出，单据头中出现过的语言类型
			List<DynamicObject> libList = new ArrayList<>();
			for (DynamicObject row : entryentity) {
				String libLanguage = row.getDynamicObject("yem_languagetype").getString("name");
				if (!list.contains(libLanguage)) {
					continue;
				}
				libList.add(row);
			}
			//创建子分录
			List<DynamicObject> subList = new ArrayList<>();//保存子单据体分录
			DynamicObject dataEntity = model.getDataEntity(true);
			DynamicObjectCollection contractterms = dataEntity.getDynamicObjectCollection("yem_contractterms");
			DynamicObject parentObject = contractterms.get(index);
			DynamicObjectCollection subentryentity = parentObject.getDynamicObjectCollection("yem_subentryentity");
			subentryentity.clear();//清空子分类原有数据
			for (int i = 0 ; i < libList.size(); i++){
				subList.add(subentryentity.addNew());
			}
			String yemClouseorder = (String) model.getValue("yem_clouseorder");//条款中英文顺序
			int chiIndex = -1;//汉语在的位置
			Boolean flag = false;
			if(libList.size()>1) {
				for (int i = 0; i < libList.size(); i++) {
					String libLanguage = libList.get(i).getDynamicObject("yem_languagetype").getString("name");
					if ("汉语".equals(libLanguage)) {
						chiIndex = i;
					}
				}
				//需要更改赋值顺序的两种情况
				if(("0".equals(yemClouseorder) && chiIndex == 1) ||("1".equals(yemClouseorder) && chiIndex == 0)){
					flag = true;
				}
			}
			//交换顺序，与条款需要展示顺序相同
			if (flag){
				DynamicObject cache = libList.get(0);
				libList.add(0,libList.get(1));
				libList.add(1,cache);
			}
			//遍历子单据体并进行赋值
			String allContent = null;
			for (int i=0; i<subList.size(); i++) {
				String content = libList.get(i).getString("yem_clausecontent");
				subList.get(i).set("yem_largetextfield", content);//条款内容赋值
				subList.get(i).set("yem_largetextfield_tag",content);//条款内容赋值
				subList.get(i).set("yem_clausename", libList.get(i).getString("yem_clause"));//条跨类型赋值
				subList.get(i).set("yem_language",libList.get(i).getDynamicObject("yem_languagetype").getString("name"));//给语言赋值
				if (allContent == null){
					allContent = content;
				}else {
					allContent =  allContent + "\n" + content;//将两次内容进行拼接
				}
			}
			this.getModel().setValue("yem_clausetype",yem_termname.getDynamicObject("yem_clausetype"));//给条款类型赋值
			this.getModel().setValue(	"yem_contentbefore",allContent,index);//修改前条款
			this.getModel().setValue("yem_clausescontent",allContent,index);//修改后条款
			this.getView().updateView("yem_subentryentity");
		}
	}

	/**
	 * 根据序号和条款类型给条款正式编号赋值
	 */
	private void setNewTermBillno() {
		DynamicObjectCollection yem_contractterms = this.getModel().getEntryEntity("yem_contractterms");//单据体
		//由于可能会存在删除任意行的可能，因此这样做就能保障编号连续，且不断号
		for (int i = 0; i < yem_contractterms.size(); i++) {
			DynamicObject contractterms = yem_contractterms.get(i);//获取该行分录对象
			DynamicObject yem_clausetype = contractterms.getDynamicObject("yem_clausetype");//获取条款类型
			if (yem_clausetype != null) {
				int num = i + 2;//加2是因为约定二为合同编号的起点
				String format = NumberChineseUtil.format(num, false, false);
				this.getModel().setValue("yem_termbillno", format + "、" + yem_clausetype.getString("yem_clausename"), i);
			}
		}
	}
	
	@Override
	public void itemClick(ItemClickEvent evt) {
		String key = evt.getItemKey();
		switch (key) {
		case "tb_del"://删行
		case "yem_moveup"://上移
		case "yem_shiftdown"://下移
			this.setNewTermBillno();//根据序号和条款类型给条款正式编号赋值
			break;

		default:
			break;
		}
	}
	
	@Override
	public void afterBindData(EventObject e) {
		String name = this.getModel().getDataEntityType().getName();
		NewVersionHelper newVersionHelper = new NewVersionHelper(name);
		if (newVersionHelper.isChanged()) {
			String billstatus = (String) this.getModel().getValue("billstatus");//单据状态
			if ("A".equals(billstatus)) {
				this.getModel().setValue("yem_newtemplate", false);//是否新增模板
				DynamicObjectCollection yem_clauseimport = this.getModel().getEntryEntity("yem_contractterms");//合同条款分录
				for (int i = 0; i < yem_clauseimport.size(); i++) {
					DynamicObject clauseimport = yem_clauseimport.get(i);
					this.getModel().setValue("yem_contentbefore", clauseimport.getString("yem_clausescontent_tag"), i);
					this.getModel().setValue("yem_contentbefore_tag", clauseimport.getString("yem_clausescontent_tag"), i);
					this.getModel().setValue("yem_adjust", false, i);
				}
			}
			
		}
	}
	@Override
	public void beforeF7Select(BeforeF7SelectEvent e) {
		String name = e.getProperty().getName();
		switch (name) {
			case "yem_org"://所属组织
				this.setOrgF7Filter(e);
				break;
			case "yem_dept"://部门
			case "yem_sharedscope"://共享范围
//			this.setDeptF7Filter(e);
				break;
			case "yem_termname"://合同条款，条款库
				this.setTermF7Filter(e);
				break;
			default:
				break;
		}
	}

	/**
	 * 对条款名称按照（当前用户加入的部门和贸易类型）进行过滤
	 * @param e
	 */
	private void setTermF7Filter(BeforeF7SelectEvent e) {
		ListShowParameter showParameter = (ListShowParameter) e.getFormShowParameter();
		showParameter.getListFilterParameter().getQFilters().clear();
		String yem_tradetype = (String) this.getModel().getValue("yem_tradetype");//贸易类型
		if (StringUtils.isNotEmpty(yem_tradetype)) {
			showParameter.getListFilterParameter().setFilter(new QFilter("yem_foreigntrade", QCP.equals, yem_tradetype));
		}

	}

	/**
	 * 部门根据所属团队进行过滤
	 * @param e
	 */
	public void setDeptF7Filter(BeforeF7SelectEvent e) {
		ListShowParameter showParameter = (ListShowParameter) e.getFormShowParameter();
		showParameter.getListFilterParameter().getQFilters().clear();
		DynamicObject yem_dept = (DynamicObject) this.getModel().getValue("yem_org");
		if (yem_dept != null) {
			showParameter.getListFilterParameter().setFilter(new QFilter("structure.viewparent.name", QCP.equals, yem_dept.getString("name")));
		}
	}

	/**
	 * 所属团队过滤
	 * @param e
	 */
	private void setOrgF7Filter(BeforeF7SelectEvent e) {
		ListShowParameter showParameter = (ListShowParameter) e.getFormShowParameter();
		showParameter.getListFilterParameter().getQFilters().clear();
		//根据行政组织形态进行过滤
		showParameter.getListFilterParameter().setFilter(new QFilter("orgpattern.name", QCP.in, new String[] {"事业部","公司"}));
	}
}
