package com.engine.htsc.cgrwd.web;

import com.alibaba.fastjson.JSONObject;
import com.engine.common.util.ParamUtil;
import com.engine.common.util.ServiceUtil;
import com.engine.htsc.cgrwd.service.CgrwdService;
import com.engine.htsc.cgrwd.service.impl.CgrwdServiceImpl;
import com.engine.htsc.payment.util.PayUtil;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class CgrwdAction {

    public CgrwdService getService(HttpServletRequest request, HttpServletResponse response){
        return  (CgrwdService) ServiceUtil.getService(CgrwdServiceImpl.class);
    }

    @GET
    @Path("/getimagefileid")
    @Produces({MediaType.TEXT_PLAIN})
    public String getImageFileid(@Context HttpServletRequest request, @Context HttpServletResponse response){
        Map<String,Object> apidatas = new HashMap<String,Object>();
        try {
            Map<String,Object> param = ParamUtil.request2Map(request);
            RecordSet rs = new RecordSet();
            String docids = Util.null2String(param.get("docids"));
            String imagefileids = "" ;
            if(!"".equals(docids)){
                String sql = " select imagefileid from docimagefile where docid in("+docids+") ";
                rs.execute(sql);
                while(rs.next()){
                    String imagefileid = Util.null2String(rs.getString("imagefileid")) ;
                    imagefileids += imagefileids==""? imagefileid : ","+imagefileid ;
                }
            }
            apidatas.put("imagefileids", imagefileids);
            apidatas.put("api_status", true);
            apidatas.put("api_errormsg", "");
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSONObject.toJSONString(apidatas);
    }



    @GET
    @Path("/getCgrwdProjectInfo")
    @Produces({MediaType.TEXT_PLAIN})
    public String getCgrwdProjectInfo(@Context HttpServletRequest request, @Context HttpServletResponse response){
        Map<String,Object> apidatas = new HashMap<String,Object>();
        try {
            User user = HrmUserVarify.getUser( request, response );
            Map<String,Object> param = ParamUtil.request2Map(request);
            apidatas = getService(request,response).getCgrwdProjectInfo(user,param);
            apidatas.put("api_status", true);
            apidatas.put("api_errormsg", "");
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSONObject.toJSONString(apidatas);
    }


    @GET
    @Path("/createRequestMark")
    @Produces({MediaType.TEXT_PLAIN})
    public String createRequestMark(@Context HttpServletRequest request, @Context HttpServletResponse response){

        Map<String,Object> apidatas = new HashMap<String,Object>();

        ModeRightInfo modeRightInfo = new ModeRightInfo();
        RecordSet rs = new RecordSet();
        int workFlowId = Util.getIntValue(request.getParameter("workflowid"));
        int formModeId = PayUtil.getFormModeIdByCubeName("uf_fklcbh");

        try{
            String sql = "select WORKFLOWNAME,UNNUMBER from workflow_base where ID=?";
            rs.executeQuery(sql, workFlowId);
            String name = "";
            if (rs.next()) {
                name = rs.getString("WORKFLOWNAME");
            }
            if (!"".equals(name)) {
                String unNumber = PayUtil.getUnNumberByWorkFlowId(workFlowId);
                LocalDateTime now = LocalDateTime.now();
                String yM = now.format(DateTimeFormatter.ofPattern("yyyyMM"));

                synchronized (this) {

                    StringBuilder mark = new StringBuilder(); //流程编码
                    rs.executeQuery(" select id,lsh,MODEUUID from uf_fklcbh where ny = '" + yM + "' and LCLX='" + unNumber + "'");
                    if (rs.next()) {
                        //更新
                        int num = Util.getIntValue(rs.getString("lsh")) + 1;
                        int id = Util.getIntValue(rs.getString("id"));
                        String updateSql = "update uf_fklcbh set lsh=? where id=?";
                        rs.executeUpdate(updateSql, num, id);
                        mark = new StringBuilder(num + "");
                        while (mark.length() < 6) {
                            mark.insert(0, "0");
                        }
                        mark = new StringBuilder(name + now.format(DateTimeFormatter.ofPattern("yyyyMM")) + mark);
                    } else {
                        String  modeUuid = UUID.randomUUID().toString();
                        String userId = Util.null2String(request.getParameter("f_weaver_belongto_userid"));
                        String userType = Util.null2String(request.getParameter("f_weaver_belongto_usertype"));
                        String createDate = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                        String createTime = now.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
                        //插入
                        String insertSql =  " insert into uf_fklcbh" +
                                " (FORMMODEID,MODEDATACREATER,MODEDATACREATERTYPE,MODEDATACREATEDATE,MODEDATACREATETIME,MODEUUID,LSH,NY,LCLX) \n" +
                                " values(?,?,?,?,?,?,?,?,?)";

                        rs.executeUpdate(insertSql, formModeId, userId, userType, createDate, createTime, modeUuid, "1", yM, unNumber);
                        mark = new StringBuilder(name + now.format(DateTimeFormatter.ofPattern("yyyyMM")) + "000001");

                        //权限重构
                        int dataId = PayUtil.getDataIdByUUID(modeUuid);
                        modeRightInfo.editModeDataShare(1, formModeId, dataId);
                    }

                    apidatas.put("value",mark.toString());
                    apidatas.put("api_status", true);
                    apidatas.put("api_errormsg", "");
                }
            }else{
                apidatas.put("api_status", false);
                apidatas.put("api_errormsg", "流程名称为空");
            }
        }catch (Exception e){
            e.printStackTrace();

            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", e.getMessage());
        }

        return JSONObject.toJSONString(apidatas);
    }

}


