package com.yem.ensign.weboffice.dynamic;

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

import com.yem.ensign.common.BigDecimalUtils;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.form.FormShowParameter;
import kd.bos.form.control.Button;
import kd.bos.form.control.Control;
import kd.bos.form.control.Label;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.mvc.form.helper.WebOfficeBrowserHelper;
import kd.bos.mvc.form.helper.WebOfficeBrowserParam;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.AttachmentServiceHelper;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;

/**
 * weboffice模板选择表单插件
 * @author hdd
 * @date 2020-08-13 下午3:28:16
 */
public class WebOfficeModelChoiceEdit extends AbstractFormPlugin {

	@Override
	public void afterCreateNewData(EventObject e) {
		super.afterCreateNewData(e);
		String supplier = "";
		FormShowParameter showParameter = this.getView().getFormShowParameter();
		Map<String, Object> cusMap = showParameter.getCustomParams();
		boolean issupplier = false;
		if (cusMap.containsKey("yem_bill")) {
			String yem_bill = cusMap.get("yem_bill").toString();
			long yem_billId = BigDecimalUtils.toBigDecimal(cusMap.get("yem_billId")).longValue();
			QFilter qFilter = new QFilter("id", QCP.equals, yem_billId);
			DynamicObject [] objs = BusinessDataServiceHelper.load(yem_bill,"id",new QFilter[] { qFilter });
			if(objs==null || objs.length==0) {
				this.getView().showMessage("请先保存单据！");
				return;
			}else {
				if (yem_bill.equals("yem_is_impcontract")&&cusMap.get("supplier")!=null) {
					supplier = cusMap.get("supplier").toString();
					issupplier = true;
				}

				boolean yem_isinvoicepg = false;
				if(cusMap.containsKey("isInvoice")) {
					yem_isinvoicepg = true;
				}
				QFilter qFilter1 = new QFilter("status", QCP.equals, "C");
				QFilter qFilter2 = new QFilter("yem_bill", QCP.equals, yem_bill);
				QFilter qFilter3 = new QFilter("yem_isinvoicepg", QCP.equals, yem_isinvoicepg);
				DynamicObject[] webofficemodels = BusinessDataServiceHelper.load("yem_webofficemodel",
						"id,number,name,yem_supplier,yem_credittemplate,yem_materialgroup,yem_deporg", new QFilter[] { qFilter1, qFilter2, qFilter3 });
				// 信用证模板条款
				Map credittemplateMap = new HashMap();
				// 供应商
				Map supplierMap = new HashMap();
				if ("yem_is_creditletter".equals(yem_bill)) {
					DynamicObject creditletter = BusinessDataServiceHelper.loadSingle(yem_billId, yem_bill);
					DynamicObjectCollection yem_credittemplates = creditletter
							.getDynamicObjectCollection("yem_credittemplate");

					if (yem_credittemplates != null && yem_credittemplates.size() > 0) {
						for (int n = 0; n < yem_credittemplates.size(); n++) {
							DynamicObject yem_credittemplate = yem_credittemplates.get(n);
							yem_credittemplate = yem_credittemplate.getDynamicObject("fbasedataid");
							if (yem_credittemplate != null) {
								credittemplateMap.put(yem_credittemplate.getPkValue(), yem_credittemplate);
							}
						}
					}
				}
				if (webofficemodels != null && webofficemodels.length > 0) {
					UserServiceHelper helper=new UserServiceHelper();
					long userId=helper.getCurrentUserId();
					long userMainOrgId = helper.getUserMainOrgId(userId);
					List ids = new ArrayList();
					for (int i = 0; i < webofficemodels.length; i++) {
						DynamicObject webofficemodel = webofficemodels[i];
						//物料分类
						boolean ismaterialgroupid = cusMap.get("yem_ismaterialgroupid")==null?false:(boolean) cusMap.get("yem_ismaterialgroupid");//是否根据物料分类过滤
						if(ismaterialgroupid) {
							long materialgroupid = cusMap.get("yem_materialgroupid")==null?0L:(long)cusMap.get("yem_materialgroupid");//物料分类ID
							DynamicObjectCollection yem_materialgroups = webofficemodel.getDynamicObjectCollection("yem_materialgroup");
							boolean materialGroupHas = false;
							for (int k = 0; k < yem_materialgroups.size(); k++) {
								DynamicObject yem_materialgroup = yem_materialgroups.get(k);
								yem_materialgroup = yem_materialgroup.getDynamicObject("fbasedataid");
								if(yem_materialgroup!=null && !materialGroupHas) {
									long yem_materialgroupid = yem_materialgroup.getLong("id");
									if(materialgroupid == yem_materialgroupid) {
										materialGroupHas = true;
									}
								}
							}
							if(!materialGroupHas) {
								continue;
							}
						}
						//如果是信用证，则根据当前用户主职位所在部门进行过滤
						if ("yem_is_creditletter".equals(yem_bill)) {
							DynamicObjectCollection yem_deporgs = webofficemodel.getDynamicObjectCollection("yem_deporg");
							boolean yem_deporgHas = false;
							for (int k = 0; k < yem_deporgs.size(); k++) {
								DynamicObject yem_deporg = yem_deporgs.get(k);
								yem_deporg = yem_deporg.getDynamicObject("fbasedataid");
								if(yem_deporg!=null && !yem_deporgHas) {
									long yem_deporgid = yem_deporg.getLong("id");
									if(userMainOrgId == yem_deporgid) {
										yem_deporgHas = true;
									}
								}
							}
							if(!yem_deporgHas) {
								continue;
							}
						}
						if (yem_bill.equals("yem_is_impcontract")) {
//							ids.add(webofficemodel.getPkValue());
							DynamicObjectCollection yem_supplier = webofficemodel.getDynamicObjectCollection("yem_supplier");
							if (yem_supplier.size() > 0 && yem_supplier != null) {
								for (int n = 0; n < yem_supplier.size(); n++) {
									DynamicObject yem_supplierobj = yem_supplier.get(n);
									yem_supplierobj = yem_supplierobj.getDynamicObject("fbasedataid");
									if (yem_supplierobj != null) {
										supplierMap.put(yem_supplierobj.getPkValue().toString(), yem_supplierobj);
									}
								}
								if (supplierMap != null && supplierMap.size() > 0) {
									if (supplierMap.containsKey(supplier)) {
										ids.add(webofficemodel.getString("id"));
									}
								}
							}else {
								ids.add(webofficemodel.getString("id"));
							}
						}else {
							ids.add(webofficemodel.getString("id"));
						}
					}
					QFilter qFilter4 = new QFilter("finterid", QCP.in, ids);
					DynamicObject[] attachments = BusinessDataServiceHelper.load("bos_attachment",
							"id,fattachmentname,ffileid,finterid", new QFilter[] { qFilter4 });
					if (attachments != null && attachments.length > 0) {
						IDataModel model = this.getModel();
						DynamicObjectCollection entryentitys = model.getEntryEntity("yem_entryentity");
						for (int i = 0; i < attachments.length; i++) {
							DynamicObject attachment = attachments[i];
							DynamicObject entryentity = entryentitys.addNew();
							entryentity.set("yem_name", attachment.get("fattachmentname"));
							entryentity.set("yem_path", attachment.get("ffileid"));
							entryentity.set("yem_modelid", attachment.get("finterid"));
						}
					}
				}
			}
		}
	}

	@Override
	public void afterBindData(EventObject e) {
		super.afterBindData(e);
	}

	@Override
	public void registerListener(EventObject e) {
		super.registerListener(e);
		Button btnok = this.getView().getControl("btnok");
		if (null != btnok) {
			this.addClickListeners(new String[] { "btnok" });
		}
		Label label = this.getView().getControl("yem_labelap1");
		label.addClickListener(this);
	}

	@Override
	public void click(EventObject evt) {
		super.click(evt);
		Control source = (Control) evt.getSource();
		String key = source.getKey();
		IDataModel model = this.getModel();
		if ("btnok".equals(key)) {
			Map<String, Object> customParams = new HashMap<>();
			int rowIndex = model.getEntryCurrentRowIndex("yem_entryentity");
			DynamicObject entryentity = model.getEntryRowEntity("yem_entryentity", rowIndex);
			if (entryentity == null) {
				this.getView().showErrorNotification("请先选择模板！");
				return;
			}
			String yem_name = entryentity.getString("yem_name");
			String yem_path = entryentity.getString("yem_path");
			String yem_modelid = entryentity.getString("yem_modelid");

			customParams.put("fileName", yem_name);
			customParams.put("fileUrl", yem_path);
			customParams.put("yem_modelid", yem_modelid);
			FormShowParameter showParameter = this.getView().getFormShowParameter();
			Map<String, Object> cusMap = showParameter.getCustomParams();
			customParams.put("yem_billId", cusMap.get("yem_billId"));
			customParams.put("yem_bill", cusMap.get("yem_bill"));
			customParams.put("isEdit", cusMap.get("isEdit"));
			customParams.put("attachmentpanel", cusMap.get("attachmentpanel"));
			if(cusMap.containsKey("isInvoice")) {
				customParams.put("isInvoice", cusMap.get("isInvoice"));
				customParams.put("yem_arrorderentry_id", cusMap.get("yem_arrorderentry_id"));
				customParams.put("yem_goodentry_map", cusMap.get("yem_goodentry_map"));
				customParams.put("invoiceNo", cusMap.get("invoiceNo"));
			}
			/**
			 * 内建浏览器打开方式参数
			 * 
			 * @param String
			 *            formId 表单Id
			 */
			WebOfficeBrowserParam webOfficeBrowserParam = new WebOfficeBrowserParam("yem_webofficenew");
			// 设置参数
			webOfficeBrowserParam.setParams(customParams);
			webOfficeBrowserParam.setHideAddressBar(false);
			// 调用浏览器帮助类，构建打开参数，返回url
			String url = WebOfficeBrowserHelper.buildUrl(webOfficeBrowserParam);
			getView().openUrl(url+"&kdweb");
		} else if ("yem_labelap1".equals(key)) {
			QFilter qFilter2 = new QFilter("name", "in", "webOffice插件");
			DynamicObject webofficeassembly = BusinessDataServiceHelper.loadSingle("yem_webofficeassembly", "id,name,number", new QFilter[] { qFilter2 });
			if(webofficeassembly!=null) {
				List<Map<String,Object>> list = AttachmentServiceHelper.getAttachments("yem_webofficeassembly",webofficeassembly.getLong("id"),"yem_attachmentpanelap");
				if(null != list && list.size()>0) {
					Map map = list.get(0);
					String url = map.get("url").toString();
					this.getView().openUrl(url);
				}else {
					this.getView().showMessage("未维护webOffice插件，请联系管理员！");
				}
			}else {
				this.getView().showMessage("未维护webOffice插件，请联系管理员！");
			}
		}
	}
}
