package weaver.interfaces.htsc.tgpt;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import weaver.conn.RecordSet;
import weaver.formmode.customjavacode.AbstractModeExpandJavaCodeNew;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.soa.workflow.request.RequestInfo;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Title: ecology-9
 * @Company: 泛微软件
 * @author: K1810039
 * @version: 1.0
 * @CreateDate: 2022-08-19
 * @Description: 这是一个尽调活动保存的时候促发日程的接口,这个接口只创建，活动创建人的日程
 * @ModifyLog:
 **/
public class CreateCleander extends AbstractModeExpandJavaCodeNew {
    /**
     * 执行模块扩展动作
     * @param param
     *  param包含(但不限于)以下数据
     *  user 当前用户
     *  importtype 导入方式(仅在批量导入的接口动作会传输) 1 追加，2覆盖,3更新，获取方式(int)param.get("importtype")
     *  导入链接中拼接的特殊参数(仅在批量导入的接口动作会传输)，比如a=1，可通过param.get("a")获取参数值
     *  页面链接拼接的参数，比如b=2,可以通过param.get("b")来获取参数
     * @return
     */
    public Map<String, String> doModeExpand(Map<String, Object> param) {

        Map<String, String> result = new HashMap<String, String>();

        RecordSet rs = new RecordSet();
        RecordSet rs2 =  new RecordSet();
        RecordSet perRs = new RecordSet();
        RecordSet inRs = new RecordSet();
        ArrayList<String> dtList = new ArrayList<>();
        ArrayList<String> nbList = new ArrayList<>();
        ArrayList<String> cyList = new ArrayList<>();
        HashMap<String,String> map = new HashMap<String,String>();
        HashMap<String,Object> paramMap = new HashMap<String,Object>();
        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("HH:mm:ss");
        PropBean pb = new PropBean();
        String tgpt_url = pb.getPropName("tgpt_url");
        String tgpt_createRcModeid = pb.getPropName("tgpt_createRcModeid");
        new Thread(){
            @Override
            public void run() {
                try {
                    User user = (User)param.get("user");
                    int billid = -1;//数据id
                    int modeid = -1;//模块id
                    RequestInfo requestInfo = (RequestInfo)param.get("RequestInfo");
                    if(requestInfo!=null){
                        billid = Util.getIntValue(requestInfo.getRequestid());
                        modeid = Util.getIntValue(requestInfo.getWorkflowid());
                        if(billid>0&&modeid>0){
                            //------请在下面编写业务逻辑代码------
                            String mainsql = "select * from uf_jdhd where id = "+ billid;
                            rs.execute(mainsql);
                            rs.next();
                            String hdksrq = rs.getString("hdksrq");
                            String hdjsrq = rs.getString("hdjsrq");
                            String rctsr = rs.getString("rctsr");
                            String creater = rs.getString("modedatacreater");
                            String hdmc = rs.getString("hdmc");
                            if(StringUtils.isNotBlank(rctsr)){
                                ArrayList<String> rctsrList = new ArrayList<String>();
                                String rctsrSql = "SELECT  modeuuid  FROM ( SELECT modeuuid, glnbry FROM uf_qtryxxgl UNION SELECT modeuuid, glnbry FROM uf_djgxxgl )   WHERE glnbry in ("+rctsr+")";
                                rs.execute(rctsrSql);
                                while(rs.next()){
                                    rctsrList.add(rs.getString("modeuuid"));
                                }

                                rctsr = StringUtils.join(rctsrList,',');
                                //1.判断是不是推送的人员是不是内部人员，判断选择人员是不是活动参与人
                                String dtSql = "select * from uf_jdhd_dt1 where mainid =  " + billid;
                                rs.execute(dtSql);
                                while(rs.next()){
                                    dtList.add(rs.getString("xm"));
                                }
                                String nbSql =  "select modeuuid,glnbry from  uf_qtryxxgl where glnbry is not null union  select modeuuid,glnbry from  uf_djgxxgl";
                                rs.execute(nbSql);
                                while(rs.next()){
                                    nbList.add(rs.getString("modeuuid"));
                                    String hrmSql = "select * from hrmresource where id = " + rs.getString("glnbry");
                                    rs2.execute(hrmSql);
                                    rs2.next();
                                    //为发送请求提供参数
                                    map.put(rs.getString("modeuuid"),rs2.getString("workcode"));
                                }

                                String hrmSql = "select * from hrmresource where id = " + creater;
                                rs2.execute(hrmSql);
                                rs2.next();
                                //为发送请求提供参数
                                String workcode = rs2.getString("workcode");

                                if(rctsr.contains(",")){
                                    String[] split = rctsr.split(",");
                                    for (String str :split) {
                                        //判断是不是内部人员和参与人员
                                        if(dtList.contains(str) && nbList.contains(str)){
                                            cyList.add(str);
                                        }
                                    }
                                }else{
                                    if(dtList.contains(rctsr) && nbList.contains(rctsr)){
                                        cyList.add(rctsr);
                                    }
                                }
                                //流程构建参与人员
                                List<PersonVo> perList = cyList.stream().map((item) -> {
                                    PersonVo per = new PersonVo();
                                    per.setRelationType("HOST");
                                    per.setUserId(map.get(item));
                                    return per;
                                }).collect(Collectors.toList());
                                int finalBillid = billid;
                                String url = tgpt_url;
                                String appToken = getAppToken();
                                HashMap<String,String> header = new HashMap<String,String>();
                                header.put("JTXT-AUTH-TOKEN",appToken);
                                header.put("JTXT-AUTH-TYPE","APP");
                                paramMap.put("attendeeList",perList);
                                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
                                String kssj =null;
                                String jssj =null;
                                try {
                                    Instant ksInstant = format.parse(hdksrq+":00").toInstant();
                                    Instant jsInstant = format.parse(hdjsrq+":00").toInstant();
                                    paramMap.put("beginTime",ksInstant.toString());
                                    paramMap.put("endTime",jsInstant.toString());
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }
                                ArrayList<String>   roomIdList =   new ArrayList<String>();
                                paramMap.put("body","");
                                paramMap.put("eventStatus","NOT_START");
                                paramMap.put("eventType","FROM_WECHAT");
                                paramMap.put("freeBusyStatus","BUSY");
                                paramMap.put("groupId","");
                                paramMap.put("importance","NORMAL");
                                paramMap.put("isAllDay",false);
                                paramMap.put("isMeeting",true);
                                paramMap.put("location","");
                                paramMap.put("meetingId","");
                                paramMap.put("organizerId","");
                                paramMap.put("outlookMeetingId","");
                                paramMap.put("period","");
                                paramMap.put("referenceObj","");
                                paramMap.put("roomIdList",roomIdList);
                                paramMap.put("sensitivity","NORMAL");
                                paramMap.put("subject",hdmc);
                                paramMap.put("uniqueId","");
                                paramMap.put("userId",workcode);
                                paramMap.put("uuid","");
                                String jsonString = JSONObject.toJSONString(paramMap);
                                String inSql = "";
                                System.out.println(jsonString);
                                String s = httpPostRaw(url, jsonString, header, "utf-8");
                                System.out.println(s);
                                JSONObject parse = (JSONObject)JSONObject.parse(s);
                                LocalDateTime now2 = LocalDateTime.now();
                                String nowDateStr = now2.format(formatter1);
                                String nowTimeStr = now2.format(formatter2);
                                if(StringUtils.isNotBlank((String)parse.get("uuid"))){
                                    String insertSql = "insert into uf_jdhdrcts (rcid,jdhdid,rccjr) values ('"+parse.get("uuid")+"','"+String.valueOf(finalBillid)+"','"+creater+"')";
                                    perRs.execute(insertSql);
                                    // 用于记录日程创建
                                    inSql = "insert into uf_createRcRecord(jdhdid,rcid,sfcjcg,FORMMODEID,MODEDATACREATER,MODEDATACREATERTYPE,MODEDATACREATEDATE,MODEDATACREATETIME) values ('"+billid+"','"+parse.get("uuid")+"','1','"+tgpt_createRcModeid+"','1','0','"+nowDateStr+"','"+nowTimeStr+"')";
                                }else {
                                    inSql = "insert into uf_createRcRecord(jdhdid,rcid,sfcjcg,FORMMODEID,MODEDATACREATER,MODEDATACREATERTYPE,MODEDATACREATEDATE,MODEDATACREATETIME) values ('"+billid+"','','0','"+tgpt_createRcModeid+"','1','0','"+nowDateStr+"','"+nowTimeStr+"')";
                                }
                                JAVATools.writelog(inSql);
                                inRs.execute(inSql);
                                result.put("flag", "true");

                            }else{
                                result.put("flag", "true");
                            }
                        }
                    }
                } catch (Exception e) {
                    result.put("errmsg","自定义出错信息");
                    result.put("flag", "false");
                }
            }
        }.start();

        return result;
    }

    /**
     * 获取应用的token
     *
     * @return token
     */
    public String getAppToken() {
        String url = Util.null2String(new PropBean().getPropName("appToken"));
//        url =  "http://eipsit.htsc.com.cn/jtxt/auth/applogin/WEAVER/Admin@123";
        JSONObject res = JSONObject.parseObject(httpPostRaw(url, "", null, null));
        return Util.null2String(res.get("accessToken"));
    }
    /**
     * 发送http请求
     * @param url        接口地址
     * @param stringJson 请求的 json 字符串
     * @param headers    头部参数
     * @param encode     编码
     * @return 响应结果
     */
    private String httpPostRaw(String url, String stringJson, Map<String, String> headers, String encode)
    {
        BaseBean bb = new BaseBean();
        if (encode == null) {
            encode = "utf-8";
        }
        String content = null;
        CloseableHttpResponse httpResponse = null;
        CloseableHttpClient closeableHttpClient = null;
        try {
            //HttpClients.createDefault()等价于 HttpClientBuilder.create().build();
            closeableHttpClient = HttpClients.createDefault();
            HttpPost httpost = new HttpPost(url);
            //设置header
            httpost.setHeader("Content-type", "application/json");
            if (headers != null && headers.size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpost.setHeader(entry.getKey(), entry.getValue());
                }
            }
            //组织请求参数
            StringEntity stringEntity = new StringEntity(stringJson, encode);
            httpost.setEntity(stringEntity);
            //响应信息
            httpResponse = closeableHttpClient.execute(httpost);
            bb.writeLog("httpResponse===" + "httpResponse===" + httpResponse);
            HttpEntity entity = httpResponse.getEntity();
            bb.writeLog("entity", "entity===" + entity);
            content = EntityUtils.toString(entity, encode);
            bb.writeLog("content", "content===" + content);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpResponse.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {  //关闭连接、释放资源
            closeableHttpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }

}

