package nc.ui.hr.plugin;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import uap.distribution.dao.DAOException;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.hr.plugin.GetDataUtil;
import nc.bs.pub.pa.PreAlertObject;
import nc.bs.pub.taskcenter.BgWorkingContext;
import nc.bs.pub.taskcenter.IBackgroundWorkPlugin;
import nc.itf.hr.IReceivableService;
import nc.itf.uap.IUAPQueryBS;
import nc.itf.uap.IVOPersistence;
import nc.jdbc.framework.SQLParameter;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.log.NcLog;
import nc.vo.arap.receivable.AggReceivableBillVO;
import nc.vo.arap.receivable.ReceivableBillItemVO;
import nc.vo.arap.receivable.ReceivableBillVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pub.lang.UFDate;
import nc.vo.pub.lang.UFDateTime;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pub.lang.UFLiteralDate;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.pubapp.pflow.PfUserObject;

public class HrLaborcostcopycbPlugin implements IBackgroundWorkPlugin {

	static BaseDAO baseDao;

	public static BaseDAO getBaseDAO() {
		if (baseDao == null) {
			baseDao = new BaseDAO();
		}
		return baseDao;
	}

	private PfUserObject[] userObjs;
	// 新增、删除、更新API
	IVOPersistence iVOPersistence = (IVOPersistence) NCLocator.getInstance().lookup(IVOPersistence.class.getName());
	private IUAPQueryBS iuap = (IUAPQueryBS) NCLocator.getInstance().lookup(IUAPQueryBS.class.getName());

	// 集团
	String pk_group = "0001A110000000000LO7";

	public PreAlertObject executeTask(BgWorkingContext bgwc) throws BusinessException {
		NcLog.info("HrLaborcostcopycbPlugin定时任务开始执行");
		System.out.println("HrLaborcostcopycbPlugin定时任务开始执行");

		InvocationInfoProxy.getInstance().setGroupId(pk_group);

		Map<String, String> pndocIDMap = null;
		Map<String, String> outlaytypeIDMap = null;
		Map<String, String> xzsxIDMap = null;
		Map<String, String> islssuedIDMap = null;
		Map<String, String> ispaymentIDMap = null;
		Map<String, String> wa_typeIDMap = null;
		Map<String, String> wa_typeMemoMap = null;
		Map<String, String> pk_deptMap = null;
		Map<String, String> pk_accperiodmonthMap = null;
		String cuserid = null;
		String pk_taxcode = null;
		Map<String, String> pk_suppliermap = null;
		Map<String, String> orgnamemap = null;
		Map<String, List<String>> mapsl = null;
		Map<String, String> outlaytypeMemoMap = null;
		try {
			pndocIDMap = getPsndocID();// 人员主键
			outlaytypeIDMap = getOutlaytypeID();// 费用归属类别id
			outlaytypeMemoMap = getOutlaytypeMemo();// 费用归属类别备注
			xzsxIDMap = getXzsxID();// 薪资事项id
			islssuedIDMap = getIslssuedID();// 是否代发id
			ispaymentIDMap = getIspaymentID();// 是否代收付id
			wa_typeIDMap = getWa_typeid();// 薪资类型id
			wa_typeMemoMap = getWa_typeMemo();// 薪资类型备注
			pk_deptMap = getPk_dept();// 部门id
			pk_accperiodmonthMap = getPk_accperiodmonth();// 查询会计月份id
			cuserid = getCuserid();// 用户主键
			pk_taxcode = getPk_taxcode();// 税码主键
			pk_suppliermap = getPk_supplier();// 供应商主键
			orgnamemap = getOrgName();// 组织名称
			mapsl = getOrgPk();// 查询档案成本归属公司名称
		} catch (Exception e) {
			e.getStackTrace();
			NcLog.info("查询表数据异常" + e.getMessage());
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}

		LinkedHashMap<String, Object> billmap = bgwc.getKeyMap();
		String date = String.valueOf(billmap.get("date"));
		String ym = "";
		String date2 = "";
		if (date != null && !"null".equals(date)) {
			String yearst = date.substring(0, 4);
			String monthst = date.substring(4, 6);
			ym = yearst + "-" + monthst;
			date2 = yearst + monthst;
		} else {
			UFLiteralDate workday = new UFLiteralDate();
			String[] s = workday.toString().split("-");
			String s1 = s[0] + "-" + s[1] + "-" + "01";
			UFDate time = new UFDate(s1);
			UFDate time1 = time.getDateBefore(1);
			String[] s2 = time1.toString().split("-");
			ym = s2[0] + "-" + s2[1];
			date2 = s2[0] + s2[1];
		}

		List<Map<String, String>> listCostMap1 = null;

		List<Map<String, String>> listCostMap2 = null;

		if (date != null && !"null".equals(date)) {
			try {
				listCostMap2 = getLaborost1(date);// 人力成本备份数据
				listCostMap1 = getNewListCostMap(listCostMap2, mapsl, orgnamemap);
			} catch (Exception e) {
				e.getStackTrace();

				NcLog.info("手工传日期查询人力成本备份数据异常" + e.getMessage());
				ExceptionUtils.wrappBusinessException(e.getMessage());
			}
		} else {
			try {
				listCostMap2 = getLaborost1(date2);// 人力成本备份数据
				listCostMap1 = getNewListCostMap(listCostMap2, mapsl, orgnamemap);
			} catch (Exception e) {
				e.getStackTrace();
				NcLog.info("定时传日期查询人力成本备份数据异常" + e.getMessage());
				ExceptionUtils.wrappBusinessException(e.getMessage());
			}
		}
		
		List<String> wa_costorglist = new ArrayList<String>();
		for (Map<String, String> map : listCostMap1) {
			String wa_org = map.get("wa_org");
			String cost_org = map.get("cost_org");
			String wa_costorg = wa_org + "," + cost_org;
			if (wa_org != null && !"null".equals(wa_org) && cost_org != null && !"null".equals(cost_org)) {
				if (!wa_costorglist.contains(wa_costorg))
					wa_costorglist.add(wa_costorg);
			}
		}

		for (int j = 0; j < wa_costorglist.size(); j++) {
			try {
				String wa_costorg = wa_costorglist.get(j);
				String waorg = wa_costorg.split(",")[0];
				String costorg = wa_costorg.split(",")[1];
				UFDouble debitamounttotal = new UFDouble();
				AggReceivableBillVO aggReceivableBillVO = new AggReceivableBillVO();
				ReceivableBillVO receivableBillVO = new ReceivableBillVO();
				// 赋值主表数据
				String pk_org = waorg;
				receivableBillVO.setDef11("人力成本备份薪资发放公司-#" + pk_org + "#" + date2);
				String pk_org_v = getPkorgv(pk_org);
				receivableBillVO.setPk_group(pk_group);
				receivableBillVO.setPk_org(pk_org);// 应收财务组织
				receivableBillVO.setPk_org_v(pk_org_v);// 应收财务组织版本
				receivableBillVO.setSett_org(pk_org);// 结算财务组织
				receivableBillVO.setSett_org_v(pk_org);// 结算财务组织版本
				String pk_user = cuserid;// 制单人
				receivableBillVO.setBillmaker(pk_user);// 制单人
				Date newDate = convertStringToDate(ym + "-01", "yyyy-MM-dd");
				String nowMonthDateStr = getMonthLastDate(newDate, 1);// 下月最后一天
				nowMonthDateStr = nowMonthDateStr.substring(0, 7) + "-01";// 下月第一天
				receivableBillVO.setBilldate(new UFDate(nowMonthDateStr));// 单据日期
				receivableBillVO.setCreator(pk_user);// 创建人
				receivableBillVO.setCreationtime(new UFDateTime());// 创建时间
				receivableBillVO.setBillstatus(-1);// 单据状态
				receivableBillVO.setBusidate(new UFDate(nowMonthDateStr));// 开票日期
				receivableBillVO.setObjtype(0);// 往来对象
				receivableBillVO.setPk_deptid(GetDataUtil.getDeptPK(""));// 收款部门
				String pk_bankaccsub = GetDataUtil.getBankaccsubPK("");// 收款账户
				receivableBillVO.setRecaccount(pk_bankaccsub);// 收款银行账户
				receivableBillVO.setPk_busitype(getBusitypePK("AR01", pk_group));// 业务流程：选择收款
				receivableBillVO.setBillclass("ys");// 单据大类：应收单
				String year = nowMonthDateStr.substring(0, 4);// 会计年度
				String month = nowMonthDateStr.substring(5, 7);// 会计月份
				receivableBillVO.setBillyear(year);// 单据会计年度
				receivableBillVO.setBillperiod(month);// 单据会计期间
				receivableBillVO.setPk_billtype("F0");// 单据类型编码
				String pk_currtype = getcurrtype("CNY");// 币种
				receivableBillVO.setPk_currtype(pk_currtype);
				String pk_country = GetDataUtil.getCountryzonePK("CN");// 国家地区 默认CN
				receivableBillVO.setSendcountryid(pk_country);// 发货国
				receivableBillVO.setTaxcountryid(pk_country);// 报税国
				receivableBillVO.setSrc_syscode(0);// 单据来源系统
				receivableBillVO.setSyscode(0);// 单据所属系统
				String pk_tradetype = "F0-Cxx-01";// 应收类型：内部应收单(含代垫费用)
				receivableBillVO.setPk_tradetype(pk_tradetype);
				String pk_billtypeid = GetDataUtil.getBilltypePK(pk_tradetype, pk_group);
				receivableBillVO.setPk_tradetypeid(pk_billtypeid);
				receivableBillVO.setIsflowbill(UFBoolean.FALSE);// 是否流程单据
				receivableBillVO.setIsreded(UFBoolean.FALSE);// 是否红冲过

				List<ReceivableBillItemVO> listItemVO = new ArrayList<ReceivableBillItemVO>();
				String pk_supplier = pk_suppliermap.get(orgnamemap.get(waorg));// 供应商主键
				if (pk_supplier == null) {
					pk_supplier = pk_suppliermap.get("上海天华建筑设计有限公司");
				}
				int m = 0;
				for (int i = 0; i < listCostMap1.size(); i++) {
					ReceivableBillItemVO receivableBillItemVO = new ReceivableBillItemVO();
					Map<String, String> map = listCostMap1.get(i);
					String wa_org = map.get("wa_org");
					String cost_org = map.get("cost_org");
					String cost_dept = map.get("cost_dept");
					String outlaytype = map.get("outlaytype");
					String vdef3 = map.get("vdef3");
					String vdef4 = map.get("vdef4");
					String svdef4 = null;
					if (!"null".equals(vdef4) && vdef4 != null) {
						svdef4 = vdef4.substring(0, 4);
					}
					if (("null".equals(vdef4) || vdef4 == null) || !"GX05".equals(svdef4)) {
						vdef4 = "否";
					} else {
						vdef4 = "是";
					}
					String workercode = map.get("workercode");
					String name = map.get("name");
					String wa_type = map.get("wa_type");
					String islssued = map.get("islssued");
					String cost_orgname = orgnamemap.get(cost_org);
					String wa_orgname = orgnamemap.get(wa_org);
					if (mapsl != null && mapsl.size() > 0) {
						List<String> orgNameList = mapsl.get(cost_orgname);
						if (orgNameList != null && orgNameList.size() > 0) {
							if (orgNameList.contains(wa_orgname)) {
								islssued = "否";
							}
						}
					}
					Object decimalmny = map.get("decimalmny");
					UFDouble total = new UFDouble(decimalmny.toString());
					Double dtotal = -total.toDouble();
					debitamounttotal = debitamounttotal.add(dtotal);

					UFDouble fstotal = new UFDouble(dtotal);
					if (waorg.equals(wa_org) && costorg.equals(cost_org)) {
						// 赋值子表数据
						receivableBillItemVO.setPk_org(pk_org);
						receivableBillItemVO.setPk_org_v(pk_org_v);
						receivableBillItemVO.setPk_group(pk_group);
						receivableBillItemVO.setPk_fiorg(pk_org);// 应收财务组织
						receivableBillItemVO.setDef30(getDefdocPKByName("05", outlaytypeMemoMap.get(outlaytype)));// 费用归属—备注
						receivableBillItemVO.setDef23(outlaytype);// 费用归属类别
//						receivableBillItemVO.setDef26(GetDataUtil.getDefdocPK("S00009", "08", "代垫费用"));// 收款摘要：S00009代垫费用
						receivableBillItemVO.setDef26(GetDataUtil.getDefdocPK("S000091", "08", "代垫费用（薪酬）"));// 收款摘要：S000091代垫费用（薪酬）
						String watypeNewName = wa_typeMemoMap.get(wa_type);
//						receivableBillItemVO.setDef29(getDefdocPKByName("YS001", "人工成本结算--" + watypeNewName));// 收款业务性质：人工成本结算
						receivableBillItemVO.setDef29(getDefdocPKByName("YS001", "暂估人工成本结算-" + watypeNewName));// 收款业务性质：人工成本结算
						receivableBillItemVO.setDef15(GetDataUtil.getDefdocPK("其他合同（财务专用）", "01", "其他合同（财务专用）"));// 经营合同名称
						receivableBillItemVO.setDef16("其他合同（财务专用）");// 合同编号
						receivableBillItemVO.setDef10("冲"+date2);// 备注
//						receivableBillItemVO.setDef10(year + month + "人力成本备份" + workercode + name);// 备注
						receivableBillItemVO.setCustomer(getCustomerPKBynameOrPkorg(cost_orgname, cost_org));// 客户
//						receivableBillItemVO.setOrdercubasdoc(getCustomerPKByName(cost_orgname));// 订单客户
						receivableBillItemVO.setTaxcodeid(GetDataUtil.getTaxcodePK("10"));// 税码
						receivableBillItemVO.setTaxrate(new UFDouble(0));// 税率
						receivableBillItemVO.setLocal_money_bal(fstotal);// 组织本币余额
						receivableBillItemVO.setLocal_money_de(fstotal);// 价税合计
						receivableBillItemVO.setLocal_notax_de(fstotal);// 金额
						receivableBillItemVO.setLocal_tax_de(new UFDouble(0));// 税额
						receivableBillItemVO.setLocal_price(fstotal);// 本币单价
						receivableBillItemVO.setLocal_taxprice(fstotal);// 本币含税单价
						receivableBillItemVO.setMoney_bal(fstotal);// 原币余额
						receivableBillItemVO.setMoney_de(fstotal);// 借方原币金额
						receivableBillItemVO.setNotax_de(fstotal);// 借方原币无税金额
						receivableBillItemVO.setOccupationmny(fstotal);// 预占用原币余额
						receivableBillItemVO.setCaltaxmny(fstotal);// 计税金额
						receivableBillItemVO.setPrice(fstotal);// 单价
						receivableBillItemVO.setTaxprice(fstotal);// 含税单价
						receivableBillItemVO.setBilldate(new UFDate(nowMonthDateStr));// 单据日期
						receivableBillItemVO.setBusidate(new UFDate(nowMonthDateStr));// 起算日期
						receivableBillItemVO.setPk_billtype("F0");// 单据类型编码
						receivableBillItemVO.setBillclass("ys");// 单据大类
						receivableBillItemVO.setRowno(m * 10 + 10);// 单据分录号--行号
						receivableBillItemVO.setRowtype(22);// 行类型：22代垫
						receivableBillItemVO.setDirection(1);// 方向：1借方
						receivableBillItemVO.setPk_currtype(pk_currtype);// 币种
						receivableBillItemVO.setTaxtype(1);// 扣税类别：1应税外加
						receivableBillItemVO.setObjtype(0);// 往来对象：0客户
						receivableBillItemVO.setSendcountryid(pk_country);// 发货国
						receivableBillItemVO.setBuysellflag(1);// 购销类型：1国内销售
//						receivableBillItemVO.setProject("PM201601130001");// 项目：其他
						receivableBillItemVO.setPk_billtype("F0");// 单据类型编码
						if ("是".equals(islssued)) {
							receivableBillItemVO.setPk_deptid(pk_deptMap.get(wa_org));// 部门
							receivableBillItemVO.setPk_deptid_v(pk_deptMap.get(wa_org));// 部门
						} else {
							receivableBillItemVO.setPk_deptid(cost_dept);// 部门
							receivableBillItemVO.setPk_deptid_v(cost_dept);// 部门
						}
						receivableBillItemVO.setDef28(cost_dept);// 对应协同单据应付单的付款部门
						receivableBillItemVO.setPk_tradetype(pk_tradetype);// 应收类型code：内部应收单(含代垫费用)
						receivableBillItemVO.setPk_tradetypeid(pk_billtypeid);// 应收类型id
						receivableBillItemVO.setQuantity_bal(new UFDouble(1));// 数量余额
						receivableBillItemVO.setQuantity_de(new UFDouble(1));// 借方数量
						receivableBillItemVO.setRate(new UFDouble(1));// 组织本币税率
						receivableBillItemVO.setRecaccount(pk_bankaccsub);// 收款银行账户
						receivableBillItemVO.setRececountryid(pk_country);// 收货国
						receivableBillItemVO.setSett_org(pk_org);// 结算财务组织
						receivableBillItemVO.setSett_org_v(pk_org);// 结算财务组织版本
						receivableBillItemVO.setTriatradeflag(UFBoolean.FALSE);// 三角贸易区
						receivableBillItemVO.setSettlecurr(pk_currtype);// 收款币种
						receivableBillItemVO.setSettlemoney(fstotal);// 收款金额
						listItemVO.add(receivableBillItemVO);
						m++;
					}
				}
				receivableBillVO.setLocal_money(debitamounttotal);// 合计金额--本币金额
				receivableBillVO.setMoney(debitamounttotal);// 原币金额
				aggReceivableBillVO.setParentVO(receivableBillVO);
				aggReceivableBillVO.setChildrenVO(listItemVO.toArray(new ReceivableBillItemVO[listItemVO.size()]));
				// 调用应收单新增方法
				IReceivableService receivableService = NCLocator.getInstance().lookup(IReceivableService.class);
				AggReceivableBillVO aggvo = receivableService.receivable_RequiresNew(aggReceivableBillVO);
			} catch (Exception e) {
				e.getStackTrace();
				e.getMessage();
				NcLog.info("生成应收单异常" + e.getMessage());
				continue;
			}
		}
		return null;
	}

	/**
	 * 查询人力成本数据差异数据
	 */
	public List<Map<String, String>> getLaborost1(String date) throws Exception {
		String sql = "SELECT t.wa_period,t.workercode,t.name,t.wa_org,t.data_source,t.cost_org,t.cost_dept,t.outlaytype,t.wa_type,t.vdef2,t.vdef3,t.vdef4,SUM(t.decimalmny) decimalmny,"
				+ " case when t.wa_org != t.cost_org then '是' else '否' end as islssued FROM hr_laborcostcopy t  "
				+ " where t.wa_period = '" + date
				+ "'  and t.decimalmny !=0 and t.wa_org!='~' and t.wa_org is not null  and t.dr=0 "
				+ "GROUP BY t.wa_period,t.wa_org,t.data_source,t.cost_org,t.cost_dept,t.outlaytype,t.wa_type,"
				+ "t.vdef2,t.vdef3,t.vdef4,t.workercode,t.name,t.islssued having SUM(t.decimalmny)!=0";
		List<Map<String, String>> listCostVO = (List<Map<String, String>>) new BaseDAO().executeQuery(sql, new MapListProcessor());
		return listCostVO;
	}

	/**
	 * 根据财务组织编码查询主键
	 */
	public String getOrgcode(String code) throws Exception {
		String sql = "select pk_financeorg  from org_financeorg where dr=0 and code='" + code + "' and pk_group = '"
				+ pk_group + "' ";
		String orgid = (String) new BaseDAO().executeQuery(sql, new ColumnProcessor());
		return orgid;
	}

	/**
	 * 根据管理部门编码查询主键
	 */
	public String getMandept(String orgcode, String mandept) throws Exception {
		String sql = "select pk_dept from org_dept od, org_orgs o where od.pk_org=o.pk_org and o.code='" + orgcode
				+ "' and od.code='" + mandept + "' and od.pk_group = '" + pk_group + "' and od.dr=0 and o.dr=0";
		String orgid = (String) new BaseDAO().executeQuery(sql, new ColumnProcessor());
		return orgid;
	}

	/**
	 * 查询部门主键
	 * 
	 * @throws @throws DAOException
	 */
	public Map<String, String> getPk_dept() throws Exception {
		String sql = "SELECT pk_org,pk_dept FROM org_dept where name='其他-虚拟（财务成本归结）'  ";
		List<Map<String, String>> listMap = (List<Map<String, String>>) new BaseDAO().executeQuery(sql, new MapListProcessor());
		Map<String, String> tyMap = new HashMap<String, String>();
		if (listMap == null || listMap.size() <= 0)
			return tyMap;
		for (int i = 0; i < listMap.size(); i++) {
			Map<String, String> map = listMap.get(i);
			String pk_org = map.get("pk_org");
			String pk_dept = map.get("pk_dept");
			tyMap.put(pk_org, pk_dept);
		}
		return tyMap;
	}

	/**
	 * 查询费用归属类别主键
	 * 
	 * @throws @throws DAOException
	 */
	public Map<String, String> getOutlaytypeID() throws Exception {
		String sql = "SELECT bd.pk_defdoc,bd.name FROM bd_defdoc bd left join  bd_defdoclist  def "
				+ "on def.pk_defdoclist  =  bd.pk_defdoclist where def.name='费用归属类别';";
		List<Map<String, String>> listMap = (List<Map<String, String>>) new BaseDAO().executeQuery(sql, new MapListProcessor());
		Map<String, String> tyMap = new HashMap<String, String>();
		if (listMap == null || listMap.size() <= 0)
			return tyMap;
		for (int i = 0; i < listMap.size(); i++) {
			Map<String, String> map = listMap.get(i);
			String name = map.get("name");
			String pk_defdoc = map.get("pk_defdoc");
			tyMap.put(name, pk_defdoc);
		}
		return tyMap;
	}

	/**
	 * 查询费用归属类别备注
	 * 
	 * @throws @throws DAOException
	 */
	public Map<String, String> getOutlaytypeMemo() throws Exception {
		String sql = "select name,memo  from bd_defdoc where pk_defdoclist = (select pk_defdoclist from bd_defdoclist where code = 'HRFI01' and nvl(dr,0) = 0)  and enablestate = '2' and nvl(dr,0) = 0";
		List<Map<String, String>> listMap = (List<Map<String, String>>) new BaseDAO().executeQuery(sql, new MapListProcessor());
		Map<String, String> tyMap = new HashMap<String, String>();
		if (listMap == null || listMap.size() <= 0)
			return tyMap;
		for (int i = 0; i < listMap.size(); i++) {
			Map<String, String> map = listMap.get(i);
			String name = map.get("name");
			String memo = map.get("memo");
			tyMap.put(name, memo);
		}
		return tyMap;
	}

	/**
	 * 查询是否代发id
	 * 
	 * @throws @throws DAOException
	 */
	public Map<String, String> getIslssuedID() throws Exception {
		String sql = "SELECT bd.pk_defdoc,bd.name FROM bd_defdoc bd left join  bd_defdoclist "
				+ " def on def.pk_defdoclist  =  bd.pk_defdoclist where def.name='是否代发'; ";
		List<Map<String, String>> listMap = (List<Map<String, String>>) new BaseDAO().executeQuery(sql, new MapListProcessor());
		Map<String, String> tyMap = new HashMap<String, String>();
		if (listMap == null || listMap.size() <= 0)
			return tyMap;
		for (int i = 0; i < listMap.size(); i++) {
			Map<String, String> map = listMap.get(i);
			String name = map.get("name");
			String pk_defdoc = map.get("pk_defdoc");
			tyMap.put(name, pk_defdoc);
		}
		return tyMap;
	}

	/**
	 * 查询薪资类型id
	 * 
	 * @throws @throws DAOException
	 */
	public Map<String, String> getWa_typeid() throws Exception {
		String sql = "SELECT bd.pk_defdoc,bd.name FROM bd_defdoc bd left join  bd_defdoclist "
				+ " def on def.pk_defdoclist  =  bd.pk_defdoclist where def.name='薪资类型'; ";
		List<Map<String, String>> listMap = (List<Map<String, String>>) new BaseDAO().executeQuery(sql, new MapListProcessor());
		Map<String, String> tyMap = new HashMap<String, String>();
		if (listMap == null || listMap.size() <= 0)
			return tyMap;
		for (int i = 0; i < listMap.size(); i++) {
			Map<String, String> map = listMap.get(i);
			String name = map.get("name");
			String pk_defdoc = map.get("pk_defdoc");
			tyMap.put(name, pk_defdoc);
		}
		return tyMap;
	}

	/**
	 * 查询薪资类型备注
	 * 
	 * @throws @throws DAOException
	 */
	public Map<String, String> getWa_typeMemo() throws Exception {
		String sql = "SELECT bd.name,bd.memo FROM bd_defdoc bd left join  bd_defdoclist "
				+ " def on def.pk_defdoclist  =  bd.pk_defdoclist where def.name='薪资类型'; ";
		List<Map<String, String>> listMap = (List<Map<String, String>>) new BaseDAO().executeQuery(sql, new MapListProcessor());
		Map<String, String> tyMap = new HashMap<String, String>();
		if (listMap == null || listMap.size() <= 0)
			return tyMap;
		for (int i = 0; i < listMap.size(); i++) {
			Map<String, String> map = listMap.get(i);
			String name = map.get("name");
			String memo = map.get("memo");
			tyMap.put(name, memo);
		}
		return tyMap;
	}

	/**
	 * 查询薪资事项id
	 * 
	 * @throws @throws DAOException
	 */
	public Map<String, String> getXzsxID() throws Exception {
		String sql = "SELECT bd.pk_defdoc,bd.name FROM bd_defdoc bd left join  bd_defdoclist "
				+ " def on def.pk_defdoclist  =  bd.pk_defdoclist where def.name='薪资事项'; ";
		List<Map<String, String>> listMap = (List<Map<String, String>>) new BaseDAO().executeQuery(sql, new MapListProcessor());
		Map<String, String> tyMap = new HashMap<String, String>();
		if (listMap == null || listMap.size() <= 0)
			return tyMap;
		for (int i = 0; i < listMap.size(); i++) {
			Map<String, String> map = listMap.get(i);
			String name = map.get("name");
			String pk_defdoc = map.get("pk_defdoc");
			tyMap.put(name, pk_defdoc);
		}
		return tyMap;
	}

	/**
	 * 查询是否代收付id
	 * 
	 * @throws @throws DAOException
	 */
	public Map<String, String> getIspaymentID() throws Exception {
		String sql = "SELECT bd.pk_defdoc,bd.name FROM bd_defdoc bd left join  bd_defdoclist "
				+ " def on def.pk_defdoclist  =  bd.pk_defdoclist where def.name='是否代收付'; ";
		List<Map<String, String>> listMap = (List<Map<String, String>>) new BaseDAO().executeQuery(sql, new MapListProcessor());
		Map<String, String> tyMap = new HashMap<String, String>();
		if (listMap == null || listMap.size() <= 0)
			return tyMap;
		for (int i = 0; i < listMap.size(); i++) {
			Map<String, String> map = listMap.get(i);
			String name = map.get("name");
			String pk_defdoc = map.get("pk_defdoc");
			tyMap.put(name, pk_defdoc);
		}
		return tyMap;
	}

	/**
	 * 查询会计月份主键
	 * 
	 * @throws @throws DAOException
	 */
	public Map<String, String> getPk_accperiodmonth() throws Exception {
		String sql = "SELECT bd_accperiodmonth.yearmth,bd_accperiodmonth.pk_accperiodmonth FROM bd_accperiod "
				+ "INNER JOIN bd_accperiodmonth ON bd_accperiod.pk_accperiod = bd_accperiodmonth.pk_accperiod ";
		List<Map<String, String>> listMap = (List<Map<String, String>>) new BaseDAO().executeQuery(sql, new MapListProcessor());
		Map<String, String> tyMap = new HashMap<String, String>();
		if (listMap == null || listMap.size() <= 0)
			return tyMap;
		for (int i = 0; i < listMap.size(); i++) {
			Map<String, String> map = listMap.get(i);
			String yearmth = map.get("yearmth");
			String pk_accperiodmonth = map.get("pk_accperiodmonth");
			tyMap.put(yearmth, pk_accperiodmonth);
		}
		return tyMap;
	}

	/**
	 * 查询人员主键
	 * 
	 * @throws @throws DAOException
	 */
	public Map<String, String> getPsndocID() throws Exception {
		String sql = "select pk_psndoc,name from bd_psndoc  where pk_group = '0001A110000000000LO7'";
		List<Map<String, String>> listPsndocIDMap = (List<Map<String, String>>) new BaseDAO().executeQuery(sql, new MapListProcessor());
		Map<String, String> pndocIDMap = new HashMap<String, String>();
		if (listPsndocIDMap == null || listPsndocIDMap.size() <= 0)
			return pndocIDMap;
		for (int i = 0; i < listPsndocIDMap.size(); i++) {
			Map<String, String> map = listPsndocIDMap.get(i);
			String name = map.get("name");
			String pk_psndoc = map.get("pk_psndoc");
			pndocIDMap.put(name, pk_psndoc);
		}
		return pndocIDMap;
	}

	/**
	 * 查询用户id
	 * 
	 * @throws @throws DAOException
	 */
	public String getCuserid() throws Exception {
		String sql = "SELECT cuserid FROM sm_user where user_code='xtyh001' ";
		String cuserid = (String) new BaseDAO().executeQuery(sql, new ColumnProcessor());
		return cuserid;
	}

	/**
	 * 增值税税码税率
	 * 
	 * @throws @throws DAOException
	 */
	public String getPk_taxcode() throws Exception {
		String sql = "SELECT pk_taxcode FROM bd_taxcode where code='10' ";
		String pk_taxcode = (String) new BaseDAO().executeQuery(sql, new ColumnProcessor());
		return pk_taxcode;
	}

	public PfUserObject[] getUserObj() {
		if (userObjs == null) {
			userObjs = new PfUserObject[] { new PfUserObject() };
		}
		return userObjs;
	}

	/**
	 * 供应商id
	 * 
	 * @throws @throws DAOException
	 */
	public Map<String, String> getPk_supplier() throws Exception {
		String sql = "SELECT name,pk_supplier FROM bd_supplier ";
		List<Map<String, String>> listMap = (List<Map<String, String>>) new BaseDAO().executeQuery(sql, new MapListProcessor());
		Map<String, String> gysMap = new HashMap<String, String>();
		if (listMap == null || listMap.size() <= 0)
			return gysMap;
		for (int i = 0; i < listMap.size(); i++) {
			Map<String, String> map = listMap.get(i);
			String name = map.get("name");
			String pk_supplier = map.get("pk_supplier");
			gysMap.put(name, pk_supplier);
		}
		return gysMap;
	}

	/**
	 * 组织名称
	 * 
	 * @throws @throws DAOException
	 */
	public Map<String, String> getOrgName() throws Exception {
		String sql = "SELECT name,pk_org FROM org_orgs where dr=0";
		List<Map<String, String>> listMap = (List<Map<String, String>>) new BaseDAO().executeQuery(sql, new MapListProcessor());
		Map<String, String> tyMap = new HashMap<String, String>();
		if (listMap == null || listMap.size() <= 0)
			return tyMap;
		for (int i = 0; i < listMap.size(); i++) {
			Map<String, String> map = listMap.get(i);
			String pk_org = map.get("pk_org");
			String name = map.get("name");
			tyMap.put(pk_org, name);
		}
		return tyMap;
	}

	/**
	 * 档案TH03组织名称
	 * 
	 * @throws @throws DAOException
	 */
	public Map<String, List<String>> getOrgPk() throws Exception {
		Map<String, List<String>> mapl = new HashMap<String, List<String>>();
		String sql = "select name,memo from bd_defdoc where pk_defdoclist =( select pk_defdoclist from bd_defdoclist where code='TH03') ";
		List<Map<String, String>> listMap = (List<Map<String, String>>) new BaseDAO().executeQuery(sql, new MapListProcessor());
		List<String> orgList = null;
		if (listMap == null || listMap.size() <= 0)
			return mapl;
		for (int i = 0; i < listMap.size(); i++) {
			orgList = new ArrayList<String>();
			Map<String, String> codeMap = listMap.get(i);
			String name = codeMap.get("name");// 成本归属公司
			String memo = codeMap.get("memo");
			String[] smemo = memo.split(",");
			for (String org : smemo) {
				orgList.add(org);
			}
			mapl.put(name, orgList);
		}
		return mapl;
	}

	/**
	 * 财务组织版本
	 */
	private String getPkorgv(String pk) throws BusinessException {
		String sql = "select   pk_vid    from  org_financeorg_v  where   pk_financeorg    = ? and nvl(dr,0) = 0 ";
		SQLParameter parameter = new SQLParameter();
		parameter.addParam(pk);
		Object pk_vid = iuap.executeQuery(sql, parameter, new ColumnProcessor());
		return pk_vid != null ? pk_vid + "" : "";
	}

	/**
	 * 币种
	 * 
	 * @param pk_org
	 * @return
	 * @throws BusinessException
	 * @throws DAOException
	 */
	private String getcurrtype(String code) throws BusinessException {
		String sql = "select      pk_currtype   from  bd_currtype  where    code   = ? and nvl(dr,0) = 0 ";
		SQLParameter parameter = new SQLParameter();
		parameter.addParam(code);
		Object pk_currtype = iuap.executeQuery(sql, parameter, new ColumnProcessor());
		return pk_currtype != null ? pk_currtype + "" : "";
	}

	/**
	 * 排除薪资发放公司与成本归属公司相同、排除TH03对应关系的公司数据
	 * 
	 * @param listCostMap
	 * @param maps
	 * @param orgnamemap
	 * @return
	 */
	private List<Map<String, String>> getNewListCostMap(List<Map<String, String>> listCostMap,
			Map<String, List<String>> maps, Map<String, String> orgnamemap) {
		List<Map<String, String>> listCostMapNew = new LinkedList<Map<String, String>>();
		for (Map<String, String> map : listCostMap) {
			String wa_org = map.get("wa_org");
			String cost_org = map.get("cost_org");
			String cost_orgname = orgnamemap.get(cost_org);
			String wa_orgname = orgnamemap.get(wa_org);
			boolean flag = true;
			if (wa_orgname.equals(cost_orgname)) {
				flag = false;
			} else {
				if (maps != null && maps.size() > 0) {
					List<String> orgNameList = maps.get(cost_orgname);
					if (orgNameList != null && orgNameList.size() > 0) {
						if (orgNameList.contains(wa_orgname)) {
							flag = false;
						}
					}
				}
			}
			if (flag) {
				listCostMapNew.add(map);
			}
		}
		return listCostMapNew;
	}

	// 自定义档案
	private String getDefdocPKByName(String defdoclistcode, String name) throws Exception {
		if ("".equals(name)) {
			return null;
		}
		String sql = "select pk_defdoc from bd_defdoc where pk_defdoclist = (select pk_defdoclist from bd_defdoclist where code = '"
				+ defdoclistcode + "' and nvl(dr,0) = 0) and name  = '" + name + "' and enablestate = '2' and nvl(dr,0) = 0";
		String pk_defdoc = (String) iuap.executeQuery(sql, new ColumnProcessor());
		if (pk_defdoc == null) {
			throw new Exception("获取" + name + "信息失败,未找到与参数" + name + "有关的数据！");
		}
		return pk_defdoc;
	}

	// 客户
	private String getCustomerPKBynameOrPkorg(String name, String pkorg) throws Exception {
		if ("".equals(name)) {
			return null;
		}
		String sql = "select pk_customer from bd_customer where  ( name  = '" + name + "' or pk_financeorg  = '" + pkorg
				+ "' ) and enablestate = '2' and nvl(dr,0) = 0";
		String pk_customer = (String) iuap.executeQuery(sql, new ColumnProcessor());
		if (pk_customer == null) {
			throw new Exception("获取客户信息失败,未找到与参数" + name + "有关的数据！");
		}
		return pk_customer;
	}
	
	// 业务流程
	private String getBusitypePK(String code,String pk_group) throws Exception {
		String sql = "select pk_busitype from bd_busitype where  busicode = '"+code+"' and pk_group = '"+pk_group+"' and validity = '1' and nvl(dr,0) = 0";
		String pk_busitype = (String) iuap.executeQuery(sql, new ColumnProcessor());
		if (pk_busitype == null) {
			throw new Exception("获取业务流程信息失败,未找到与参数" + code + "有关的数据！");
		}
		return pk_busitype;
	}

	// 获取相差月份最后一天addMonth==0 当月 1 下月
	private String getMonthLastDate(Date date, int addMonth) {
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(date);
		calendar.add(Calendar.MONTH, addMonth);
		calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
		Date first = calendar.getTime();
		return convertDateToString(first, "yyyy-MM-dd");
	}

	// 日期格式转字符串
	private String convertDateToString(Date inDate, String dateFormat) {
		String resultValue = "";
		if (inDate == null) {
			return resultValue;
		}
		try {
			SimpleDateFormat df = new SimpleDateFormat(dateFormat == null ? "yyyy-MM-dd" : dateFormat, Locale.US);
			resultValue = df.format(inDate);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultValue;
	}

	// 字符串转日期格式
	private Date convertStringToDate(String inDate, String format) {
		if (inDate == null || inDate.isEmpty()) {
			return null;
		}
		SimpleDateFormat df;
		Date resultDate = null;
		try {
			df = new SimpleDateFormat(format == null ? "yyyy-MM-dd" : format, Locale.US);
			df.setLenient(false);
			resultDate = df.parse(inDate);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultDate;
	}

}
