package weaver.interfaces.htsc.tgpt;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
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.comInfo.PropBean;
import weaver.interfaces.htsc.cus.HTUtil;
import weaver.soa.workflow.request.RequestInfo;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
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 UpdateOrDeleteCleander 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>();
        ArrayList<String> rccjrList = new ArrayList<>();//已经创建过日程的日程创建人
        ArrayList<String> rcIdList = new ArrayList<>();//日程id xp系统
        ArrayList<String> dtXm = new ArrayList<>();//尽调活动明细表姓名
        ArrayList<String> nbList = new ArrayList<>();//内部人员
        RecordSet rs = new RecordSet();
        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");

                    //获取当前的已经创建过日程的人员uf_jdhdrcts
                    String sql ="select * from uf_jdhdrcts where jdhdid =   "+billid;
                    rs.execute(sql);
                    String oldKshdsj = null;
                    String oldJshdsj = null;
                    while(rs.next()){
                        rccjrList.add(rs.getString("rccjr"));
                        rcIdList.add(rs.getString("rcid"));
                        oldKshdsj= rs.getString("hdksrq");
                        oldJshdsj = rs.getString("hdjsrq");
                    }
                    sql  = "select * from uf_jdhd_dt1 where mainid = "+billid;
                    rs.execute(sql);
                    while(rs.next()){
                        dtXm.add(rs.getString("xm"));
                    }
                    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"));
                    }
                    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"));
                    }
                    //当之前的创建日程人员和本次修改后的创建日程人员不一致时，要给新增，修改，删除
                    boolean flag = compareByContainsAll(rccjrList, rctsrList);
                    if(!flag){
                        //判断当前人员是否在进洞活动的明细表1中，若不存在需要进行删除日程
                        //判断明细表1中相对于uf_jdhdrcts，新增的人员进行日程创建，，其他人员进行日程修改
                        List<String> insertPerson = rctsrList.stream().filter((item) -> {
                            return !rccjrList.contains(item);
                        }).collect(Collectors.toList());
                        insert(insertPerson,dtXm,nbList,dtXm,hdksrq,hdjsrq,billid);

                        List<String> delPerson = rccjrList.stream().filter((item) -> {
                            return !dtXm.contains(item);
                        }).collect(Collectors.toList());
                        del(delPerson,billid);

                        List<String> updatePerson = dtXm.stream().filter((item) -> {
                            return rccjrList.contains(item);
                        }).collect(Collectors.toList());
                        update(hdksrq,hdjsrq,updatePerson,billid,dtXm,nbList);
                    }
                    //只是修改了时间
                    if(flag&& (!Objects.equals(oldKshdsj,hdksrq) ||!Objects.equals(oldJshdsj,hdjsrq))){
                        update(hdksrq,hdjsrq,rccjrList,billid,dtXm,nbList);
                    }
                }
            }
        } catch (Exception e) {
            result.put("errmsg","自定义出错信息");
            result.put("flag", "false");
        }
        return result;
    }
    //修改日程
    private void update(String hdksrq, String hdjsrq, List<String> updatePerson,int billid,List<String> dtXm,List<String> nbList) {
        RecordSet rs = new RecordSet();
        HashMap<String, String> map = new HashMap<>();
        PropBean pb = new PropBean();
        String tgpt_url_authlogin = pb.getPropName("tgpt_url_authlogin");
        updatePerson.forEach((item)->{
            HashMap<String, String> header = new HashMap<>();
            String personSql = "select * from (SELECT  glnbry  FROM ( SELECT modeuuid, glnbry FROM uf_qtryxxgl UNION SELECT modeuuid, glnbry FROM uf_djgxxgl )   WHERE modeuuid = '"+item+"')";
            rs.execute(personSql);
            rs.next();
            String glnbry = rs.getString("glnbry");
            String hrmSql = "select * from hrmresource where id = "+glnbry;
            rs.execute(hrmSql);
            rs.next();
            String workcode = rs.getString("workcode");
            header.put("iv-user",workcode);
            String token = httpPostRaw(tgpt_url_authlogin, null, header, null);
            JSONObject parse = (JSONObject)JSONObject.parse(token);
            String accessToken = (String)parse.get("accessToken");
            HashMap<String, String> getHeader = new HashMap<>();
            getHeader.put("JTXT-AUTH-TOKEN",accessToken);
            getHeader.put("JTXT-AUTH-TYPE","USER");
            String tgpt_url_get = pb.getPropName("tgpt_url_get");
            String sql = "select * from uf_jdhdrcts where jdhdid =   "+billid + " and rccjr = '" +item+"'";
            rs.execute(sql);
            if(rs.next()){
                String rcid = rs.getString("rcid");
                String content = httpGetRaw(tgpt_url_get + rcid, getHeader, null);
                JSONObject json = (JSONObject)JSONObject.parse(content);
                List<String> collect = dtXm.stream().filter((item1) -> {
                    return nbList.contains(item1);
                }).collect(Collectors.toList());
                List<PersonVo> perList = collect.stream().map((item1) -> {
                    PersonVo per = new PersonVo();
                    per.setRelationType("HOST");
                    per.setUserId(map.get(item1));
                    return per;
                }).collect(Collectors.toList());
                json.put("attendeeList",perList);
                try {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Instant ksInstant = format.parse(hdksrq+":00").toInstant();
                    Instant jsInstant = format.parse(hdjsrq+":00").toInstant();
                    json.put("beginTime",ksInstant.toString());
                    json.put("endTime",jsInstant.toString());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                HashMap<String, String> postHeader = new HashMap<>();
                postHeader.put("JTXT-AUTH-TOKEN",getAppToken());
                postHeader.put("JTXT-AUTH-TYPE","APP");
                String tgpt_url_update = pb.getPropName("tgpt_url_update");
                httpPostRaw(tgpt_url_update,json.toJSONString(),postHeader,null);
            }
        });
    }
    //远程删除日程
    public void del(List<String> delPerson,int billid){
        if(delPerson.isEmpty()){}else{
            PropBean pb = new PropBean();
            String tgpt_del_url = pb.getPropName("tgpt_del_url");
            ArrayList<String> uuidList = new ArrayList<>();
            RecordSet rs = new RecordSet();
            String appToken = getAppToken();
            HashMap<String,String> header = new HashMap<String,String>();
            header.put("JTXT-AUTH-TOKEN",appToken);
            header.put("JTXT-AUTH-TYPE","APP");
            delPerson.forEach((item)->{
                String sql ="select * from uf_jdhdrcts where jdhdid =   "+billid + " and rccjr = '" +item+"'";
                rs.execute(sql);
                if(rs.next()){
                    String rcid = rs.getString("rcid");
                    httpPostRaw(tgpt_del_url+"/"+rcid,"",header,null);

                }
            });
        }


    }
    //方法一：使用list中的containsAll方法，此方法是判断list2是否是list的子集，即list2包含于list
    public  boolean compareByContainsAll(List<String> list, List<String> list2){
        boolean flag = false;
        if (list.size()==list2.size()){
            if (list.containsAll(list2)){
                flag = true;
            }
        }
        return flag;
    }
                 // cjList 参加
    public void insert(List<String> createList,List<String> cjList,List<String> nbList,List<String> xmList,String hdksrq,String hdjsrq,int billid){
        RecordSet rs = new RecordSet();
        PropBean pb = new PropBean();
        String tgpt_url = pb.getPropName("tgpt_url");
        HashMap<String,Object> paramMap = new HashMap<String,Object>();
        HashMap<String, String> map = new HashMap<>();
        createList.forEach((item)->{
            String hrmSql = "select * from hrmresource where id = " + item;
            rs.execute(hrmSql);
            rs.next();
            //为发送请求提供参数
            map.put(item,rs.getString("workcode"));
        });
        //流程构建参与人员
        cjList = cjList.stream().filter((item)->{return nbList.contains(item);}).collect(Collectors.toList());
        List<PersonVo> perList = cjList.stream().map((item) -> {
            PersonVo per = new PersonVo();
            per.setRelationType("HOST");
            per.setUserId(map.get(item));
            return per;
        }).collect(Collectors.toList());
        List<String> newCreateList = createList.stream().filter((item) -> {
            return nbList.contains(item) && xmList.contains(item);
        }).collect(Collectors.toList());

        newCreateList.forEach((item)->{
            String workcode = map.get(item);
            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","");
            paramMap.put("uniqueId","");
            paramMap.put("userId",workcode);
            paramMap.put("uuid","");
            String jsonString = JSONObject.toJSONString(paramMap);
            System.out.println(jsonString);
            String s = httpPostRaw(url, jsonString, header, "utf-8");
            System.out.println(s);
            JSONObject parse = (JSONObject)JSONObject.parse(s);
            if(StringUtils.isNotBlank((String)parse.get("uuid"))){
                String insertSql = "insert into uf_jdhdrcts (rcid,jdhdid,rccjr) values ('"+parse.get("uuid")+"','"+String.valueOf(billid)+"','"+item+"')";
                rs.execute(insertSql);
            }

        });

    }
    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;
    }
    /**
     * get请求
     *
     * @param url
     * @param headers
     * @param encode
     * @return
     */
    private Log log = LogFactory.getLog(UpdateOrDeleteCleander.class);
    public String httpGetRaw(String url, Map<String, String> headers, String encode) {
        if (encode == null) {
            encode = "utf-8";
        }
        String content = null;
        CloseableHttpResponse httpResponse = null;
        CloseableHttpClient closeableHttpClient = null;
        try {

            //HttpClients.createDefault()等价于 HttpClientBuilder.create().build();
            closeableHttpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(url);

            //设置header
            httpGet.setHeader("Content-type", "application/json");
            if (headers != null && headers.size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpGet.setHeader(entry.getKey(), entry.getValue());
                }
            }
            //响应信息
            httpResponse = closeableHttpClient.execute(httpGet);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity, encode);
        } catch (Exception e) {
            log.error("http get error", e);
        } finally {
            try {
                httpResponse.close();
            } catch (IOException e) {
                log.error("http response close error", e);
            }
        }
        try {  //关闭连接、释放资源
            closeableHttpClient.close();
        } catch (IOException e) {
            log.error("http connection close error", e);
        }
        return content;
    }



}

