package com.engine.htsc.trip.web;

import com.engine.common.util.ParamUtil;
import com.engine.htsc.trip.service.ReimbursementService;
import com.engine.htsc.trip.service.impl.ReimbursementServiceImpl;
import com.engine.htsc.trip.util.AjaxResult;
import com.engine.common.util.ServiceUtil;
import com.engine.htsc.trip.util.LogUtil;
import com.engine.htsc.trip.util.WeaverUtil;
import org.apache.commons.lang3.ArrayUtils;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.system.code.CodeBuild;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by qlk
 */
public class ReimbursementAction {
	public ReimbursementAction() {
	}

	private ReimbursementService getServices(HttpServletRequest request, HttpServletResponse response) {
		User user = HrmUserVarify.getUser(request, response);
		return ServiceUtil.getService(ReimbursementServiceImpl.class, user);
	}

  @GET
  @Path("/self/pay")
  @Produces({MediaType.APPLICATION_JSON})
  public AjaxResult<String> getSelfPayMark(@QueryParam("requestid") String requestId) {
    try {
      RecordSet rs = new RecordSet();
      String tableName = WeaverUtil.getTableNameByRequestId(requestId, rs);
      rs.executeQuery("select YWZFFYDBX from " + tableName + " where REQUESTID=?", requestId);
      String selfPayMark = "";
      if (rs.next()) {
        selfPayMark = Util.null2String(rs.getString("YWZFFYDBX"));
      }
      return AjaxResult.ok(selfPayMark);
    } catch (Exception e) {
      return AjaxResult.error(e.getMessage());
    }

  }

  @GET
  @Path("/bring/dt12/{formTable}/{requestIds}")
  @Produces({MediaType.APPLICATION_JSON})
  public AjaxResult<List<List<String>>> getDt12(
          @PathParam("formTable") String formTable,
          @PathParam("requestIds") String requestIds,
          @Context HttpServletRequest request,
          @Context HttpServletResponse response) {

		List<List<String>> details = this.getServices(request, response).bringDt12(formTable, requestIds);
		return AjaxResult.ok(details, "报销带出费用明细");
	}

	@GET
	@Path("/bring/dt13/{formTable}/{requestIds}")
	@Produces({MediaType.APPLICATION_JSON})
	public AjaxResult<List<List<String>>> getDt13(
			@PathParam("formTable") String formTable,
			@PathParam("requestIds") String requestIds,
			@Context HttpServletRequest request,
			@Context HttpServletResponse response) {

		List<List<String>> details = this.getServices(request, response).bringDt13(formTable, requestIds);
		return AjaxResult.ok(details, "报销带出行程明细");
	}

	@GET
	@Path("/bring/claimant/{formTable}/{requestIds}")
	@Produces({MediaType.APPLICATION_JSON})
	public AjaxResult<Map<String, Object>> getClaimant(
			@PathParam("formTable") String formTable,
			@PathParam("requestIds") String requestIds,
			@Context HttpServletRequest request,
			@Context HttpServletResponse response) {

		Map<String, Object> details = this.getServices(request, response).bringClaimant(formTable, requestIds);
		return AjaxResult.ok(details, "报销带出报销人");
	}

	@GET
	@Path("/check/leader/{ngr}")
	@Produces({MediaType.APPLICATION_JSON})
	public AjaxResult<Boolean> isLeader(
			@PathParam("ngr") String ngr,
			@Context HttpServletRequest request,
			@Context HttpServletResponse response) {

		boolean isLeader = this.getServices(request, response).checkLeader(ngr);
		return AjaxResult.ok(isLeader, "校验拟稿人是否为领导");
	}

	@GET
	@Path("/get/apInfo/{gllc}")
	@Produces({MediaType.APPLICATION_JSON})
	public AjaxResult<List<Map<String, Object>>> getAssociationProcessInfo(
			@PathParam("gllc") String lcs,
			@Context HttpServletRequest request,
			@Context HttpServletResponse response) {
		if ("".equals(lcs)) {
			return AjaxResult.failed();
		}
		List<Map<String, Object>> apInfo = this.getServices(request, response).getApInfo(lcs);
		return AjaxResult.ok(apInfo, "获取关联流程信息,返回关联流程的名称和已报销次数");
	}

	@GET
	@Path("/get/deptbrowserbtn/{ccr}/{lc}")
	@Produces({MediaType.APPLICATION_JSON})
	public AjaxResult<Map<String, Object>> getDbmBrowserBtn(
			@PathParam("ccr") String ccr,
			@PathParam("lc") String lc,
			@Context HttpServletRequest request,
			@Context HttpServletResponse response) {

		Map<String, Object> addObj = this.getServices(request, response).getBrowserBtn(ccr, lc);
		return AjaxResult.ok(addObj, "获取多部门浏览按钮addObj对象");
	}

	@GET
	@Path("/get/bankinfo/{ngr}/{bxr}")
	@Produces({MediaType.APPLICATION_JSON})
	public AjaxResult<Map<String, String>> getBankInfo(
			@PathParam("ngr") String ngr,
			@PathParam("bxr") String bxr,
			@Context HttpServletRequest request,
			@Context HttpServletResponse response) {

		Map<String, String> addObj = this.getServices(request, response).getBankInfo(ngr, bxr);
		return AjaxResult.ok(addObj, "获取员工的银行账号、开户行信息");
	}

	@GET
	@Path("/standard/trip/{traveler}/{destination}")
	@Produces({MediaType.APPLICATION_JSON})
	public AjaxResult<List<String>> standard(
			@PathParam("traveler") String traveler,
			@PathParam("destination") String destination,
			@Context HttpServletRequest request,
			@Context HttpServletResponse response) {

		List<String> travelStandard = this.getServices(request, response).getTravelStandardForSingle(traveler, destination);
		return AjaxResult.ok(travelStandard, "报销流程明细行差标");
	}

	@GET
	@Path("/get/gsxmbrowserbtn/{ccr}/{lc}")
	@Produces({MediaType.APPLICATION_JSON})
	public AjaxResult<Map<String, Object>> getGsxm(
			@PathParam("ccr") String ccr,
			@PathParam("lc") String lc,
			@Context HttpServletRequest request,
			@Context HttpServletResponse response) {

		Map<String, Object> addObj = this.getServices(request, response).getGsxmBrowserBtn(ccr, lc);
		return AjaxResult.ok(addObj, "获取关联出差申请的投行项目(报销明细表8)");
	}

	@GET
	@Path("/get/Accounting/{bxd}")
	@Produces({MediaType.APPLICATION_JSON})
	public AjaxResult<List<String>> getAccountingByLocation(
			@PathParam("bxd") String bxd,
			@Context HttpServletRequest request,
			@Context HttpServletResponse response) {

		List<String> accounting = this.getServices(request, response).getAccountingByLocation(bxd);
		return AjaxResult.ok(accounting, "报销地确认报销地费用会计");
	}

	@GET
	@Path("/get/Subsidy/{requestid}")
	@Produces({MediaType.APPLICATION_JSON})
	public AjaxResult<List<Map<String, String>>> getSubsidyStandard(
			@PathParam("requestid") String requestid,
			@Context HttpServletRequest request,
			@Context HttpServletResponse response) {

		List<Map<String, String>> res = null;
		try {
			res = this.getServices(request, response).getSubsidyStandard(requestid);
			return AjaxResult.ok(res, "获取出差补贴标准");
		} catch (Exception e) {
			return AjaxResult.error();
		}

	}

	@GET
	@Path("/get/bankinfomation/{hrmid}")
	@Produces({MediaType.APPLICATION_JSON})
	public AjaxResult<Map<String, String>> getBankInfo(
			@PathParam("hrmid") String hrmid,
			@Context HttpServletRequest request,
			@Context HttpServletResponse response
	) {
		Map<String, String> res;
		try {
			res = this.getServices(request, response).getBankInfoFormOADB(hrmid);
			return AjaxResult.ok(res);
		} catch (Exception e) {
			return AjaxResult.error();
		}
	}

	@GET
	@Path("/get/getRelatedInfo/{gllc}")
	@Produces({MediaType.APPLICATION_JSON})
	public AjaxResult<Map<String, List<String>>> getRelatedInfo(
			@PathParam("gllc") String gllc,
			@Context HttpServletRequest request,
			@Context HttpServletResponse response
	) {
		Map<String, List<String>> relatedInfo;
		try {
			relatedInfo = this.getServices(request, response).getRelatedInfo(gllc);
			return AjaxResult.ok(relatedInfo);
		} catch (Exception e) {
			return AjaxResult.error();
		}
	}

	@GET
	@Path("/doBudgerCommit")
	@Produces({MediaType.APPLICATION_JSON})
	public AjaxResult<Map<String, String>> doBudgerCommit(
			@QueryParam("requestid") String requsetid,
			@QueryParam("billStatus") String billStatus,
			@Context HttpServletRequest request,
			@Context HttpServletResponse response
	) {
		String res = "";
		Map<String, String> resMap = new HashMap<>();
		try {
			if ("".equals(requsetid)) {
				return AjaxResult.failed("requestid为空");
			}
			String[] reqids = requsetid.split(",");
			for (String reqid : reqids) {
				res = this.getServices(request,  response).doBudgetCommit(reqid, billStatus);
				resMap.put(reqid, res);
			}
			return AjaxResult.ok(resMap);
		} catch (Exception e) {
			return AjaxResult.failed("异常: [" + e + "]");
		}
	}

	@GET
	@Path("/doUpdateEnclosure")
	@Produces({MediaType.TEXT_PLAIN})
	public String updateEnclosure(
			@QueryParam("requestid") String requestid,
			@QueryParam("fj") String fj,
			@Context HttpServletRequest request,
			@Context HttpServletResponse response
	) {
		String res = "";
		try {
			LogUtil logUtil = new LogUtil();
			RecordSet rs = new RecordSet();
			String tablename = WeaverUtil.getTableNameByRequestId(requestid, rs);
			if (!"".equals(tablename)) {
				//原始附件类型
				String select_fj_sql = "select fj from " + tablename + " where requestid=" + requestid;
				logUtil.writeLog("doUpdateEnclosure fj_sql执行: [" + select_fj_sql + "]");
				String org_fj = "";
				rs.executeQuery(select_fj_sql);
				if (rs.next()) {
					org_fj = Util.null2String(rs.getString("fj"));
				}
				if (!"".equals(org_fj)) {
					String fjs = org_fj + "," + fj;
					List<String> collect = Arrays.stream(fjs.split(",")).distinct().collect(Collectors.toList());
					fj = String.join(",", collect);
				}

				String update_bx_sql = "update " + tablename + " set fj='" + fj + "' where requestid=" + requestid;
				logUtil.writeLog("doUpdateEnclosure update_bx_sql执行: [" + update_bx_sql + "]");
				rs.executeUpdate(update_bx_sql);
				return "更新表单成功";
			} else {
				return "流程无对应表单";
			}
		} catch (Exception e) {
			return "异常";
		}
	}

	@GET
	@Path("/generateLcbh")
	@Produces({MediaType.TEXT_PLAIN})
	public String generateLcbh(
			@QueryParam("formid") int formid,
			@QueryParam("requestid") int requestid,
			@Context HttpServletRequest request,
			@Context HttpServletResponse response
	) {
		LogUtil logUtil = new LogUtil();
		logUtil.writeLog("[formid]: " + formid + "  [requestid]: " + requestid);
		CodeBuild cbuild = new CodeBuild(formid);
		String flowCodeStr = cbuild.getFlowCodeStr(requestid, 1);
		logUtil.writeLog("[flowCodeStr]: [" + flowCodeStr + "]");
		return flowCodeStr;
	}

	@POST
	@Path("/updateBudgetMiddleTable")
	@Produces({MediaType.TEXT_PLAIN})
	public AjaxResult<Boolean> updateBudgetRecords(
			@Context HttpServletRequest request,
			@Context HttpServletResponse response
	) {
		Boolean isOk = this.getServices(request, response).doBudgetMiddleTable(ParamUtil.request2Map(request));
		return AjaxResult.ok(isOk);
	}

	@GET
	@Path("/monthlyAllowance")
	@Produces({MediaType.APPLICATION_JSON})
	public AjaxResult<List<Map<String, Object>>> monthlyAllowance(
			@QueryParam("date") String date,
			@Context HttpServletRequest request,
			@Context HttpServletResponse response
	) {
		List<Map<String, Object>> resp;
		try {
			Map<String, String> params = new HashMap<>();
			params.put("date", date);
			resp = this.getServices(request, response).monthlyAllowance(params);
			return AjaxResult.ok(resp);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.failed("接口异常,"+ e);
		}
	}

	@GET
	@Path("/monthlyAllowance/trip")
	@Produces({MediaType.APPLICATION_JSON})
	public AjaxResult<List<Map<String, Object>>> monthlyAllowance4Trip(
					@QueryParam("startDate") String startDate,
					@QueryParam("endDate") String endDate,
					@Context HttpServletRequest request,
					@Context HttpServletResponse response
	) {
		List<Map<String, Object>> resp;
		try {
			Map<String, String> params = new HashMap<>();
			params.put("startDate", startDate);
			params.put("endDate", endDate);
			resp = this.getServices(request, response).monthlyAllowance4BusinessTrip(params);
			return AjaxResult.ok(resp);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.failed("接口异常,"+ e);
		}
	}
}
