package com.engine.htsc.payment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.api.htsc.businessMethod.SubUnionBizUtil;
import com.engine.htsc.payment.pojo.BudgetDTO;
import com.engine.htsc.payment.pojo.BudgetList;
import com.engine.htsc.payment.service.BudgetStrategy;
import com.engine.htsc.payment.util.BizUtils;
import com.engine.htsc.payment.util.PayUtil;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.resource.ResourceComInfo;

import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.UUID;

/**
 * 总部通用付款预算参数构建
 */
public class HeadPaymentBudgetStrategy implements BudgetStrategy<BudgetDTO> {

	@Override
	public BudgetDTO buildNewBudgetParamFromWorkflowDB(String requestNo, String billStatus) throws Exception {
		RecordSet rs = new RecordSet();
		BizUtils bizUtils = new BizUtils();
		DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		ResourceComInfo resourceComInfo = new ResourceComInfo();
		DepartmentComInfo departmentComInfo = new DepartmentComInfo();
		String table = bizUtils.getTableNameByRequestId(requestNo);
		String sql = "select t1.ID,t1.REQUESTID,t1.LCBH,t1.NGR,t1.FKXX,t2.REQUESTNAME from " + table + " t1\n" +
				"left join WORKFLOW_REQUESTBASE t2\n" +
				"on t1.REQUESTID=t2.REQUESTID\n" +
				"where t1.REQUESTID=?";
		rs.executeQuery(sql, requestNo);
		BudgetDTO budgetDTO = new BudgetDTO();
		String bz = "0"; // 0 本币
		String detailId = "";
		if (rs.next()) {
			budgetDTO.setBillNum(rs.getString("REQUESTID"));
			budgetDTO.setBizDate(df.format(LocalDateTime.now()));
			budgetDTO.setBillStatus(billStatus);
			budgetDTO.setBillName(rs.getString("LCBH"));
			budgetDTO.setBillTitle(rs.getString("REQUESTNAME"));
			budgetDTO.setPesonName(resourceComInfo.getLastname(rs.getString("NGR")));
			bz = rs.getString("FKXX");
			detailId = rs.getString("ID");
		}
		boolean itFlag = false;
		if (budgetDTO.getBillName().contains("总部IT付款")) {
			itFlag = !BizUtils.whetherItOrTy(requestNo); //判断是否为it类付款
		}
		String queryBudgetList;
		rs.writeLog("requestId:"+requestNo+" 是否IT付款:"+itFlag);
		if(itFlag) {
			queryBudgetList = queryITBudgetSqlFromDetailTable(bz, table, detailId);
		}else {
			queryBudgetList = queryBudgetSqlFromDetailTable(bz, table, detailId);
		}
		rs.writeLog("requestId:"+requestNo+" 是否IT付款:"+itFlag+" 查询付款明细sql:"+queryBudgetList);
		String uuid = UUID.randomUUID().toString();
		int i = 1;
		ArrayList<BudgetList> list = new ArrayList<>();
		rs.executeQuery(queryBudgetList);
		while (rs.next()) {
			BudgetList budgetList = new BudgetList();
			String fysjcdbm = rs.getString("FYSJCDBM");
			String yskm = rs.getString("YSKM");
			String superBudgetCode = PayUtil.getSuperBudgetCode(yskm);
			budgetList.setDeptNum(departmentComInfo.getDepartmentCode(fysjcdbm));
			if(itFlag) {
				rs.writeLog("requestId:"+requestNo+" 是否IT付款:"+itFlag+" 付款明细projectcode:"+rs.getString("PROJECTCODE"));
				budgetList.setBgItem(rs.getString("PROJECTCODE"));
				budgetList.setBgITElement(rs.getString("PROJECTCODE"));
			}else {
				budgetList.setBgItem(superBudgetCode);
				budgetList.setBgITElement(superBudgetCode);
			}
			budgetList.setBgElement("0101"); //default
			budgetList.setBillEntryID(uuid + "#" + i);
			budgetList.setItemEntryNum(yskm);

			if ("0".equals(bz)) {
				//明细8
				String jshjje = Util.null2String(rs.getString("JSHJJE"));
				String bhsje = Util.null2String(rs.getString("BHSJE"));
				String sj = Util.null2String(rs.getString("SJ"));
				jshjje = new DecimalFormat("0.00").format(NumberUtils.toDouble(jshjje));
				budgetList.setAmount(jshjje);
				budgetList.setNoTaxAmount(bhsje);
				budgetList.setTaxAmount(sj);
				if (!itFlag) {
					// 非IT付款的情况下,价税合计不为0 不含税为0的情况下 不含税金额改成和价税合计一样的金额
					if (StringUtils.isNotBlank(jshjje) && !"0".equals(jshjje) && !"0.00".equals(jshjje) && (
							StringUtils.isBlank(bhsje) || "0".equals(bhsje) || "0.00".equals(bhsje))) {
						// 不含价税金额
						budgetList.setNoTaxAmount(jshjje);
					}
				}
			} else {
				String rmbje = Util.null2String(rs.getString("rmbje"));
				rmbje = new DecimalFormat("0.00").format(NumberUtils.toDouble(rmbje));
				budgetList.setAmount(rmbje);
				budgetList.setNoTaxAmount(rmbje);
				budgetList.setTaxAmount("0.00");
			}
			i++;
			list.add(budgetList);
		}
		budgetDTO.setList(list); //分录汇总
		//HTO-11640查询主表，当付款流程中字段“先付款后发票”选项为“是”时，接口字段“SFYFP”传值“Y”，
		// “先付款后发票”选项为“否”时，接口字段“SFYFP”传值“N”；
		//针对分支机构通用付款,总部通用付款，总部it付款，总部工会付款,托收业务付款，资管通用付款，紫金通用付款
		if(SubUnionBizUtil.equalsTableName(requestNo, "fzjgtyfk")||SubUnionBizUtil.equalsTableName(requestNo, "zbtyfk")
		||SubUnionBizUtil.equalsTableName(requestNo, "zbghfk")||SubUnionBizUtil.equalsTableName(requestNo, "zbitfk")
				||SubUnionBizUtil.equalsTableName(requestNo, "fyft") || SubUnionBizUtil.equalsTableName(requestNo, "zgtyfk")
		||SubUnionBizUtil.equalsTableName(requestNo, "zjtyfk") ||SubUnionBizUtil.equalsTableName(requestNo, "zgstyfk")){
			RecordSet sqlFindYfp = new RecordSet();
			String sqlNew = "select sfxfkhtgfp from "+table+" where requestid = "+requestNo;
			sqlFindYfp.execute(sqlNew);
			if (sqlFindYfp.next()){
				String sfxfkhtgfp = Util.null2String(sqlFindYfp.getString("sfxfkhtgfp"));
				if ("0".equals(sfxfkhtgfp)){
					//当付款流程中字段“先付款后发票”选项为“是”时，接口字段“SFYFP”传值“Y”
					budgetDTO.setSFYFP("Y");
				}else{
					//“先付款后发票”选项为“否”时，接口字段“SFYFP”传值“N”；
					budgetDTO.setSFYFP("N");
				}
			}
		}

		return budgetDTO;
	}

	@Override
	public String queryBudgetSqlFromDetailTable(String bz, String table, String detailId) {
		String sql = "";
		if ("0".equals(bz)) {
			//dt8
			sql = "select FYCDBMFZR,FYSJCDBM,YSKM,BHSJE,SJ,JSHJJE from " + table + "_DT8 where MAINID=" + detailId;
		} else if ("1".equals(bz)) {
			//dt9
			sql = "select FYCDBMFZR,FYSJCDBM,YSKM,RMBJE from " + table + "_DT9 where MAINID=" + detailId;
		}
		return sql;
	}

	/**
	 *  IT付款明细
	 * @param bz
	 * @param table
	 * @param detailId
	 * @return
	 */
	public String queryITBudgetSqlFromDetailTable(String bz, String table, String detailId) {
		String sql = "";
		if ("0".equals(bz)) {
			//dt8
			sql = "select FYCDBMFZR,FYSJCDBM,YSKM,BHSJE,SJ,JSHJJE,projectcode from " + table + "_DT8 where MAINID=" + detailId;
		} else if ("1".equals(bz)) {
			//dt9
			sql = "select FYCDBMFZR,FYSJCDBM,YSKM,RMBJE,projectcode from " + table + "_DT9 where MAINID=" + detailId;
		}
		return sql;
	}

	@Override
	public BudgetDTO getLastBudgetParamFromModeDB(String requestNo, String itFlag) {
		RecordSet rs = new RecordSet();
		rs.executeQuery("select YSQQCS from UF_YSJLB where ITFLAG=? and LCID=?", itFlag, requestNo);
		String lastOperateBudgetParam = "";
		if (rs.next()) {
			lastOperateBudgetParam = Util.null2String(rs.getString("YSQQCS"));
		}
		//decode
		BudgetDTO budgetDTO = null;
		try {
			budgetDTO = JSONObject.parseObject(lastOperateBudgetParam, BudgetDTO.class);
		} catch (Exception e) {
			new BizUtils().log(e.getMessage());
		}
		return budgetDTO;
	}
}
