package nc.pubimpl.paybill.yx;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.impl.am.db.processor.CountProcessor;
import nc.impl.pubapp.pattern.data.bill.BillQuery;
import nc.jdbc.framework.SQLParameter;
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.AggPayBillVO;
import nc.vo.arap.pay.PayBillVO;
import nc.vo.arap.pay.bzfk.ImageCoverVO;
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.pubapp.pattern.exception.ExceptionUtils;

/**
 * 调用影像接口实现类
 * 
 * @author ll
 * @date 2021-05-26
 */
public class NCCPaybillBusinessListener {

	public void getService(AggPayBillVO[] volist) throws BusinessException {
		IImagePubService lookup = NCLocator.getInstance().lookup(IImagePubService.class);
		for (AggPayBillVO baseAggVO : volist) {
			PayBillVO hvo = baseAggVO.getHeadVO();
			if (("F3-Cxx-W02".equals(hvo.getPk_tradetype()) || "F3-Cxx-W04".equals(hvo.getPk_tradetype()))
					&& "Y".equals(hvo.getDef70())) {
				String primaryKey = hvo.getPk_paybill();
				String effectstatus = hvo.getEffectstatus().toString();
				String billstatus = hvo.getApprovestatus().toString();
				if ("-1".equals(billstatus) && "0".equals(effectstatus) && hvo.getStatus() != VOStatus.DELETED) {
					billstatus = "1";
				} else if ("3".equals(billstatus)) {
					billstatus = "0";
				} else if ("1".equals(billstatus)) {
					this.ImageCover(hvo);
					return;
				} else if (hvo.getStatus() == VOStatus.DELETED) {
					billstatus = "3";
				} else {
					return;
				}
				lookup.updateImageStatus(primaryKey, billstatus);
			//update by guojx 采购付款单调用影像接口		
			} else if (("F3-Cxx-W02".equals(hvo.getPk_tradetype()) || "F3-Cxx-W04".equals(hvo.getPk_tradetype()))
					&& "N".equals(hvo.getDef70() == null ? "N" : hvo.getDef70())) {
				// 自动创建影像接口
				String billstatus = hvo.getApprovestatus().toString();
				String billid = hvo.getPk_paybill();
				if (!isSendImage(billid)) {
					if ("1".equals(billstatus))
						this.AutoImageCover(hvo);
				}
			} else if ("F3-Cxx-W01".equals(hvo.getPk_tradetype())) {
				UFDate creationtime=hvo.getCreationtime().getDate();//单据创建日期
				UFDate Time = new UFDate("2021-10-19 00:00:00");//单据控制时间
				if(!Time.before(creationtime)) {
					return;
				}
				
				// modify by longht 有票无票都推封面 20210826 start
				// String sql = "select * from er_erminvoice e join "//modify by longht
				// 处理付款单不传封面到影像问题 20210825
				String sql = "select count(1) from er_erminvoice e join "
						+ "(select distinct a.pk_payablebill,b.pk_paybill " + "from  ap_payablebill a "
						+ "inner join ap_payitem b on a.pk_payablebill=b.top_billid) ap on ap.pk_payablebill = e.pk_bxdhead "
						+ "where ap.pk_paybill = ? ";
				SQLParameter params = new SQLParameter();
				params.addParam(hvo.getPk_paybill());
				Integer query = (Integer) getDAO().executeQuery(sql, params, new CountProcessor());// 无票有票付款主键传递不一样
//				if(query != null && query > 0 &&"1".equals(hvo.getApprovestatus().toString())) {
//					this.ImageCover(hvo);
//				}
				// modify by longht 有票无票都推封面 20210826 end
				// 增加明源单据状态更新 xuyong 2021-08-30 start
				String primaryKey = hvo.getDef1();
				String effectstatus = hvo.getEffectstatus().toString();
				String billstatus = hvo.getApprovestatus().toString();
				if (query != null && query > 0) {
					if("1".equals(billstatus)) {
						this.AutoImageCover(hvo);
					}
				} else {
					if (hvo.getStatus() == VOStatus.DELETED) {
						lookup.updateImageStatus(primaryKey, "1");
					} else if ("1".equals(billstatus)) {
						this.ImageCover(hvo);
					} else {
						return;
					}
					
					// 增加明源单据状态更新 xuyong 2021-08-30 end
				}
				//update by guojx 采购付款单调用影像接口
			}else if("F3-Cxx-D42".equals(hvo.getPk_tradetype())&& "Y".equals(hvo.getDef70())) {
				String billstatus = hvo.getApprovestatus().toString();
				if("1".equals(billstatus)) {
					this.AutoImageCover(hvo);
				}
			}
		}
	}

	public void AutoImageCover(PayBillVO vo) {
		try {
			ImageContentVO autoImageVO = new ImageContentVO();
			autoImageVO.setBillCode(vo.getPk_paybill());
			//update by guojx 采购付款单调用影像接口
			if("F3-Cxx-D42".equals(vo.getPk_tradetype())) {
				autoImageVO.setBillCodeType("accountBill");
				autoImageVO.setBusinessType("209");
			}else {
				autoImageVO.setBillCodeType("expensesBill");
				autoImageVO.setBusinessType("305");
			}
			if("F3-Cxx-D42".equals(vo.getPk_tradetype())) {
				autoImageVO.setBillUse("20901");
			}else if ("F3-Cxx-W02".equals(vo.getPk_tradetype())) {
				autoImageVO.setBillUse("30501");
			} else {
				autoImageVO.setBillUse("30502");
			}
			if("F3-Cxx-W01".equals(vo.getPk_tradetype())) {
				autoImageVO.setBillCodeType("publicBill");
				autoImageVO.setBusinessType("101");
				autoImageVO.setBillUse("10101");	
			}
			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());
			if("F3-Cxx-D42".equals(vo.getPk_tradetype())) {
				autoImageVO.setSystemOrig(3);
			}else {
				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_paybill());

			String fileUrl = url.toString();

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

	}

	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 ImageCover(PayBillVO vo) {
		try {
			List<ImageCoverVO> coverVOs = new ArrayList<ImageCoverVO>();
			ImageCoverVO coverVO = new ImageCoverVO();
			coverVO.setBillCode(vo.getPk_paybill());
			coverVO.setBillCodeType("expensesBill");
			if("F3-Cxx-D42".equals(vo.getPk_tradetype())) {
				coverVO.setBillCodeType("accountBill");
			}
			if ("F3-Cxx-W01".equals(vo.getPk_tradetype()))
				coverVO.setBillCodeType("publicBill");
			if ("F3-Cxx-W01".equals(vo.getPk_tradetype()))
				coverVO.setBillCode(vo.getDef1());
			coverVO.setUserCode(InvocationInfoProxy.getInstance().getUserCode());
			if("F3-Cxx-D42".equals(vo.getPk_tradetype())) {
				coverVO.setSystemOrig("3");
			}else {
				coverVO.setSystemOrig("2");
			}
			coverVO.setFileOperationType("cover");
			// add by longht 付款单封面传输参数有问题，导致明源封面被覆盖 20210826 start
//			if("F3-Cxx-W01".equals(vo.getPk_tradetype()))
//				coverVO.setFileOperationType("hook");
			// add by longht 付款单封面传输参数有问题，导致明源封面被覆盖 20210826 end
			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");
			// modify by longht 付款单封面传输参数有问题，导致明源封面被覆盖 20210826 start
//			if (!ImageCommonUtil.isMYbill(vo.getPk_paybill()) && "F3-Cxx-W01".equals(vo.getPk_tradetype())) {
//				file.put("businessFileType", "cover");
//			}
			// modify by longht 付款单封面传输参数有问题，导致明源封面被覆盖 20210826 end
			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_paybill());

			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);
		}
	}

	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;
	}

	private String getUserPK(String imageId) {
		String sql = new StringBuilder("select user_code ").append(" from ").append(" sm_user ")
				.append(" where cuserid = '" + imageId + "'").toString();
		String result = "";
		try {
			result = (String) getDAO().executeQuery(sql, new ColumnProcessor());
		} catch (DAOException e) {
			ExceptionUtils.wrappBusinessException("查询原影像信息单据主键出错," + e.getMessage());
		}
		return result;
	}

	private static IImagePubService getiImagePubService() {
		IImagePubService iImagePubService = NCLocator.getInstance().lookup(IImagePubService.class);
		return iImagePubService;
	}

	private static BaseDAO getDAO() {

		BaseDAO dao = new BaseDAO();
		return dao;
	}
}
