package com.engine.htxc.contract.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.util.ParamUtil;
import com.engine.common.util.ServiceUtil;
import com.engine.htxc.apprchalink.contract.service.ContractLinkService;
import com.engine.htxc.apprchalink.contract.service.impl.ContractLinkServiceImpl;
import com.engine.htxc.common.ParamValidException;
import com.engine.htxc.common.R;
import com.engine.htxc.common.dto.EcologyCommonResponseDTO;
import com.engine.htxc.commonutil.base.RequestJsonUtil;
import com.engine.htxc.contract.dto.*;
import com.engine.htxc.contract.service.ContractService;
import com.engine.htxc.contract.service.impl.ContractServiceImpl;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.interfaces.htsc.GlobatTools.JAVATools;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author K1810015
 * @version 1.0.0
 * @ClassName ContractAction.java
 * @createTime 2022年07月01日 09:56:00
 */
public class ContractAction {

    private static final Logger logger= LoggerFactory.getLogger(ContractAction.class);

    private ContractService getService() {
        return ServiceUtil.getService(ContractServiceImpl.class);
    }


    ContractLinkService contractLinkService=
            ServiceUtil.getService(ContractLinkServiceImpl.class);


    @POST
    @Path("/getdocmodeinfo")
    @Produces({MediaType.TEXT_PLAIN})
    public String getdocmodeinfo(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        try {
            User user = HrmUserVarify.getUser(request, response);
             JSONArray jsonarray= getService().getfileinfo(user, ParamUtil.request2Map(request));
            return JAVATools.Apiretrun("200",jsonarray);
        } catch (Exception e) {
            e.printStackTrace();
            return JAVATools.Apiretrun("400","error");
        }
    }

    @POST
    @Path("/getdocimagefileinfo")
    @Produces({MediaType.TEXT_PLAIN})
    public String getdocimagefileinfo(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        try {
            User user = HrmUserVarify.getUser(request, response);
            JSONArray jsonarray= getService().getdocimagefileinfo(user, ParamUtil.request2Map(request));
            return JAVATools.Apiretrun("200",jsonarray);
        } catch (Exception e) {
            e.printStackTrace();
            return JAVATools.Apiretrun("400","error");
        }
    }




    @POST
    @Path("/contractuser")
    @Produces({MediaType.TEXT_PLAIN})
    public String contractuser(@Context HttpServletRequest request, @Context HttpServletResponse response){
        JSONObject retjson = new JSONObject();
        try {
            User user = HrmUserVarify.getUser(request, response);
            JSONObject jsonobj = RequestJsonUtil.getRequestJsonObject(request);
            if(jsonobj==null || jsonobj.size()<=0){
                retjson.put("status", "400");
                retjson.put("error", "参数有误");
                return retjson.toJSONString();
            }
            JSONObject jsonObject = contractLinkService.getnextuser(jsonobj);
            if (jsonObject != null) {
                retjson.put("status", "200");
                retjson.put("data", jsonObject);
            } else {
                retjson.put("status", "400");
                retjson.put("error", "参数有误");
            }
            return retjson.toJSONString();
        }catch (Exception e){
            retjson.put("status", "400");
            retjson.put("error", "参数有误");
            return retjson.toJSONString();
        }
    }


    @POST
    @Path("/updatestatus")
    @Produces({MediaType.TEXT_PLAIN})
    public String updatestatus(@Context HttpServletRequest request, @Context HttpServletResponse response){
        JSONObject retjson = new JSONObject();
        try {
            User user = HrmUserVarify.getUser(request, response);
            boolean flag= getService().updateStatus(user,ParamUtil.request2Map(request));
           return JSONObject.toJSONString(R.ok(Util.null2String(flag)));
        }catch (Exception e){
            return JSONObject.toJSONString(R.error("msg"));
        }
    }

    /**
     * <p>分送节点下一步骤判断</p>
     * @title workflowNextJudge
     * @author K1810015
     * @updateTime 2022/8/26 17:42
     */
    @POST
    @Path("/workflowNextJudge")
    @Produces({MediaType.TEXT_PLAIN})
    public String workflowNextJudge(@Context HttpServletRequest request, @Context HttpServletResponse response){
        JSONObject retjson = new JSONObject();
        try {
            User user = HrmUserVarify.getUser(request, response);
            return getService().workflowNextJudge(user,ParamUtil.request2Map(request));

        }catch (Exception e){
            return JSONObject.toJSONString(R.error("msg"));
        }
    }


    @POST
    @Path("/updateContractenType")
    @Produces({MediaType.TEXT_PLAIN})
    public String updateContractenType(@Context HttpServletRequest request, @Context HttpServletResponse response){
        JSONObject retjson = new JSONObject();
        try {
            User user = HrmUserVarify.getUser(request, response);
            boolean flag= getService().updateContractenType(user,ParamUtil.request2Map(request));
            return JSONObject.toJSONString(R.ok(Util.null2String(flag)));
        }catch (Exception e){
            return JSONObject.toJSONString(R.error("msg"));
        }
    }


    @POST
    @Path("/startContractProcess")
    @Produces({MediaType.TEXT_PLAIN})
    public String startContractProcess(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        try {
            User user = HrmUserVarify.getUser(request, response);

            final String contractDataJson = Util.null2String(request.getParameter("contractData"));
            logger.info("传入合同流程数据：[{}]",contractDataJson);
            final ContractProcessDTO contractProcessDTO = JSON.parseObject(contractDataJson, ContractProcessDTO.class);
            new ContractProcessValidator(contractProcessDTO).validate();

            final ProcessInfoDTO processInfoDTO = getService().startContractProcess(user, contractProcessDTO);
            logger.info("返回数据：[{}]",processInfoDTO);

            if(processInfoDTO==null){
                return EcologyCommonResponseDTO.failJson("流程发起失败");
            }
            return EcologyCommonResponseDTO.successJson(processInfoDTO);
        }catch (ParamValidException | IllegalArgumentException e){
            logger.error("参数校验失败",e);
            return EcologyCommonResponseDTO.failJson("参数校验失败："+e.getMessage());
        }catch (Exception e){
            logger.error("发起合同流程失败",e);
        }
        return EcologyCommonResponseDTO.failJson("流程发起失败");
    }



    /**
     * 保存合同起草的开户行等信息到对手方明细表中
     * @param request
     * @param response
     * @return
     */
    @POST
    @Path("/saveBankInfoToCounterparty")
    @Produces({MediaType.TEXT_PLAIN})
    public String saveBankInfoToCounterparty(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        try {
            Map<String, Object> paramMap = ParamUtil.request2Map(request);
            String dataString = paramMap.get("data")==null?"":paramMap.get("data").toString();
            List<Map> dataList =   JSON.parseArray(dataString,Map.class);
            Map<String, Object> data = Maps.newHashMap();
            data.put("data",dataList);
            return JSON.toJSONString(getService().saveBankInfoToCounterparty(data));
        }catch (Exception e){
            logger.error("保存异常",e);
        }
        return JAVATools.Apiretrun("-1", "保存合同起草的开户行等信息到对手方明细表中失败");
    }


    /**
     * <p>合同审批流程保存之后关联建模</p>
     * @title linkMode
     * @author K1810015
     * @updateTime 2022/8/31 19:54
     */
    @POST
    @Path("/linkmode")
    @Produces({MediaType.TEXT_PLAIN})
    public String linkmode(@Context HttpServletRequest request, @Context HttpServletResponse response){
        JSONObject retjson = new JSONObject();
        try {
            User user = HrmUserVarify.getUser(request, response);
            return getService().linkMode(user,ParamUtil.request2Map(request));

        }catch (Exception e){
            return JSONObject.toJSONString(R.error("msg"));
        }
    }

    /**
     * <p>删除流程关联建模</p>
     * @title linkMode
     * @author K1810015
     * @updateTime 2022/8/31 19:54
     */
    @POST
    @Path("/unlinkmode")
    @Produces({MediaType.TEXT_PLAIN})
    public String unlinkmode(@Context HttpServletRequest request, @Context HttpServletResponse response){
        JSONObject retjson = new JSONObject();
        try {
            User user = HrmUserVarify.getUser(request, response);
            return getService().unLinkMode(user,ParamUtil.request2Map(request));

        }catch (Exception e){
            return JSONObject.toJSONString(R.error("msg"));
        }
    }
    /**
     * <p>引导页面</p>
     * @title guidePages
     * @author K1810015
     * @updateTime 2022/9/1 15:28
     */
    @POST
    @Path("/guidePages")
    @Produces({MediaType.TEXT_PLAIN})
    public String guidePages(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        JSONObject retjson = new JSONObject();
        try {
            User user = HrmUserVarify.getUser(request, response);
            return getService().guidePages(user,ParamUtil.request2Map(request));

        }catch (Exception e){
            return JSONObject.toJSONString(R.error("msg"));
        }
    }

    /**
     * <p>引导页面</p>
     * @title guidePages
     * @author K1810015
     * @updateTime 2022/9/1 15:28
     */
    @POST
    @Path("/todosealname")
    @Produces({MediaType.TEXT_PLAIN})
    public String todosealname(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        JSONObject retjson = new JSONObject();
        try {
            User user = HrmUserVarify.getUser(request, response);
            return getService().todosealname(user,ParamUtil.request2Map(request));

        }catch (Exception e){
            return JSONObject.toJSONString(R.error("msg"));
        }
    }

}
