package nc.pubimpl.payablebill.yx;

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

import org.apache.commons.lang3.StringUtils;

import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
import nc.bs.framework.common.NCLocator;
import nc.impl.am.db.processor.CountProcessor;
import nc.jdbc.framework.processor.ColumnListProcessor;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.pubitf.payablebill.yx.AutoVO;
import nc.pubitf.payablebill.yx.IImagePubService;
import nc.pubitf.payablebill.yx.ImageCommonUtil;
import nc.pubitf.payablebill.yx.ImageContentVO;
import nc.vo.arap.pay.bzfk.ImageCoverVO;
import nc.vo.arap.payable.AggPayableBillVO;
import nc.vo.arap.payable.PayableBillItemVO;
import nc.vo.arap.payable.PayableBillVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.VOStatus;
import nc.vo.pub.lang.UFDate;
import nc.vo.pub.lang.UFDateTime;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
/**
 * 调用影像接口
 * @author ll
 * @date 2021-05-26
 */
public class PayablebillAfterRule  {

	public void getService(AggPayableBillVO[] volist) throws BusinessException {
		IImagePubService service=NCLocator.getInstance().lookup(IImagePubService.class);
		for(AggPayableBillVO vo:volist) {
			PayableBillVO hvo = vo.getHeadVO();
			//add by longht 处理明源应付单影像历史数据问题 start 
			if ("F1-Cxx-W02".equals(hvo.getPk_tradetype())) {
				UFDate creationtime = hvo.getCreationtime().getDate();//单据创建日期
				UFDate Time = new UFDate("2021-10-19 00:00:00");//单据控制时间
				if(!Time.before(creationtime)) {
					return;
				}
			}
			//add by longht 处理明源应付单影像历史数据问题 end 
			
			//wby 20211104 补充物业应付单（明源）推影像封面  F1-Cxx-W03:报账应付单（物业） F1-Cxx-W04:对外账扣款单（物业） F1-Cxx-W02:物业应付单（明源）
			if(("F1-Cxx-W02".equals(hvo.getPk_tradetype()) || "F1-Cxx-W03".equals(hvo.getPk_tradetype()) || "F1-Cxx-W04".equals(hvo.getPk_tradetype()))) {
				//物业应付单（明源）不判断def70
				if("Y".equals(hvo.getDef70()) || "F1-Cxx-W02".equals(hvo.getPk_tradetype())) {
					String billstatus = hvo.getApprovestatus().toString();
					String effectstatus = hvo.getEffectstatus().toString();
					if("-1".equals(billstatus) && "0".equals(effectstatus) && hvo.getStatus() != VOStatus.DELETED) {
						billstatus = "1";
					} else if("3".equals(billstatus)) {			
						billstatus = "0";
						this.checkInvoice(vo);
					} else if("10".equals(effectstatus)) {
						billstatus = "2";
					} else if(hvo.getStatus() == VOStatus.DELETED) {
						billstatus = "3";
					} else {
						return;
					}
			
					String billid = hvo.getPk_payablebill();
					service.updateImageStatus(billid, billstatus);
					if (billstatus == "2") {
						this.ImageCover(hvo);
					}
				} else {
					// 自动创建影像接口
					String billstatus = hvo.getApprovestatus().toString();
					String billid = hvo.getPk_payablebill();
					if (!isSendImage(billid)) {
						if ("1".equals(billstatus)) {
							this.AutoImageCover(hvo);
						}
					}
				}
			}
		}
	}

	public static boolean isSendImage(String billid) {
		String sql = new StringBuilder("SELECT COUNT(*)").append("  FROM IMG_TM_LOG")
				.append(" WHERE BILLID = '" + billid + "'").append(" AND TM_STATUS = 'S'")
				.append(" AND APICODE = 'AUTO-UPDATE-IMAGE'").toString();
		try {
			Integer count = (Integer) getDAO().executeQuery(sql, new CountProcessor());
			if (count != null && count > 0) {
				return true;
			}
		} catch (DAOException e) {
			ExceptionUtils.wrappBusinessException("查询单据是否上传影像系统待办失败,请联系用友顾问!");
		}
		return false;
	}

	public void AutoImageCover(PayableBillVO vo) {
		try {
			ImageContentVO autoImageVO = new ImageContentVO();
			autoImageVO.setBillCode(vo.getPk_payablebill());
			autoImageVO.setBillCodeType("expensesBill");
			autoImageVO.setBusinessType("304");
			if ("F1-Cxx-W04".equals(vo.getPk_tradetype())) {
				autoImageVO.setBillUse("30402");
			} else {
				autoImageVO.setBillUse("30401");
			}
			autoImageVO.setUserName(ImageCommonUtil.getUserName(vo.getBillmaker()));
			autoImageVO.setUserCode(ImageCommonUtil.getUserCode(vo.getBillmaker()));
			autoImageVO.setPurchaserName(ImageCommonUtil.getCorporationName(vo.getPk_org()));
			autoImageVO.setPurchaserTaxNo(ImageCommonUtil.getTaxPayerCode(vo.getPk_org()));
			autoImageVO.setSettlementNo(vo.getBillno());
			autoImageVO.setCreateTime((new UFDateTime()).toStdString());
			autoImageVO.setStatus("1");
			autoImageVO.setTotalAmount(vo.getMoney().toString());
			autoImageVO.setRemark(vo.getScomment());
			autoImageVO.setSystemOrig(2);
			AutoVO autoVO = new AutoVO();
			autoVO.setBillMain(autoImageVO);

			List<Map<String, String>> files = new ArrayList<Map<String, String>>();
			Map<String, String> file = new HashMap<>();
			file.put("fileName", getTradetypeName(vo.getPk_tradetype()));
			file.put("fileType", ".pdf");
			file.put("isTransform", "1");
			file.put("businessFileType", "coverAudit");
			String acttach = file.get("fileName") + autoImageVO.getBillCode();
			file.put("attachmentName", acttach);
			List<Map<String, String>> query = (List<Map<String, String>>) getDAO().executeQuery(
					"select vdef1,appcode  from  erm_bgyimageconfig where transtype ='"+vo.getPk_tradetype()+"'",
					new MapListProcessor());
			StringBuffer url = new StringBuffer();
			if(query==null || query.size()<=0) {
				throw new BusinessException("获取传影像审批封面地址失败,交易类型为："+vo.getPk_tradetype()+"，请联系用友顾问!");
			}
			url.append(query.get(0).get("vdef1") + "?");
			url.append("appcode="+query.get(0).get("appcode")+"");
			url.append("&Oids=" + vo.getPk_payablebill());

			String fileUrl = url.toString();

			file.put("fileUrl", fileUrl);
			files.add(file);
			autoVO.setFiles(files);
			getiImagePubService().AutoUpdateImage(autoVO);
		} catch (BusinessException e) {
			ExceptionUtils.wrappException(e);
		}

	}

	public void ImageCover(PayableBillVO vo) {
		try {
			List<ImageCoverVO> coverVOs = new ArrayList<ImageCoverVO>();
			ImageCoverVO coverVO = new ImageCoverVO();
			coverVO.setBillCode(vo.getPk_payablebill());
			coverVO.setBillCodeType("expensesBill");
			coverVO.setUserCode(getUserPK(vo.getBillmaker()));
			coverVO.setSystemOrig("2");
			coverVO.setFileOperationType("cover");
			List<Map<String,String>> files = new ArrayList<Map<String,String>>();
			Map<String, String> file = new HashMap<>();
			file.put("fileName", getTradetypeName(vo.getPk_tradetype()));
			file.put("fileType", ".pdf");
			file.put("isTransform", "1");
			file.put("businessFileType", "coverAudit");
			String acttach = file.get("fileName") + coverVO.getBillCode();
			file.put("attachmentName", acttach);
			List<Map<String, String>> query = (List<Map<String, String>>) getDAO().executeQuery(
					"select vdef1,appcode  from  erm_bgyimageconfig where transtype ='"+vo.getPk_tradetype()+"'",
					new MapListProcessor());
			StringBuffer url = new StringBuffer();
			if(query==null || query.size()<=0) {
				throw new BusinessException("获取传影像审批封面地址失败,交易类型为："+vo.getPk_tradetype()+"，请联系用友顾问!");
			}
			url.append(query.get(0).get("vdef1") + "?");
			url.append("appcode="+query.get(0).get("appcode")+"");
			url.append("&Oids=" + vo.getPk_payablebill());
			
			String fileUrl = url.toString();
			
			file.put("fileUrl",fileUrl );
			files.add(file);
			coverVO.setFiles(files);
			coverVOs.add(coverVO);
			getiImagePubService().updateImageCover(coverVOs);
		} catch (BusinessException e) {
			ExceptionUtils.wrappException(e);
		}
	}
	
	public static void checkInvoice(AggPayableBillVO vo) throws BusinessException {
		//检查发票为空不走校验逻辑  2021-05-25 ll
		StringBuilder sql = new StringBuilder();
		  sql.append("select pk_bxdhead");
		  sql.append("  from er_erminvoice");
		  sql.append(" where pk_bxdhead = '"+vo.getHeadVO().getPk_payablebill()+"' ");
		  sql.append(" and dr = 0 ");
		String pk_bxdhead = "";
		try {
			pk_bxdhead  = (String) getDAO().executeQuery(sql.toString(), new ColumnProcessor());
		} catch (DAOException e) {
			ExceptionUtils.wrappBusinessException("计算发票总合计金额失败,请联系用友顾问!");
		}
//		if(pk_bxdhead!=null && !"".equals(pk_bxdhead)) {
		// 发票总额与单据总额校验，当发票总额小于单据总额时控制单据不允许提交
//		UFDouble total = vo.getHeadVO().getMoney();
		//修改检验为单据总额减去单据上对应行存在根据《发票类型-物业》自定义档案简称字段判断，
		//为Y的那些行含税金额数据，再跟发票总额比对
		PayableBillItemVO[] items=(PayableBillItemVO[]) vo.getChildrenVO();
		UFDouble money_cr= UFDouble.ZERO_DBL;
		if(items!=null&&items.length>0)
		for(PayableBillItemVO itemvo:items) {
			if(getShort(itemvo.getDef27()))
			money_cr=money_cr.add(itemvo.getMoney_cr());
		}
		UFDouble total=vo.getHeadVO().getMoney().sub(money_cr);
		//修改校验结束  xuyong
		  sql = new StringBuilder();
		  sql.append("select to_char(sum(hjje))");
		  sql.append("  from er_erminvoice");
		  sql.append(" where pk_bxdhead = '"+vo.getHeadVO().getPk_payablebill()+"' ");
		  sql.append(" and dr = 0 ");
		String totalInvoice = "";
		try {
			totalInvoice  = (String) getDAO().executeQuery(sql.toString(), new ColumnProcessor());
		} catch (DAOException e) {
			ExceptionUtils.wrappBusinessException("计算发票总合计金额失败,请联系用友顾问!");
		}
		if((StringUtils.isBlank(totalInvoice) ? UFDouble.ZERO_DBL : new UFDouble(totalInvoice)).compareTo(total) < 0) {
			throw new BusinessException("发票总额小于单据总额,单据不允许提交!");
		}
		
		// 发票可抵扣金额与NCC单据金额可抵扣金额比较，当小于时不允许提交
		UFDouble totalTaxAmount=new UFDouble(0);
		for(nc.vo.arap.payable.PayableBillItemVO bvo :vo.getBodyVOs()) {
			totalTaxAmount=totalTaxAmount.add(bvo.getLocal_tax_cr());
		}
		
		sql = new StringBuilder("select to_char(sum(defitem4))") 
				.append("  from er_erminvoice")
				.append(" where pk_bxdhead = '"+ vo.getHeadVO().getPk_payablebill() +"' ")
				.append(" and dr = 0 ");
		String totalDefitem4 = "";
		try {
			totalDefitem4  =  (String) getDAO().executeQuery(sql.toString(), new ColumnProcessor());
		} catch (DAOException e) {
			ExceptionUtils.wrappBusinessException("计算发票总可抵扣金额失败,请联系用友顾问!");
		}
		if((StringUtils.isBlank(totalDefitem4) ? UFDouble.ZERO_DBL : new UFDouble(totalDefitem4)).compareTo(totalTaxAmount) != 0) {
			throw new BusinessException("发票可抵扣金额不等于NCC单据金额可抵扣金额,单据不允许提交!");
		}
		// 法人
		String fr = getCorporationName(vo.getHeadVO().getPk_org());
		
		sql = new StringBuilder("select gmfmc")
				.append("  from er_erminvoice")
				.append(" where pk_bxdhead = '"+ vo.getHeadVO().getPk_payablebill() +"' ")
				.append(" and dr = 0 ");
		List<String> invoiceFR = new ArrayList<String>();
		try {
			invoiceFR  = (List<String>) getDAO().executeQuery(sql.toString(), new ColumnListProcessor());
		} catch (DAOException e) {
			ExceptionUtils.wrappBusinessException("获取发票购买方名称失败,请联系用友顾问!");
		}
		for(String infr : invoiceFR) {
			if(infr!=null && !infr.equals("") && !infr.equals(fr)) { //发票购方名称为空不进行对比 2021-06-03 ll
				throw new BusinessException("发票上的购方名称与单据上的费用入账单位的法人组织不匹配,单据不允许提交!");
			}
		}
		
		//发票上的销方单位需要跟对公单据上的收款单位保持一致进行校验
		sql = new StringBuilder("select xsfmc,defitem7")
				.append("  from er_erminvoice")
				.append(" where pk_bxdhead = '"+ vo.getHeadVO().getPk_payablebill() +"' ")
				.append(" and dr = 0 ");
		List<Map<String, String>> invoiceDW = new ArrayList<Map<String, String>>();
		try {
			invoiceDW  = (List<Map<String, String>>) getDAO().executeQuery(sql.toString(),new MapListProcessor());
		} catch (DAOException e) {
			ExceptionUtils.wrappBusinessException("获取发票信息失败,请联系用友顾问!");
		}
		
		 sql = new StringBuilder("select name ")
				.append(" from bd_supplier a")
				.append(" where a.pk_supplier = '"+ vo.getHeadVO().getSupplier() +"'");
		String result = "";
		try {
			result = (String) getDAO().executeQuery(sql.toString(), new ColumnProcessor());
		} catch (DAOException e) {
			ExceptionUtils.wrappBusinessException("根据供应商主键查询供应商名称失败,请联系用友顾问!");
		}
		
		for(Map infr : invoiceDW) {
			if(infr != null && infr.get("xsfmc") != null && !result.equals(infr.get("xsfmc")) && !"1".equals(infr.get("defitem7"))) {
				throw new BusinessException("发票上的销方单位跟对公单据上的收款单位不一致,单据不允许提交!");
			}
		}
//		}
	}
	
	private String getTradetypeName(String imageId) {
		String sql = new StringBuilder("select billtypename ")
				.append(" from ")
				.append(" bd_billtype ")
				.append(" where pk_billtypecode = '" + imageId + "'").toString();
		String result = "";
		try {
			result = (String) getDAO().executeQuery(sql, new ColumnProcessor());
		} catch (DAOException e) {
			ExceptionUtils.wrappBusinessException("查询单据类型名称出错,"+e.getMessage());
		}
		return result;
	}
	
	/**
	 * 根据组织主键查询法人公司名称
	 * @param pk_org 组织主键
	 * @return
	 */
	public static String getCorporationName(String pk_org) {
		String sql = new StringBuilder("select def19")
				.append(" from org_orgs_v a")
				.append(" where a.pk_org = '"+ pk_org +"'").toString();
		String result = "";
		try {
			result = (String) getDAO().executeQuery(sql, new ColumnProcessor());
		} catch (DAOException e) {
			ExceptionUtils.wrappBusinessException("根据组织主键查询法人公司名称失败,请联系用友顾问!");
		}
		return result;
	}
	/**
	 * 判断简称是否为Y
	 * 
	 * */
	private static boolean getShort(String Id) {
		boolean bool=false;
		String sql = new StringBuilder("select shortname ")
				.append(" from ")
				.append(" bd_defdoc ")
				.append(" where pk_defdoc = '" + Id + "'")
				.append(" and dr = 0 and shortname='Y' ").toString();
		String result = "";
		try {
			result = (String) getDAO().executeQuery(sql, new ColumnProcessor());
			if(!StringUtils.isBlank(result)) {
				bool=true;
			}
		} catch (DAOException e) {
			ExceptionUtils.wrappBusinessException("查询发票类型简称出错,"+e.getMessage());
		}
		return bool;
	}
	
	private String getUserPK(String imageId) {
		String sql = new StringBuilder("select user_code ")
				.append(" from ")
				.append(" sm_user ")
				.append(" where cuserid = '" + imageId + "'")
				.append(" and dr = 0").toString();
		String result = "";
		try {
			result = (String) getDAO().executeQuery(sql, new ColumnProcessor());
		} catch (DAOException e) {
			ExceptionUtils.wrappBusinessException("查询原影像信息单据主键出错,"+e.getMessage());
		}
		return result;
	}
	
	private static BaseDAO getDAO() {
	
     BaseDAO dao = new BaseDAO();
		return dao;
	}
	
	private static IImagePubService getiImagePubService() {
		IImagePubService iImagePubService = NCLocator.getInstance().lookup(IImagePubService.class);
		return iImagePubService;
	}
	

}
