package weaver.interfaces.htsc.cus;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.htsc.trip.service.impl.ReimbursementServiceImpl;
import com.engine.htsc.trip.util.LogUtil;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.RequestManager;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * author: Weaver_nj_qlk
 * description: 预算接口调用
 * 发起：
 * 不调用
 * 会计节点：节点后
 * 预占 3
 * 非会计退回：经过会计节点后的退回
 * 回退 2
 * 办结：节点前
 * 实占 1
 */
public class BudgetCommitInvokeAction implements Action {

	static DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");

	//预算状态
	private String billStatus;

	private final LogUtil logUtil = new LogUtil();

	@Override
	public String execute(RequestInfo requestInfo) {
		JSONObject params = new JSONObject();
		HTUtil htUtil = new HTUtil();
		RecordSet rs = new RecordSet();
		RequestManager requestManager = requestInfo.getRequestManager();

		try {
			ResourceComInfo rc = new ResourceComInfo();
			DepartmentComInfo dc = new DepartmentComInfo();
			// 主表
			String tableName = requestManager.getBillTableName();
			// 明细表
			String dt8TableName = tableName + "_dt8";
			String dt9TableName = tableName + "_dt9";
			String requestId = requestInfo.getRequestid();
			logUtil.writeLog("=====预算接口调用execute,requestId: " + requestId + "====");
			String main_sql = "select t1.lcbh,t1.ngr,t1.id,t2.requestname from " + tableName + " t1\n" +
					" left join workflow_requestbase t2\n" +
					" on t1.requestid=t2.requestid\n" +
					" where t1.requestid=" + requestId;
			logUtil.writeLog("执行main_sql=== " + main_sql);
			rs.execute(main_sql);
			String lcbh = "";
			String requestname = "";
			String ngr = "";
			String mainId = "";
			if (rs.next()) {
				lcbh = Util.null2String(rs.getString("lcbh"));
				requestname = Util.null2String(rs.getString("requestname"));
				ngr = Util.null2String(rs.getString("ngr"));
				mainId = Util.null2String(rs.getString("id"));
			}
			params.put("billnum", requestId);
			params.put("billname", lcbh);
			params.put("billstatus", billStatus);
			params.put("billtitle", requestname);
			params.put("personName", rc.getLastname(ngr));
			params.put("bizdate", df.format(LocalDateTime.now()));
			logUtil.writeLog("参数1" + params);
			//list
			JSONArray levelObjList = new JSONArray();
			JSONObject levelObj;
			String dt8_sql = "select fycdr,yskm,ccsqlc from " + dt8TableName + " where mainid=" + mainId;
			logUtil.writeLog("执行dt8_sql===" + dt8_sql);
			rs.execute(dt8_sql);
			int i = 1;
			String km = "";
			String ccsqlc = "";
			while (rs.next()) {
				levelObj = new JSONObject();
				String fycdr = Util.null2String(rs.getString("fycdr"));
				levelObj.put("employeeNum", fycdr);
				levelObj.put("deptNum", Util.null2String(dc.getDepartmentCode(rc.getDepartmentID(fycdr))));
				levelObj.put("bgitem", "86010503");
				levelObj.put("bgElement", "0101");
				levelObj.put("billEntryID", UUID.randomUUID().toString() + "#" + i);
				km = Util.null2String(rs.getString("yskm"));
				ccsqlc = Util.null2String(rs.getString("ccsqlc"));
				levelObj.put("itemEntryNum", km);
				//科目对应金额
				levelObj.putAll(getKjKmCharges(km, dt9TableName, ccsqlc, mainId));
				levelObjList.add(levelObj);
				i++;
			}
			//科目为空，直接返回
			if ("".equals(km)) {
				return SUCCESS;
			}
			params.put("list", levelObjList);
			logUtil.writeLog("[params]: [" + params + "]");
			Map<String, Object> dataMap = new HashMap<>();
			dataMap.put("data", params);
			//预算接口调用
			String resp = htUtil.budgetCommit(dataMap);
			logUtil.writeLog("[预算接口response]: 【" + resp + "】");
			if (!"F1001".equals(resp)) {
				requestManager.setMessagecontent("预算接口执行失败!");
				requestManager.setMessageid("5000");
				return FAILURE_AND_CONTINUE;
			} else {
				//更新预算中间表
				Map<String, Object> reqMap = new HashMap<>();
				ReimbursementServiceImpl reimbursementService = new ReimbursementServiceImpl();
				reqMap.put("lcbm", lcbh);
				reqMap.put("billStatus", billStatus);
				Boolean isUpdate = reimbursementService.doBudgetMiddleTable(reqMap);
				if (isUpdate) {
					return SUCCESS;
				} else {
					requestManager.setMessagecontent("节点后附加操作更新预算表失败!");
					requestManager.setMessageid("5000");
					return FAILURE_AND_CONTINUE;
				}
			}
		} catch (Exception e) {
			requestManager.setMessagecontent("节点后附加操作接口调用异常!" + e);
			requestManager.setMessageid("5000");
			return FAILURE_AND_CONTINUE;
		}

	}

	public String getBillStatus() {
		return billStatus;
	}

	public void setBillStatus(String billStatus) {
		this.billStatus = billStatus;
	}

	/**
	 * 明细表14取科目对应数据
	 * 金额,是否超标,实际金额,标准金额,不含税价金额,税金
	 * @param km 科目code
	 * @param dt9TableName 明细表9
	 * @param ccsqlc 出差申请流程
	 * @param mainId 流程id
	 * @return map
	 */
	public static JSONObject getKjKmCharges(String km, String dt9TableName, String ccsqlc, String mainId) {
		RecordSet rs = new RecordSet();
		LogUtil logUtil = new LogUtil();
		logUtil.writeLog("[执行getKjKmCharges方法]");
		JSONObject subParam = new JSONObject();
		String dt9_sql = "select qzzsbhsje as zsbhs,zssj,sfcb,zscb,lkysbhsje as lkysbhs,lkyssj,qt from "+dt9TableName+" where mainid="+mainId+" and ccsqlc=" + ccsqlc;
		rs.execute(dt9_sql);
		logUtil.writeLog("[执行dt9_sql]: [" + dt9_sql + "]");
		if (rs.next()) {
			logUtil.writeLog("[km]: [" + km + "]");
			if ("8601050302".equals(km)) { // 其他
				String qt = Util.null2String(rs.getString("qt"), "0.00");
				subParam.put("amount", qt); // 金额
				subParam.put("overweight", "否"); // 是否超标
				subParam.put("actualAmount", qt); // 实际金额
				subParam.put("standardAmount", "0.00"); // 标准金额
				subParam.put("notaxAmount", qt); // 不含价税金额
				subParam.put("taxAmount", "0.00"); //税金

			} else if ("8601050301".equals(km)) { // 交通费 (默认)
				String lkysbhs = Util.null2String(rs.getString("lkysbhs"), "0.00");
				String lkyssj = Util.null2String(rs.getString("lkyssj"), "0.00");
				subParam.put("amount", lkyssj);
				subParam.put("overweight", "否");
				subParam.put("actualAmount", lkyssj);
				subParam.put("standardAmount", "0.00");
				subParam.put("notaxAmount", lkysbhs);
				subParam.put("taxAmount", "0.00");

			} else if ("8601050303".equals(km)) { // 住宿费
				String zsbhs = Util.null2String(rs.getString("zsbhs"), "0.00");
				String zssj = Util.null2String(rs.getString("zssj"), "0.00");
				String zscb = Util.null2String(rs.getString("zscb"), "0.00"); //住宿标准值
				subParam.put("amount", zssj);
				subParam.put("overweight", Util.null2String(rs.getString("sfcb"), "否"));
				subParam.put("actualAmount", zssj);
				subParam.put("standardAmount", zscb);
				subParam.put("notaxAmount", zsbhs);
				subParam.put("taxAmount", "0.00");

			} else {
				subParam.put("amount", "0.00");
				subParam.put("overweight", "否");
				subParam.put("actualAmount", "0.00");
				subParam.put("standardAmount", "0.00");
				subParam.put("notaxAmount", "0.00");
				subParam.put("taxAmount", "0.00");
			}

		}

		logUtil.writeLog("===getKjKmCharges===, subParam: " + subParam);
		return subParam;
	}

	private static double str2Double(String data) {
		if ("".equals(data)) {
			data = "0.00";
		}
		return Double.parseDouble(data);
	}


}
