package nc.wy.baseapp.utils;

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

import org.apache.commons.lang3.StringUtils;

import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
import nc.jdbc.framework.SQLParameter;
import nc.jdbc.framework.processor.ArrayListProcessor;
import nc.jdbc.framework.processor.ColumnListProcessor;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.vo.baseapp.image.ErmInvoice;
import nc.vo.baseapp.image.ImageInvoiceHVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFDateTime;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;

public class InsertErminvoice {
	
	private static BaseDAO dao = null;
	
	public static void insertVO(String billid, ImageInvoiceHVO imageInvoiceHVO) throws BusinessException {
		ErmInvoice ermInvoice = new ErmInvoice();
		Object[] list = (Object[]) getJKBXMessage(billid).get(0);
		ermInvoice.setCreator(list[4] == null ? "" : list[4].toString());
		// 发票是否新增标识 0否 1是
		ermInvoice.setDefitem1(imageInvoiceHVO.getIsAdd());
		// 发票是否修改标识 0否 1是
		ermInvoice.setDefitem2(imageInvoiceHVO.getIsChange());
		// 发票类型
		ermInvoice.setDefitem3(imageInvoiceHVO.getInvoiceType());
		// 发票地址
		ermInvoice.setFileurl(imageInvoiceHVO.getImageUrl());
		ermInvoice.setFpdm(imageInvoiceHVO.getInvoiceCode());
		ermInvoice.setFphm(imageInvoiceHVO.getInvoiceNo());
		ermInvoice.setFplxbm("invoice001");
		ermInvoice.setFplxmc("invoice001");
		ermInvoice.setFplxpk("invoice001");
		ermInvoice.setXsfnsrsbh(imageInvoiceHVO.getSellerTaxNo());
		ermInvoice.setCheckcode(imageInvoiceHVO.getCheckCode());
		ermInvoice.setDefitem7(imageInvoiceHVO.getIsReplace());//增加是否代开
		ermInvoice.setDefitem10(imageInvoiceHVO.getTicketCode());
		ermInvoice.setDefitem11(imageInvoiceHVO.getInvoiceId());
		ermInvoice.setGmfmc(imageInvoiceHVO.getPurchaserName());
		ermInvoice.setHjje(new UFDouble(imageInvoiceHVO.getAmountWithTax()));
		ermInvoice.setInspectstatus(1);
		ermInvoice.setJshj(new UFDouble(imageInvoiceHVO.getAmountWithTax()));
		if(null != imageInvoiceHVO.getPaperDrewDate()) {
			String kprq = imageInvoiceHVO.getPaperDrewDate();
			ermInvoice.setKprq(changeDateTime(kprq));
		}
		ermInvoice.setPk_billtype(getPk_billtype("267X"));
		ermInvoice.setPk_bxdhead(billid);
		ermInvoice.setPk_group(list[0] == null ? "" : list[0].toString());
		ermInvoice.setPk_org(list[1] == null ? "" : list[1].toString());
		ermInvoice.setPk_org_v(list[2] == null ? "" : list[2].toString());
		ermInvoice.setPk_psndoc(list[3] == null ? "" : getPk_psndoc(list[3].toString()));
		// 发票报销状态：已归集
		ermInvoice.setPurchaserstatus(34);
		ermInvoice.setSl(imageInvoiceHVO.getTaxRate());
		ermInvoice.setSourcetype("264X");
		ermInvoice.setTaxamount(new UFDouble(imageInvoiceHVO.getTaxAmount()));
		ermInvoice.setTniamount(new UFDouble(imageInvoiceHVO.getAmountWithTax()).sub(new UFDouble(imageInvoiceHVO.getTaxAmount())).toString());
		ermInvoice.setXsfmc(imageInvoiceHVO.getSellerName());
		// 可抵扣税额
		if(isDK(imageInvoiceHVO.getInvoiceType())) {
			ermInvoice.setDefitem4(imageInvoiceHVO.getTaxAmount());
		} else {
			ermInvoice.setDefitem4("0");
		}
		getDAO().insertVO(ermInvoice);
	}
	
	/**
	 * 查询报销单信息
	 * @param billid
	 * @return
	 */
	private static List getJKBXMessage(String billid) {
		String sql = new StringBuilder("select pk_group,pk_org,pk_org_v,operator,creator")
				.append(" from er_bxzb")
				.append(" where pk_jkbx = '" + billid + "'")
				.append(" and dr = 0").toString();
		List result = null;
		try {
			result = (List) getDAO().executeQuery(sql, new ArrayListProcessor());
		} catch (DAOException e) {
			ExceptionUtils.wrappBusinessException("查询报销单组织信息出错,"+e.getMessage());
		}
		return result;
	}
	
	/**
	 * 查询费用发票主键
	 * @param code
	 * @return
	 */
	private static String getPk_billtype(String code) {
		String sql = new StringBuilder("select pk_billtypeid")
				.append(" from bd_billtype")
				.append(" where pk_billtypecode = '" + code + "'")
				.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 UFDateTime changeDateTime(String date) {
		if(!StringUtils.isBlank(date)) {
			date = date.substring(0, 4) + "-" + date.substring(4, 6) + "-" + date.substring(6, 8) + " 00:00:00";
		}
		return new UFDateTime(date);
	}
	
	/**
	 * 判断是否报销单
	 * @param billid
	 * @return
	 */
	public static boolean isBXZB(String billid) {
		String sql = new StringBuilder("select pk_jkbx")
				.append(" from er_bxzb")
				.append(" where pk_jkbx = '" + billid + "'")
				.append(" and dr = 0").toString();
		Boolean isexist = Boolean.FALSE;
		String result = "";
		try {
			result = (String) getDAO().executeQuery(sql, new ColumnProcessor());
			if(!StringUtils.isBlank(result)) {
				isexist = Boolean.TRUE;
			}
		} catch (DAOException e) {
			ExceptionUtils.wrappBusinessException("根据主键查询报销单出错,"+e.getMessage());
		}
		return isexist;
	}
	/**
	 * 应付发票同步票夹
	 * 2021-05-20 ll
	 * @param billid
	 * @param imageInvoiceHVO
	 * @throws BusinessException
	 */
	public static void payablebillInsertVO(String billid, ImageInvoiceHVO imageInvoiceHVO) throws BusinessException {
		ErmInvoice ermInvoice = new ErmInvoice();
		Object[] list = (Object[]) getPayablebillMessage(billid).get(0);
		ermInvoice.setCreator(list[4] == null ? "" : list[4].toString());
		// 发票是否新增标识 0否 1是
		ermInvoice.setDefitem1(imageInvoiceHVO.getIsAdd());
		// 发票是否修改标识 0否 1是
		ermInvoice.setDefitem2(imageInvoiceHVO.getIsChange());
		// 发票类型
		ermInvoice.setDefitem3(imageInvoiceHVO.getInvoiceType());
		// 发票地址
		ermInvoice.setFileurl(imageInvoiceHVO.getImageUrl());
		ermInvoice.setFpdm(imageInvoiceHVO.getInvoiceCode());
		ermInvoice.setFphm(imageInvoiceHVO.getInvoiceNo());
		ermInvoice.setFplxbm("invoice001");
		ermInvoice.setFplxmc("invoice001");
		ermInvoice.setFplxpk("invoice001");
		ermInvoice.setXsfnsrsbh(imageInvoiceHVO.getSellerTaxNo());
		ermInvoice.setCheckcode(imageInvoiceHVO.getCheckCode());
		ermInvoice.setDefitem7(imageInvoiceHVO.getIsReplace());//增加是否代开
		ermInvoice.setDefitem10(imageInvoiceHVO.getTicketCode());
		ermInvoice.setDefitem11(imageInvoiceHVO.getInvoiceId());
		ermInvoice.setGmfmc(imageInvoiceHVO.getPurchaserName());
		ermInvoice.setHjje(new UFDouble(imageInvoiceHVO.getAmountWithTax()));
		ermInvoice.setInspectstatus(1);
		ermInvoice.setJshj(new UFDouble(imageInvoiceHVO.getAmountWithTax()));
		if(null != imageInvoiceHVO.getPaperDrewDate()) {
			String kprq = imageInvoiceHVO.getPaperDrewDate();
			ermInvoice.setKprq(changeDateTime(kprq));
		}
		ermInvoice.setPk_billtype(getPk_billtype("267X"));
		ermInvoice.setPk_bxdhead(billid);
		ermInvoice.setPk_group(list[0] == null ? "" : list[0].toString());
		ermInvoice.setPk_org(list[1] == null ? "" : list[1].toString());
		ermInvoice.setPk_org_v(list[2] == null ? "" : list[2].toString());
		ermInvoice.setPk_psndoc(list[3] == null ? "" : getPk_psndoc(list[3].toString())); //还原发票人员字段 2021-05-27 ll
		// 发票报销状态：已归集
		ermInvoice.setPurchaserstatus(34);
		ermInvoice.setSl(imageInvoiceHVO.getTaxRate());
		ermInvoice.setSourcetype(list[5] == null ? "" : list[5].toString());
		ermInvoice.setTaxamount(new UFDouble(imageInvoiceHVO.getTaxAmount()));
		ermInvoice.setTniamount(new UFDouble(imageInvoiceHVO.getAmountWithTax()).sub(new UFDouble(imageInvoiceHVO.getTaxAmount())).toString());
		ermInvoice.setXsfmc(imageInvoiceHVO.getSellerName());
		// 可抵扣税额
		if(isDK(imageInvoiceHVO.getInvoiceType())) {
					ermInvoice.setDefitem4(imageInvoiceHVO.getTaxAmount());
		} else {
					ermInvoice.setDefitem4("0");
		}
		getDAO().insertVO(ermInvoice);
	}
	
	private static List getPayablebillMessage(String billid) {
		String sql = new StringBuilder("select pk_group,pk_org,pk_org_v,billmaker,creator,pk_tradetype")
				.append(" from ap_payablebill")
				.append(" where pk_payablebill = '" + billid + "'")
				.append(" and dr = 0").toString();
		List result = null;
		try {
			result = (List) getDAO().executeQuery(sql, new ArrayListProcessor());
		} catch (DAOException e) {
			ExceptionUtils.wrappBusinessException("查询报销单组织信息出错,"+e.getMessage());
		}
		return result;
	}
	
	/**
	 * 验证是否应付发票
	 * 2021-05-20 ll
	 * @param billid
	 * @return
	 */
	public static boolean ispayablebill(String billid) {
		String sql = new StringBuilder("select pk_payablebill")
				.append(" from ap_payablebill")
				.append(" where pk_payablebill = '" + billid + "'")
				.append(" and dr = 0").toString();
		Boolean isexist = Boolean.FALSE;
		String result = "";
		try {
			result = (String) getDAO().executeQuery(sql, new ColumnProcessor());
			if(!StringUtils.isBlank(result)) {
				isexist = Boolean.TRUE;
			}
		} catch (DAOException e) {
			ExceptionUtils.wrappBusinessException("根据主键查询应付单出错,"+e.getMessage());
		}
		return isexist;
	}
	
	/**
	 * 根据用户主键查找人员主键
	 * @author chenjm
	 * @param pkUser
	 * @return
	 */
	public static String getPk_psndoc(String pkUser){
		String sql = new StringBuilder("SELECT SM_USER.PK_PSNDOC")
				.append("  FROM SM_USER")
				.append("   WHERE SM_USER.CUSERID = '"+pkUser+"'").toString();
		String result = "";
		try {
			result = (String) getDAO().executeQuery(sql, new ColumnProcessor());
		} catch (DAOException e) {
			ExceptionUtils.wrappBusinessException("根据用户主键查找人员主键失败,请联系用友顾问!");
		}
		return result;
	}
	
	/**
	 * 是否可抵扣
	 * @param invoiceType 发票类型编码
	 * @return
	 * @throws BusinessException
	 */
	public static boolean isDK(String invoiceType) throws BusinessException{
		String sql = new StringBuilder("select b.code")
				.append(" from bd_defdoclist a")
				.append(" left join bd_defdoc b")
				.append(" on a.pk_defdoclist = b.pk_defdoclist")
				.append(" where a.code = 'WY888'")
				.append(" and b.enablestate = 2").toString();
		List<String> result = new ArrayList<>();
		try {
			result = (List<String>) getDAO().executeQuery(sql, new ColumnListProcessor());
		} catch (DAOException e) {
			ExceptionUtils.wrappBusinessException("查询发票是否可抵扣失败,请联系用友顾问!");
		}
		if(result.contains(invoiceType)) {
			return true;
		}
		return false;
	}
	
	private static BaseDAO getDAO() {
		if(null == dao) {
			dao = new BaseDAO();
		}
		return dao;
	}

}
