package nccloud.web.arap.arappub.viewhandler.bodyafter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.apache.commons.lang3.ArrayUtils;
import com.google.gson.Gson;
import nc.itf.arap.fieldmap.IBillFieldGet;
import nc.itf.bd.bankacc.cust.ICustBankaccQueryService;
import nc.itf.gl.api.IResourceService;
import nc.md.model.MetaDataException;
import nc.md.persist.framework.IMDPersistenceQueryService;
import nc.pubitf.arap.pub.ICurrentVersionService;
import nc.pubitf.uapbd.ICustomerPubService;
import nc.pubitf.uapbd.ISupplierPubService;
import nc.vo.arap.basebill.BaseItemVO;
import nc.vo.arap.pay.PayBillVO;
import nc.vo.arap.pub.BillEnumCollection.ObjType;
import nc.vo.arap.utils.StringUtil;
import nc.vo.bd.bankaccount.BankAccSubVO;
import nc.vo.bd.bankaccount.cust.CustBankaccUnionVO;
import nc.vo.bd.cust.CustomerVO;
import nc.vo.bd.cust.finance.CustFinanceVO;
import nc.vo.bd.cust.saleinfo.CustsaleVO;
import nc.vo.bd.supplier.SupplierVO;
import nc.vo.bd.supplier.finance.SupFinanceVO;
import nc.vo.gl.openapi.GLQueryWebVO;
import nc.vo.org.AccountingBookVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFDate;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nccloud.api.rest.utils.NCCRestUtils;
import nccloud.framework.service.ServiceLocator;
import nccloud.framework.web.ui.model.row.Cell;
import nccloud.framework.web.ui.pattern.billcard.CardBodyAfterEditEvent;
import nccloud.framework.web.ui.pattern.grid.ChangedRow;
import nccloud.web.arap.arappub.util.AfterEditEventUtil;
import nccloud.web.arap.arappub.util.ArapUiUtil;
import nccloud.web.arap.arappub.util.BillEventHandlerUtil;

/**
 * @author hanzhhm
 */
public class BodyCuspAfterEditHandler extends BodyBatchBillHandler<CardBodyAfterEditEvent> {
	/**
	 * 220201/224103/224105/224101科目的期末余额
	 */
	private String endlocamount220201 = "";
	private String endlocamount224103 = "";
	private String endlocamount224105 = "";
	private String endlocamount224101 = "";
	IMDPersistenceQueryService imDPersistenceService = ServiceLocator.find(IMDPersistenceQueryService.class);

	@Override
	public void handle() {
		String key = getKey();
		String pk_billtype = (String) getHeadValue(IBillFieldGet.PK_BILLTYPE);
		Integer objtype = (Integer) getBodyValue(IBillFieldGet.OBJTYPE);

		if (IBillFieldGet.CUSTOMER.equals(key) || IBillFieldGet.CUSTOMER_V.equals(key)) {
			// 增加客户版本化处理 qinwfh 2021-07-05
			// 分别处理编辑客户和客户版本字段
			UFDate thisbilldate = getHeadValue(IBillFieldGet.BILLDATE);
			Map<String, String> customerPKtoVIDMap = new HashMap<String, String>();// 接收根据customer返回的customer对customer_v的MAP值
			Map<String, String> customerVIDtoPKMap = new HashMap<String, String>();// 接收根据customer_v和单击日期返回的customer_v对customer的MAP值
			if (IBillFieldGet.CUSTOMER_V.equals(key)) {
				// 根据客户customer_v去获取对应的customer
				String[] customer_vid = new String[] { (String) getBodyValue(IBillFieldGet.CUSTOMER_V) };
				if (StringUtil.isEmptyWithTrim(customer_vid[0])) {
					setBodyValue(null, IBillFieldGet.CUSTOMER);
				} else {
					try {
						customerVIDtoPKMap = ServiceLocator.find(ICustomerPubService.class)
								.getCustomerOIDByVid(customer_vid);
					} catch (BusinessException e1) {
						ExceptionUtils.wrappException(e1);
					}
					// 设置表头和表体客户CUSTOMER_V字段值
					if (customerVIDtoPKMap != null && !customerVIDtoPKMap.isEmpty() && customerVIDtoPKMap.size() > 0) {
						setBodyValue(customerVIDtoPKMap.get(customer_vid[0]), IBillFieldGet.CUSTOMER);
					}
				}
			} else {
				// 根据客户customer和时间去获取对应最新的customer_v
				String customer_oid = (String) getBodyValue(IBillFieldGet.CUSTOMER);
				if (StringUtil.isEmptyWithTrim(customer_oid)) {
					setBodyValue(null, IBillFieldGet.CUSTOMER_V);
				} else {
					Map<String, UFDate> customerAndDateMap = new HashMap<String, UFDate>();
					customerAndDateMap.put(customer_oid, thisbilldate);
					try {
						customerPKtoVIDMap = ServiceLocator.find(ICustomerPubService.class)
								.getCustomerLastVIDByOidAndDate(customerAndDateMap);
					} catch (BusinessException e1) {
						ExceptionUtils.wrappException(e1);
					}
					// 设置表头和表体客户CUSTOMER字段值
					// 同时，考虑升级问题，历史数据可能没有Vid值，则设置为oid
					if (customerPKtoVIDMap != null && customerPKtoVIDMap.size() != 0) {
						setBodyValue(customerPKtoVIDMap.get(customer_oid), IBillFieldGet.CUSTOMER_V);
					} else {
						setBodyValue(customer_oid, IBillFieldGet.CUSTOMER_V);
					}
				}
			}
			super.doChange4RateWithCuSp();

			// setHeadValueByFirstLine(IBillFieldGet.CUSTOMER);
			if (IBillFieldGet.F2.equals(pk_billtype) || IBillFieldGet.F0.equals(pk_billtype)) {
				if (ObjType.SUPPLIER.VALUE.intValue() != objtype) {
					Map<String, Object> customerMap = new HashMap<String, Object>();
					try {
						customerMap = setBodyChanel();
					} catch (BusinessException e) {
						ExceptionUtils.wrappException(e);
					}

					// 带出财务信息页签 默认 币种、收付款协议、业务员、部门 modify by zhongfsh3
					// 2019-06-01
					CustomerVO customerVO = (customerMap != null && customerMap.get("customerVO") != null)
							? (CustomerVO) customerMap.get("customerVO")
							: null;
					if (customerVO != null) {
						CustFinanceVO[] finances = customerVO.getFinances();
						if (finances != null && finances.length > 0) {
							String pk_org = (String) getHeadValue(IBillFieldGet.PK_ORG);

							for (CustFinanceVO custFinanceVO : finances) {
								// 根据组织匹配过滤客户基本档案财务页签
								if (custFinanceVO.getPk_org().equals(pk_org)) {
									String pk_currtype = custFinanceVO.getPk_currtype1();
									String pk_payitem = custFinanceVO.getPk_payterm();
									String pk_resppsn = custFinanceVO.getPk_resppsn1();
									String pk_respdept = custFinanceVO.getPk_respdept1();
									String pk_respdept_v = null;
									if (pk_respdept != null) {
										try {
											UFDate billdate = getHeadValue(IBillFieldGet.BILLDATE);
											ICurrentVersionService service = ServiceLocator
													.find(ICurrentVersionService.class);
											pk_respdept_v = service.queryDeptPkVidByPKAndDate(pk_respdept, billdate);
										} catch (BusinessException e) {
											ExceptionUtils.wrappException(e);
										}
									}

									// 值不为空且发生改变，自动带出
									if (pk_currtype != null
											&& !Objects.equals(pk_currtype, getBodyValue(BaseItemVO.PK_CURRTYPE))) {
										bodyAfterEdit(pk_currtype, IBillFieldGet.PK_CURRTYPE);
									}
									if (pk_payitem != null
											&& !Objects.equals(pk_payitem, getBodyValue(BaseItemVO.PK_PAYTERM))) {
										bodyAfterEdit(pk_payitem, IBillFieldGet.PK_PAYTERM);
									}
									if (pk_resppsn != null
											&& !Objects.equals(pk_resppsn, getBodyValue(BaseItemVO.PK_PSNDOC))) {
										bodyAfterEdit(pk_resppsn, IBillFieldGet.PK_PSNDOC);
									}
									if (pk_respdept != null
											&& !Objects.equals(pk_respdept, getBodyValue(BaseItemVO.PK_DEPTID))) {
										bodyAfterEdit(pk_respdept, IBillFieldGet.PK_DEPTID);
									}
									if (pk_respdept_v != null && !Objects.equals(pk_respdept_v,
											getBodyValue(IBillFieldGet.PK_DEPTID_V))) {
										bodyAfterEdit(pk_respdept_v, IBillFieldGet.PK_DEPTID_V);
									}
									break;
								}
							}
						}
					}
					// 清空付款银行
					if (isClear(IBillFieldGet.PAYACCOUNT, IBillFieldGet.CUSTOMER)) {
						setBodyValue(null, IBillFieldGet.PAYACCOUNT); // 2012版本判断银行账户是否停用，停用清空
					}
					setBodyValue(null, IBillFieldGet.FREECUST);
					// setHeadValueByFirstLine(IBillFieldGet.CUSTOMER);
					String cusBankAccs = (customerMap != null && customerMap.get("cusBankaccs") != null)
							? (String) customerMap.get("cusBankaccs")
							: null;
					String defaultBankSubAccCurrtype = (customerMap != null
							&& customerMap.get("defaultBankSubAccCurrtype") != null)
									? ((BankAccSubVO) customerMap.get("defaultBankSubAccCurrtype")).getPk_currtype()
									: null;
					String editRowCurrtype = (String) getBodyValueByRowIndex(IBillFieldGet.PK_CURRTYPE, getRowindex());
					if (null != defaultBankSubAccCurrtype && null != editRowCurrtype
							&& defaultBankSubAccCurrtype.equals(editRowCurrtype)) {
						setBodyValue(cusBankAccs, IBillFieldGet.PAYACCOUNT);
					}
					// setHeadValueByFirstLine(IBillFieldGet.PAYACCOUNT);
				}
				// 订单客户与发票客户不做联动 addBy baoxina 恢复by baoxina
				setBodyValue(getBodyValue(IBillFieldGet.CUSTOMER), IBillFieldGet.ORDERCUBASDOC);
				// 编辑客户版本字段时联动订单客户版本字段 qinwfh 2021-07-06
				setBodyValue(getBodyValue(IBillFieldGet.CUSTOMER_V), IBillFieldGet.ORDERCUBASDOC_V);
			} else if ((IBillFieldGet.F1.equals(pk_billtype) || IBillFieldGet.F3.equals(pk_billtype))) {
				if (ObjType.CUSTOMER.VALUE.intValue() == objtype) {
					Map<String, Object> customerMap = new HashMap<String, Object>();
					try {
						customerMap = setBodyChanel();
					} catch (BusinessException e) {
						ExceptionUtils.wrappException(e);
					}

					// 带出财务信息页签 默认 币种、收付款协议、业务员、部门 modify by zhongfsh3
					// 2019-06-01
					CustomerVO customerVO = (customerMap != null && customerMap.get("customerVO") != null)
							? (CustomerVO) customerMap.get("customerVO")
							: null;
					if (customerVO != null) {
						CustFinanceVO[] finances = customerVO.getFinances();
						if (finances != null && finances.length > 0) {
							String pk_org = (String) getHeadValue(IBillFieldGet.PK_ORG);

							for (CustFinanceVO custFinanceVO : finances) {
								// 根据组织匹配过滤客户基本档案财务页签
								if (custFinanceVO.getPk_org().equals(pk_org)) {
									String pk_currtype = custFinanceVO.getPk_currtype1();
									String pk_payitem = custFinanceVO.getPk_payterm();
									String pk_resppsn = custFinanceVO.getPk_resppsn1();
									String Pk_respdept = custFinanceVO.getPk_respdept1();
									String Pk_respdept_v = null;
									if (Pk_respdept != null) {
										try {
											UFDate billdate = getHeadValue(IBillFieldGet.BILLDATE);
											ICurrentVersionService service = ServiceLocator
													.find(ICurrentVersionService.class);
											Pk_respdept_v = service.queryDeptPkVidByPKAndDate(Pk_respdept, billdate);
										} catch (BusinessException e) {
											ExceptionUtils.wrappException(e);
										}
									}

									// 值不为空且发生改变，自动带出
									if (pk_currtype != null
											&& !Objects.equals(pk_currtype, getBodyValue(BaseItemVO.PK_CURRTYPE))) {
										bodyAfterEdit(pk_currtype, IBillFieldGet.PK_CURRTYPE);
									}
									if (pk_payitem != null
											&& !Objects.equals(pk_payitem, getBodyValue(BaseItemVO.PK_PAYTERM))) {
										bodyAfterEdit(pk_payitem, IBillFieldGet.PK_PAYTERM);
									}
									if (pk_resppsn != null
											&& !Objects.equals(pk_resppsn, getBodyValue(BaseItemVO.PK_PSNDOC))) {
										bodyAfterEdit(pk_resppsn, IBillFieldGet.PK_PSNDOC);
									}
									if (Pk_respdept != null
											&& !Objects.equals(Pk_respdept, getBodyValue(BaseItemVO.PK_DEPTID))) {
										bodyAfterEdit(Pk_respdept, IBillFieldGet.PK_DEPTID);
									}
									if (Pk_respdept_v != null && !Objects.equals(Pk_respdept_v,
											getBodyValue(IBillFieldGet.PK_DEPTID_V))) {
										bodyAfterEdit(Pk_respdept_v, IBillFieldGet.PK_DEPTID_V);
									}
									break;
								}
							}
						}
					}
					// 清空收款银行
					if (isClear(IBillFieldGet.RECACCOUNT, IBillFieldGet.CUSTOMER)) {
						setBodyValue(null, IBillFieldGet.RECACCOUNT);// 2012版本
					}
					setBodyValue(null, IBillFieldGet.FREECUST);
					// setHeadValueByFirstLine(IBillFieldGet.CUSTOMER);
					String cusBankAccs = (customerMap != null && customerMap.get("cusBankaccs") != null)
							? (String) customerMap.get("cusBankaccs")
							: null;
					String defaultBankSubAccCurrtype = (customerMap != null
							&& customerMap.get("defaultBankSubAccCurrtype") != null)
									? ((BankAccSubVO) customerMap.get("defaultBankSubAccCurrtype")).getPk_currtype()
									: null;
					String editRowCurrtype = (String) getBodyValueByRowIndex(IBillFieldGet.PK_CURRTYPE, getRowindex());
					if (null != defaultBankSubAccCurrtype && null != editRowCurrtype
							&& defaultBankSubAccCurrtype.equals(editRowCurrtype)) {
						setBodyValue(cusBankAccs, IBillFieldGet.RECACCOUNT);
					}
				}
			}

			// 订单客户与发票客户不做联动 addBy baoxina 恢复by baoxina
			// setBodyValue(getBodyValue(IBillFieldGet.CUSTOMER),
			// IBillFieldGet.ORDERCUBASDOC);
			// 编辑客户版本字段时联动订单客户版本字段 qinwfh 2021-07-06
			// setBodyValue(getBodyValue(IBillFieldGet.CUSTOMER_V),
			// IBillFieldGet.ORDERCUBASDOC_V);
		} else if (IBillFieldGet.SUPPLIER.equals(key) || IBillFieldGet.SUPPLIER_V.equals(key)) {
			// 增加供应商版本化处理
			// 增加版本化处理 qinwfh 2021-07-05
			// 分别处理编辑供应商和供应商版本字段
			Map<String, String> supplierPKtoVIDMap = new HashMap<String, String>();// 接收根据supplier返回的supplier对supplier_v的MAP值
			Map<String, String> supplierVIDtoPKMap = new HashMap<String, String>();// 接收根据supplier_v和单击日期返回的supplier_v对customer的MAP值
			UFDate thisbilldate = getHeadValue(IBillFieldGet.BILLDATE);
			if (IBillFieldGet.SUPPLIER_V.equals(key)) {
				// 根据供应商supplier_v去获取对应的supplier
				String[] supplier_vid = new String[] { (String) getBodyValue(IBillFieldGet.SUPPLIER_V) };
				if (StringUtil.isEmptyWithTrim(supplier_vid[0])) {
					setBodyValue(null, IBillFieldGet.SUPPLIER);
					if(aggvo.getParent() instanceof PayBillVO) {
						setBodyValue(null, "def30");
						setBodyValue(null, "def31");
						setBodyValue(null, "def32");
						setBodyValue(null, "def33");
					}
					
				} else {
					try {
						supplierVIDtoPKMap = ServiceLocator.find(ISupplierPubService.class)
								.getSupplierOIDByVid(supplier_vid);
					} catch (BusinessException e1) {
						ExceptionUtils.wrappException(e1);
					}
					// 设置表头和表体供应商SUPPLIER_V字段值
					if (supplierVIDtoPKMap != null && !supplierVIDtoPKMap.isEmpty() && supplierVIDtoPKMap.size() > 0) {
						setBodyValue(supplierVIDtoPKMap.get(supplier_vid[0]), IBillFieldGet.SUPPLIER);
					}
				}
			} else {
				// 根据供应商supplier和时间去获取对应最新的supplier_v
				String supplier_oid = (String) getBodyValue(IBillFieldGet.SUPPLIER);
				if (StringUtil.isEmptyWithTrim(supplier_oid)) {
					setBodyValue(null, IBillFieldGet.SUPPLIER_V);
					if(aggvo.getParent() instanceof PayBillVO) {
						setBodyValue(null, "def30");
						setBodyValue(null, "def31");
						setBodyValue(null, "def32");
						setBodyValue(null, "def33");
					}
				} else {
					Map<String, UFDate> supplierAndDateMap = new HashMap<String, UFDate>();
					supplierAndDateMap.put(supplier_oid, thisbilldate);
					try {
						supplierPKtoVIDMap = ServiceLocator.find(ISupplierPubService.class)
								.getSupplierLastVIDByOidAndDate(supplierAndDateMap);
					} catch (BusinessException e1) {
						ExceptionUtils.wrappException(e1);
					}
					// 设置表头和表体供应商SUPPLIER_V字段值
					// 考虑升级问题，当Vid为空时，将oid值赋值给vid
					if (supplierPKtoVIDMap != null && supplierPKtoVIDMap.size() != 0) {
						setBodyValue(supplierPKtoVIDMap.get(supplier_oid), IBillFieldGet.SUPPLIER_V);
					} else {
						setBodyValue(supplier_oid, IBillFieldGet.SUPPLIER_V);
					}
				}
			}
			super.doChange4RateWithCuSp();

			if (IBillFieldGet.F3.equals(pk_billtype) || IBillFieldGet.F1.equals(pk_billtype)) {
				if (ObjType.CUSTOMER.VALUE.intValue() != objtype) {
					String supplier = (String) getBodyValue(IBillFieldGet.SUPPLIER);

					// 带出财务信息页签 默认 币种、收付款协议、业务员、部门 add by zhongfsh3 2019-06-01
					SupplierVO supplierVO = BillEventHandlerUtil.getSupplierVO(supplier);
					if (supplierVO != null && supplierVO.getSupfinance() != null) {
						SupFinanceVO[] financeVOs = supplierVO.getSupfinance();
						String pk_org = (String) getBodyValue(IBillFieldGet.PK_ORG);
						if (financeVOs != null && financeVOs.length > 0) {
							for (SupFinanceVO financeVO : financeVOs) {
								// 根据组织匹配过滤客户基本档案财务页签
								if (financeVO.getPk_org().equals(pk_org)) {
									String pk_currtype = financeVO.getPk_currtype();
									String pk_payitem = financeVO.getPk_payterm();
									String pk_resppsn = financeVO.getPk_resppsn();
									String Pk_respdept = financeVO.getPk_respdept();
									String Pk_respdept_v = null;
									if (Pk_respdept != null) {
										try {
											UFDate billdate = getHeadValue(IBillFieldGet.BILLDATE);
											ICurrentVersionService service = ServiceLocator
													.find(ICurrentVersionService.class);
											Pk_respdept_v = service.queryDeptPkVidByPKAndDate(Pk_respdept, billdate);
										} catch (BusinessException e) {
											ExceptionUtils.wrappException(e);
										}
									}

									// 值不为空且发生改变，自动带出
									if (pk_currtype != null
											&& !Objects.equals(pk_currtype, getBodyValue(BaseItemVO.PK_CURRTYPE))) {
										bodyAfterEdit(pk_currtype, IBillFieldGet.PK_CURRTYPE);
									}
									if (pk_payitem != null
											&& !Objects.equals(pk_payitem, getBodyValue(BaseItemVO.PK_PAYTERM))) {
										bodyAfterEdit(pk_payitem, IBillFieldGet.PK_PAYTERM);
									}
									if (pk_resppsn != null
											&& !Objects.equals(pk_resppsn, getBodyValue(BaseItemVO.PK_PSNDOC))) {
										bodyAfterEdit(pk_resppsn, IBillFieldGet.PK_PSNDOC);
									}
									if (Pk_respdept != null
											&& !Objects.equals(Pk_respdept, getBodyValue(BaseItemVO.PK_DEPTID))) {
										bodyAfterEdit(Pk_respdept, IBillFieldGet.PK_DEPTID);
									}
									if (Pk_respdept_v != null && !Objects.equals(Pk_respdept_v,
											getBodyValue(IBillFieldGet.PK_DEPTID_V))) {
										bodyAfterEdit(Pk_respdept_v, IBillFieldGet.PK_DEPTID_V);
									}
									break;
								}
							}

						}
					}
					// 泰开项目客开，带出供应商辅助余额111
					// 核算账薄编码
					if (supplierVO != null && aggvo.getParent() instanceof PayBillVO) {
						PayBillVO billvo = (PayBillVO) aggvo.getParent();
						String pk_relorg = billvo.getPk_fiorg();
						String accbookCode = getAccbookCode(pk_relorg);
						// 单据日期
						UFDate billdate = billvo.getBilldate();
						// 当前时间
						Long serverDate = System.currentTimeMillis();
						// 如果有单据号则为修改,修改时单据日期选择现在
						// 单据号
						String billno = billvo.getBillno();
						if (billno != null) {
							billdate = new UFDate(serverDate);
						}
						getAccountingSubject(accbookCode, billdate, supplierVO.getCode(), supplierVO.getName());
						setBodyValue(endlocamount220201, "def30");
						setBodyValue(endlocamount224103, "def31");
						setBodyValue(endlocamount224105, "def32");
						setBodyValue(endlocamount224101, "def33");
					}
					// 清空收款银行
					if (isClear(IBillFieldGet.RECACCOUNT, IBillFieldGet.SUPPLIER)) {
						setBodyValue(null, IBillFieldGet.RECACCOUNT);// 2012版本
					}
					setBodyValue(null, IBillFieldGet.FREECUST);
					// setHeadValueByFirstLine(IBillFieldGet.SUPPLIER);

					String supBankAccs = BillEventHandlerUtil.getDefaultSupBankAccs(supplier);
					String defaultBankSubAccCurrtype = BillEventHandlerUtil
							.getDefaultBankSubAccCurrtypeByAccpk(supBankAccs);
					String editRowCurrtype = (String) getBodyValueByRowIndex(IBillFieldGet.PK_CURRTYPE, getRowindex());
					String headCurrtype = (String) getHeadValue(IBillFieldGet.PK_CURRTYPE);
					String headCustomer = (String) getHeadValue(IBillFieldGet.CUSTOMER);
					if (null != defaultBankSubAccCurrtype && null != editRowCurrtype
							&& defaultBankSubAccCurrtype.equals(editRowCurrtype)) {
						setBodyValue(supBankAccs, IBillFieldGet.RECACCOUNT);
					}
					if (headCurrtype != null && headCustomer != null && supplier != null && editRowCurrtype != null) {
						if (editRowCurrtype.equals(headCurrtype) && supplier.equals(headCustomer)) {
							if (defaultBankSubAccCurrtype != null && headCurrtype.equals(defaultBankSubAccCurrtype)) {
								// setHeadValueByFirstLine(IBillFieldGet.RECACCOUNT);
							}
						}
					}
					// setHeadValueByFirstLine(IBillFieldGet.RECACCOUNT);
				}
				// 订单客户与发票客户不做联动 addBy baoxina 恢复by baoxina
				setBodyValue(getBodyValue(IBillFieldGet.SUPPLIER), IBillFieldGet.ORDERCUBASDOC);
				// 编辑客户版本字段时联动订单客户版本字段 qinwfh 2021-07-06
				setBodyValue(getBodyValue(IBillFieldGet.SUPPLIER_V), IBillFieldGet.ORDERCUBASDOC_V);

			} else if ((IBillFieldGet.F2.equals(pk_billtype) || IBillFieldGet.F0.equals(pk_billtype))) {
				if (ObjType.SUPPLIER.VALUE.intValue() == objtype) {
					String supplier = (String) getBodyValue(IBillFieldGet.SUPPLIER);

					// 带出财务信息页签 默认 币种、收付款协议、业务员、部门 add by zhongfsh3 2019-06-01
					SupplierVO supplierVO = BillEventHandlerUtil.getSupplierVO(supplier);
					if (supplierVO != null && supplierVO.getSupfinance() != null) {
						SupFinanceVO[] financeVOs = supplierVO.getSupfinance();
						String pk_org = (String) getBodyValue(IBillFieldGet.PK_ORG);
						if (financeVOs != null && financeVOs.length > 0) {
							for (SupFinanceVO financeVO : financeVOs) {
								// 根据组织匹配过滤客户基本档案财务页签
								if (financeVO.getPk_org().equals(pk_org)) {
									String pk_currtype = financeVO.getPk_currtype();
									String pk_payitem = financeVO.getPk_payterm();
									String pk_resppsn = financeVO.getPk_resppsn();
									String Pk_respdept = financeVO.getPk_respdept();
									String Pk_respdept_v = null;
									if (Pk_respdept != null) {
										try {
											UFDate billdate = getHeadValue(IBillFieldGet.BILLDATE);
											ICurrentVersionService service = ServiceLocator
													.find(ICurrentVersionService.class);
											Pk_respdept_v = service.queryDeptPkVidByPKAndDate(Pk_respdept, billdate);
										} catch (BusinessException e) {
											ExceptionUtils.wrappException(e);
										}
									}

									// 值不为空且发生改变，自动带出
									if (pk_currtype != null
											&& !Objects.equals(pk_currtype, getBodyValue(BaseItemVO.PK_CURRTYPE))) {
										bodyAfterEdit(pk_currtype, IBillFieldGet.PK_CURRTYPE);
									}
									if (pk_payitem != null
											&& !Objects.equals(pk_payitem, getBodyValue(BaseItemVO.PK_PAYTERM))) {
										bodyAfterEdit(pk_payitem, IBillFieldGet.PK_PAYTERM);
									}
									if (pk_resppsn != null
											&& !Objects.equals(pk_resppsn, getBodyValue(BaseItemVO.PK_PSNDOC))) {
										bodyAfterEdit(pk_resppsn, IBillFieldGet.PK_PSNDOC);
									}
									if (Pk_respdept != null
											&& !Objects.equals(Pk_respdept, getBodyValue(BaseItemVO.PK_DEPTID))) {
										bodyAfterEdit(Pk_respdept, IBillFieldGet.PK_DEPTID);
									}
									if (Pk_respdept_v != null && !Objects.equals(Pk_respdept_v,
											getBodyValue(IBillFieldGet.PK_DEPTID_V))) {
										bodyAfterEdit(Pk_respdept_v, IBillFieldGet.PK_DEPTID_V);
									}
									break;
								}
							}

						}
					}

					// 清空收款银行
					if (isClear(IBillFieldGet.PAYACCOUNT, IBillFieldGet.SUPPLIER)) {
						setBodyValue(null, IBillFieldGet.PAYACCOUNT);// 2012
					}
					setBodyValue(null, IBillFieldGet.FREECUST);
					// setHeadValueByFirstLine(IBillFieldGet.SUPPLIER);

					String supBankAccs = BillEventHandlerUtil.getDefaultSupBankAccs(supplier);
					String defaultBankSubAccCurrtype = BillEventHandlerUtil
							.getDefaultBankSubAccCurrtypeByAccpk(supBankAccs);
					String editRowCurrtype = (String) getBodyValueByRowIndex(IBillFieldGet.PK_CURRTYPE, getRowindex());
					String headCurrtype = (String) getHeadValue(IBillFieldGet.PK_CURRTYPE);
					String headCustomer = (String) getHeadValue(IBillFieldGet.CUSTOMER);
					if (null != defaultBankSubAccCurrtype && null != editRowCurrtype
							&& defaultBankSubAccCurrtype.equals(editRowCurrtype)) {
						setBodyValue(supBankAccs, IBillFieldGet.PAYACCOUNT);
					}
					if (headCurrtype != null && headCustomer != null && supplier != null && editRowCurrtype != null) {
						if (editRowCurrtype.equals(headCurrtype) && supplier.equals(headCustomer)) {
							if (defaultBankSubAccCurrtype != null && headCurrtype.equals(defaultBankSubAccCurrtype)) {
								// setHeadValueByFirstLine(IBillFieldGet.RECACCOUNT);
							}
						}
					}
				}
			}
			// 订单客户与发票客户不做联动 addBy baoxina 恢复by baoxina
			// setBodyValue(getBodyValue(IBillFieldGet.SUPPLIER),
			// IBillFieldGet.ORDERCUBASDOC);
			// 编辑客户版本字段时联动订单客户版本字段 qinwfh 2021-07-06
			// setBodyValue(getBodyValue(IBillFieldGet.SUPPLIER_V),
			// IBillFieldGet.ORDERCUBASDOC_V);
		}
	}

	/**
	 * nccloud/api/gl/accountrep/assbalance 查询辅助余额接口.查220201/224103/224105的科目的期末余额
	 * 
	 * @param accbookCode    辅助核算编码
	 * @param billdate       单据日期
	 * @param checkvaluecode 供应商编码
	 * @param checkvaluename 供应商名称
	 */
	public void getAccountingSubject(String acccode, UFDate date, String code, String name) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		String strdate = formatter.format(date.toDate());

		endlocamount220201 = getendlocamountBy(queryAssBalance(getRequest(acccode, strdate, code, name)));
		endlocamount224103 = getendlocamountBy(queryAssBalance(getRequest1(acccode, strdate, code, name)));
		endlocamount224105 = getendlocamountBy(queryAssBalance(getRequest2(acccode, strdate, code, name)));
		endlocamount224101 = getendlocamountBy(queryAssBalance(getRequest3(acccode, strdate, code, name)));
	}

	/**
	 * 解析json获取期末余额
	 * 
	 * @param json
	 * @return 期末余额 endlocamount
	 */
	public String getendlocamountBy(List<Map<String, Object>> data) {
		if (data == null) {
			return null;
		}
		String str2 = (String) data.get(0).get("endlocamount");
		String str3 = (String) data.get(0).get("endorint");
		if (str2 == null || "".equals(str2)) {
			str2 = "0.0";
		} else {
			if ("借".equals(str3)) {
				str2 = "-" + str2;
			}
		}
		return str2;
	}

	public List<Map<String, Object>> queryAssBalance(String json) {
		NCCRestUtils.initInvocationInfo();
		GLQueryWebVO qryWebVO = (GLQueryWebVO) new Gson().fromJson(json, GLQueryWebVO.class);
		List<Map<String, Object>> data = null;
		try {
			data = ServiceLocator.find(IResourceService.class).queryAssBalanceByVO(qryWebVO);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (data == null) {
			return null;
		}
		return data;
	}

	private static String getRequest(String accbookCode, String strdate, String code, String name) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<String> accbookcodeList = new ArrayList<String>();
		accbookcodeList.add(accbookCode);
		map.put("accbookCode", accbookcodeList);
		map.put("queryByPeriod", "false");
		map.put("inclUntallyed", "true");
		map.put("inclTransfer", "true");
		map.put("inclError", "true");
		map.put("inclReclassify", "true");
		map.put("date", strdate);
		map.put("endDate", strdate);
		map.put("currtypeCode", "本币");

		List<Map<String, Object>> queryObjList = new ArrayList<Map<String, Object>>();
		Map<String, Object> quyMap = new HashMap<String, Object>();
		Map<String, Object> typeMap = new HashMap<String, Object>();

		typeMap.put("checktypecode", "会计科目");
		typeMap.put("checktypename", "会计科目");
		quyMap.put("checktype", typeMap);
		List<Map<String, String>> valueList = new ArrayList<Map<String, String>>();
		Map<String, String> valueMap = new HashMap<String, String>();

		valueMap.put("checkvaluecode", "220201");
		valueMap.put("checkvaluename", "应付款");
		valueList.add(valueMap);
		quyMap.put("checkvalue", valueList);
		queryObjList.add(quyMap);
		//
		Map<String, Object> quyMap1 = new HashMap<String, Object>();
		Map<String, Object> typeMap1 = new HashMap<String, Object>();

		typeMap1.put("checktypecode", "0019");
		typeMap1.put("checktypename", "供应商档案");
		quyMap1.put("checktype", typeMap1);
		List<Map<String, String>> valueList1 = new ArrayList<Map<String, String>>();
		Map<String, String> valueMap1 = new HashMap<String, String>();

		valueMap1.put("checkvaluecode", code);
		valueMap1.put("checkvaluename", name);
		valueList1.add(valueMap1);
		quyMap1.put("checkvalue", valueList1);
		queryObjList.add(quyMap1);
		map.put("queryObj", queryObjList);
		return new Gson().toJson(map);
	}

	private static String getRequest1(String accbookCode, String strdate, String code, String name) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<String> accbookcodeList = new ArrayList<String>();
		accbookcodeList.add(accbookCode);
		map.put("accbookCode", accbookcodeList);
		map.put("queryByPeriod", "false");
		map.put("inclUntallyed", "true");
		map.put("inclTransfer", "true");
		map.put("inclError", "true");
		map.put("inclReclassify", "true");
		map.put("date", strdate);
		map.put("endDate", strdate);
		map.put("currtypeCode", "本币");

		List<Map<String, Object>> queryObjList = new ArrayList<Map<String, Object>>();
		Map<String, Object> quyMap = new HashMap<String, Object>();
		Map<String, Object> typeMap = new HashMap<String, Object>();

		typeMap.put("checktypecode", "会计科目");
		typeMap.put("checktypename", "会计科目");
		quyMap.put("checktype", typeMap);
		List<Map<String, String>> valueList = new ArrayList<Map<String, String>>();
		Map<String, String> valueMap = new HashMap<String, String>();

		valueMap.put("checkvaluecode", "224103");
		valueMap.put("checkvaluename", "单位");
		valueList.add(valueMap);
		quyMap.put("checkvalue", valueList);
		queryObjList.add(quyMap);
		//
		Map<String, Object> quyMap1 = new HashMap<String, Object>();
		Map<String, Object> typeMap1 = new HashMap<String, Object>();

		typeMap1.put("checktypecode", "0019");
		typeMap1.put("checktypename", "供应商档案");
		quyMap1.put("checktype", typeMap1);
		List<Map<String, String>> valueList1 = new ArrayList<Map<String, String>>();
		Map<String, String> valueMap1 = new HashMap<String, String>();

		valueMap1.put("checkvaluecode", code);
		valueMap1.put("checkvaluename", name);
		valueList1.add(valueMap1);
		quyMap1.put("checkvalue", valueList1);
		queryObjList.add(quyMap1);
		map.put("queryObj", queryObjList);
		return new Gson().toJson(map);
	}

	private static String getRequest2(String accbookCode, String strdate, String code, String name) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<String> accbookcodeList = new ArrayList<String>();
		accbookcodeList.add(accbookCode);
		map.put("accbookCode", accbookcodeList);
		map.put("queryByPeriod", "false");
		map.put("inclUntallyed", "true");
		map.put("inclTransfer", "true");
		map.put("inclError", "true");
		map.put("inclReclassify", "true");
		map.put("date", strdate);
		map.put("endDate", strdate);
		map.put("currtypeCode", "本币");

		List<Map<String, Object>> queryObjList = new ArrayList<Map<String, Object>>();
		Map<String, Object> quyMap = new HashMap<String, Object>();
		Map<String, Object> typeMap = new HashMap<String, Object>();

		typeMap.put("checktypecode", "会计科目");
		typeMap.put("checktypename", "会计科目");
		quyMap.put("checktype", typeMap);
		List<Map<String, String>> valueList = new ArrayList<Map<String, String>>();
		Map<String, String> valueMap = new HashMap<String, String>();

		valueMap.put("checkvaluecode", "224105");
		valueMap.put("checkvaluename", "运费");
		valueList.add(valueMap);
		quyMap.put("checkvalue", valueList);
		queryObjList.add(quyMap);
		//
		Map<String, Object> quyMap1 = new HashMap<String, Object>();
		Map<String, Object> typeMap1 = new HashMap<String, Object>();

		typeMap1.put("checktypecode", "0019");
		typeMap1.put("checktypename", "供应商档案");
		quyMap1.put("checktype", typeMap1);
		List<Map<String, String>> valueList1 = new ArrayList<Map<String, String>>();
		Map<String, String> valueMap1 = new HashMap<String, String>();

		valueMap1.put("checkvaluecode", code);
		valueMap1.put("checkvaluename", name);
		valueList1.add(valueMap1);
		quyMap1.put("checkvalue", valueList1);
		queryObjList.add(quyMap1);
		map.put("queryObj", queryObjList);
		return new Gson().toJson(map);
	}

	private static String getRequest3(String accbookCode, String strdate, String code, String name) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<String> accbookcodeList = new ArrayList<String>();
		accbookcodeList.add(accbookCode);
		map.put("accbookCode", accbookcodeList);
		map.put("queryByPeriod", "false");
		map.put("inclUntallyed", "true");
		map.put("inclTransfer", "true");
		map.put("inclError", "true");
		map.put("inclReclassify", "true");
		map.put("date", strdate);
		map.put("endDate", strdate);
		map.put("currtypeCode", "本币");

		List<Map<String, Object>> queryObjList = new ArrayList<Map<String, Object>>();
		Map<String, Object> quyMap = new HashMap<String, Object>();
		Map<String, Object> typeMap = new HashMap<String, Object>();

		typeMap.put("checktypecode", "会计科目");
		typeMap.put("checktypename", "会计科目");
		quyMap.put("checktype", typeMap);
		List<Map<String, String>> valueList = new ArrayList<Map<String, String>>();
		Map<String, String> valueMap = new HashMap<String, String>();

		valueMap.put("checkvaluecode", "224101");
		valueMap.put("checkvaluename", "保证金");
		valueList.add(valueMap);
		quyMap.put("checkvalue", valueList);
		queryObjList.add(quyMap);
		//
		Map<String, Object> quyMap1 = new HashMap<String, Object>();
		Map<String, Object> typeMap1 = new HashMap<String, Object>();

		typeMap1.put("checktypecode", "0019");
		typeMap1.put("checktypename", "供应商档案");
		quyMap1.put("checktype", typeMap1);
		List<Map<String, String>> valueList1 = new ArrayList<Map<String, String>>();
		Map<String, String> valueMap1 = new HashMap<String, String>();

		valueMap1.put("checkvaluecode", code);
		valueMap1.put("checkvaluename", name);
		valueList1.add(valueMap1);
		quyMap1.put("checkvalue", valueList1);
		queryObjList.add(quyMap1);
		map.put("queryObj", queryObjList);
		return new Gson().toJson(map);
	}

	/**
	 * 
	 * @return 获取核算账薄code
	 */
	public String getAccbookCode(String pk_relorg) {
		List<AccountingBookVO> bills = null;
		String sql = "pk_relorg = '" + pk_relorg + "' and dr = 0 ";
		String accbookCode = "";
		try {
			bills = (List<AccountingBookVO>) imDPersistenceService.queryBillOfVOByCond(AccountingBookVO.class, sql,
					false);
			if (bills.size() != 0) {
				accbookCode = bills.get(0).getCode();
			}
		} catch (MetaDataException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return accbookCode;

	}

	private Map<String, Object> setBodyChanel() throws BusinessException {
		String pk_customer = (String) getBodyValue(IBillFieldGet.CUSTOMER);
		String pk_org = (String) getHeadValue(IBillFieldGet.PK_ORG);
		String chanel = null;
		Map<String, Object> customerMap = new HashMap<String, Object>();
		Map<String, Map<String, Object>> cuspAfterEditHandler = new HashMap<String, Map<String, Object>>();
		if (null != pk_customer) {
			cuspAfterEditHandler = BillEventHandlerUtil.getCuspAfterEditHandler();
			if (null != cuspAfterEditHandler) {
				customerMap = cuspAfterEditHandler.get(pk_customer + pk_org);
				if (customerMap == null) {
					BillEventHandlerUtil.setCuspAfterEditHandler(pk_customer, pk_org);
					cuspAfterEditHandler = BillEventHandlerUtil.getCuspAfterEditHandler();
					customerMap = cuspAfterEditHandler.get(pk_customer + pk_org);
				}
			}
			if (customerMap != null && customerMap.get("custsaleVOs") != null) {
				CustsaleVO[] vos = (CustsaleVO[]) customerMap.get("custsaleVOs");
				if (null != vos && vos.length > 0 && null != vos[0]) {
					chanel = vos[0].getChannel();
				}
			}
		}
		for (int i = 0; i < aggvo.getChildrenVO().length; i++) {
			setBodyValue(chanel, IBillFieldGet.SO_TRANSTYPE);
		}
		return customerMap;
	}

	/**
	 * 设置表体值并触发编辑事件
	 *
	 * @param newValue
	 * @param fieldName
	 * @author zhongfsh3
	 * @date 2019年6月12日
	 */
	private void bodyAfterEdit(Object newValue, String fieldName) {
		// 设置表体值
		setBodyValue(newValue, fieldName);
		// 触发编辑事件
		Cell oldCell = getEvent().getCard().getBody().getModel().getRows()[getRowindex()].getCell(fieldName);
		Cell newCell = ArapUiUtil.copyCell(oldCell);
		newCell.setValue(newValue);
		ChangedRow changeRow = new ChangedRow(newCell, oldCell,
				getEvent().getCard().getBody().getModel().getRows()[getRowindex()].getRowid());
		CardBodyAfterEditEvent event = new CardBodyAfterEditEvent(fieldName, getEvent().getCard(), getRowindex(),
				new ChangedRow[] { changeRow });
		AfterEditEventUtil.bodyAfterEdit(event, aggvo, getEventInfo());
	}

	private List<String> keys = Arrays.asList(new String[] { IBillFieldGet.CUSTOMER, IBillFieldGet.SUPPLIER,
			IBillFieldGet.SUPPLIER_V, IBillFieldGet.CUSTOMER_V });

	@Override
	protected Collection<String> getFilterKey() {
		return keys;
	}

	/**
	 * 编辑供应商后，银行账户是否停用bd_bankaccbas(银行账户)bd_bankaccsub（客商银行账户子户）
	 *
	 * @param key银行账户相关字段 ，editkey 编辑的字段
	 * @return
	 * @throws BusinessException
	 */
	private boolean isClear(String key, String editKey) {
		boolean flag = true;
		String keyValue = (String) getBodyValue(key);
		String editValue = (String) getBodyValue(editKey);// 编辑的字段的值
		try {
			CustBankaccUnionVO[] custBank = ServiceLocator.find(ICustBankaccQueryService.class)
					.queryCustBankaccUnionVOsByCust(editValue, IBillFieldGet.SUPPLIER.equals(editKey) ? 3 : 1, true);
			if (ArrayUtils.isEmpty(custBank)) {
				return true;
			}

			for (CustBankaccUnionVO vo : custBank) {
				if (vo.getBankaccbasVO() == null) {
					continue;
				}
				Integer enable = (Integer) vo.getAttributeValue("a.enablestate");
				if (enable == null || (enable != null && enable != 2)) {
					continue;
				}
				String pk_bank = (String) vo.getAttributeValue("pk_bankaccsub");
				if (StringUtil.isEmptyWithTrim(pk_bank)) {
					continue;
				}
				if (pk_bank.equals(keyValue)) {
					flag = false;
					break;
				}
			}
		} catch (BusinessException e) {
			ExceptionUtils.wrappException(e);

		}
		if (editValue == null) {
			return true;
		}
		return flag;

	}

}
