package com.engine.htsc.tgpt.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.engine.core.impl.Service;
import com.engine.htsc.tgpt.service.TgptService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.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.conn.RecordSetDataSource;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.util.HttpRequestUtil;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Title: ecology-9
 * @Company: 泛微软件
 * @author: K1810039
 * @version: 1.0
 * @CreateDate: 2022-08-19
 * @Description: 投关平台
 * @ModifyLog:
 **/
public class TgptServiceImpl  extends Service implements TgptService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Override
    public Map<String, String> getGlnbry(String xm) {
        HashMap<String, String> map = new HashMap<>();
        RecordSet rs = new RecordSet();
        String sql = "select * from hrmresource where id = ( SELECT  glnbry  FROM ( SELECT modeuuid, glnbry FROM uf_qtryxxgl UNION SELECT modeuuid, glnbry FROM uf_djgxxgl )   WHERE modeuuid = '"+xm+"')";
        rs.execute(sql);
        if(rs.next()){
            map.put("id",rs.getString("id"));
            map.put("name",rs.getString("lastname"));
            map.put("workcode",rs.getString("workcode"));
            return map;
        }else{
            return null;
        }


    }

    @Override
    public boolean getWorkflow(String billid) {
        PropBean pb = new PropBean();
        RecordSet rs = new RecordSet();
        RecordSet rs2 = new RecordSet();
        String ehd_tablename = pb.getPropName("ehd_tablename");
        String sql = "select * from "+ehd_tablename +" where jmid = "+billid;
        rs.execute(sql);
        while(rs.next()){
            String requestid = rs.getString("requestid");
            sql = "select base.*,oper.* from workflow_requestbase base left join workflow_currentoperator oper on base.requestid = oper.requestid where oper.iscomplete = 0 and base.deleted = 0  and base.requestid = "+requestid;
            rs2.execute(sql);
            boolean next = rs2.next();
            if(next){
                return next;
            }

        }
       return false;
    }

    /**
     * E互动，获取回答次数和平均回复时间
     */
    @Override
    public Map<String, String> getNumAndTime() {
        JAVATools.writelog("----getNumAndTime----");
        PropBean pb = new PropBean();
        HashMap<String, String> map = new HashMap<>();
        HttpRequestUtil httpRequestUtil = new HttpRequestUtil();
        Map<String,Object> param = new HashMap<>();
        Map<String,Object> paramMap = new HashMap<>();
        String answerTimes ="";
        String answerAvgTime ="";
        //String url = "http://168.61.9.105:8085/htsc-cds-inter/IInterProvider/getResourceData";
        String url = pb.getPropName("tgpt_zxzxUrl");
        String key = pb.getPropName("ehd_key");
        JAVATools.writelog("url:"+url);
        // 指定华泰个股下的数据
        String[] arr = {"601688"};
        param.put("TRADINGCODE",arr);
        paramMap.put("key",key);
        paramMap.put("resource","ZX_INTERACTIVESTATS");
        paramMap.put("paramMaps",param);
        paramMap.put("startrow","0");
        paramMap.put("rownum","200");
        paramMap.put("orderBy","");
        paramMap.put("selectedFields",null);
        String requestParams = JSONObject.toJSONString(paramMap);
        JAVATools.writelog("requestParams-->"+requestParams);
        try {
            String response = httpRequestUtil.sendPost(url, requestParams,"UTF-8");
            JSONObject resJsonObject = JSONObject.parseObject(response);
            String status = resJsonObject.getString("status");
            if (!"1".equals(status)){
                return map;
            }
            List<Map<String,Object>> dataList = (List<Map<String,Object>>) resJsonObject.get("dataList");
            for (Map<String,Object> dataMap : dataList) {
                answerTimes = dataMap.get("ANSWERTIMES").toString();
                answerAvgTime = dataMap.get("ANSWERAVGTIME").toString();
            }
            map.put("answerTimes",answerTimes);
            map.put("answerAvgTime",answerAvgTime);
        } catch (Exception e) {
            logger.info("catch exception:"+e.getMessage());
        }
        return map;
    }

    /**
     * 删除日程
     * @param billids
     * @return
     */
    @Override
    public Map<String, Object> deleteRc(String billids) {
        JAVATools.writelog("----deleRcAndGtsl----"+billids);
        Map<String, Object> map = new HashMap<>();
        try {
            //字符串转换成list
            List<String> billidsList = new ArrayList<>();
            if (StringUtils.isNotBlank(billids)){
                billidsList = convertStringToList(billids);
            }
            JAVATools.writelog("billidsList:"+JSONObject.toJSONString(billidsList));
            for (String billid : billidsList) {
                // 调用接口，删除日程
                del(Integer.parseInt(billid));
            }

        } catch (NumberFormatException e) {
            map.put("flag","0");
            logger.info("catch exception:"+e.getMessage());
        }
        map.put("flag","1");
        return map;
    }

    /**
     * 通讯录软删除，更新是否显示字段 sfxs = 1
     * @param billids
     * @param tableName
     * @return
     */
    @Override
    public Map<String, Object> updateYsc(String billids, String tableName) {
        JAVATools.writelog("----updateYsc----");
        JAVATools.writelog("billids:"+billids);
        JAVATools.writelog("tableName:"+tableName);
        Map<String, Object> map = null;
        try {
            map = new HashMap<>();
            RecordSet rs = new RecordSet();
            String sql = "update "+tableName+" set sfxs = '1' where ID in("+billids+")";
            JAVATools.writelog(sql);
            boolean flag = rs.execute(sql);
            if (flag){
                map.put("flag","1");
            }else {
                map.put("flag","0");
            }
        } catch (Exception e) {
            logger.info("catch exception:"+e.getMessage());
        }
        return map;
    }

    @Override
    public List<Map<String, String>> getYb(String billid) {
        List<Map<String, String>> dataList = new ArrayList<>();
        RecordSet rs = new RecordSet();
        JAVATools.writelog("----getYb---billid:"+billid);
        String sql = "select * from uf_wbfxsxxgl_dt1 where MAINID = "+billid;
        rs.execute(sql);
        while (rs.next()){
            Map<String, String> dataMap = new HashMap<>();
            String id = rs.getString("id");
            String ybmc = rs.getString("ybmc");
            String ybdz = rs.getString("ybdz");
            dataMap.put("id",id);
            dataMap.put("ybmc",ybmc);
            dataMap.put("ybdz",ybdz);
            dataList.add(dataMap);
        }
        JAVATools.writelog("----getYb---dataList:"+dataList);
        return dataList;
    }

    /**
     * 删除尽调活动，改变沟通数量
     * @param billids
     * @return
     */
    @Override
    public Map<String, Object> deleteJdhdAndUpdateGtsl(String billids) {
        JAVATools.writelog("----deleteJdhdAndUpdateGtsl----"+billids);
        Map<String, Object> map = new HashMap<>();
        RecordSet rs = new RecordSet();
        RecordSet rs2 = new RecordSet();
        String sql = "";
        //字符串转换成list
        List<String> billidsList = new ArrayList<>();
        if (StringUtils.isNotBlank(billids)){
            billidsList = convertStringToList(billids);
        }
        JAVATools.writelog("billidsList:"+JSONObject.toJSONString(billidsList));

        List<String> xmList = new ArrayList<>();
        try {
            for (String billid : billidsList) {
                // 1.改变沟通数量,获取明细表的姓名
                String xmStrs = "";
                sql = "select XM from uf_jdhd_dt1 where mainid = "+billid;
                JAVATools.writelog(sql);
                rs.execute(sql);
                while (rs.next()){
                    xmList.add(rs.getString("XM"));
                }
                // 将List集合转换成  "'1','2','3',...." 格式的字符串
                if (CollectionUtils.isNotEmpty(xmList)){
                    xmStrs = convertListToString(xmList);
                }
                JAVATools.writelog(xmStrs);
                // 更新沟通数量 减1
                sql = "update uf_jgtzzxxgl set jnylygsgtsl = jnylygsgtsl-1  where modeuuid in ("+xmStrs+")";
                JAVATools.writelog(sql);
                rs.execute(sql);
                sql = "update uf_wbfxsxxgl set jnylygsgtsl = jnylygsgtsl-1  where modeuuid in ("+xmStrs+")";
                JAVATools.writelog(sql);
                rs2.execute(sql);

                // 2.删除对应的明细表数据
                String sql1 = "delete from UF_JDHD_DT1 where MAINID = "+billid;
                rs2.execute(sql1);
                String sql2 = "delete from UF_JDHD_DT2 where MAINID = "+billid;
                rs2.execute(sql2);
                String sql3 = "delete from UF_JDHD_DT3 where MAINID = "+billid;
                rs2.execute(sql3);

            }
            // 3.删除该活动
            sql = "delete from uf_jdhd where ID in ("+billids+")";
            JAVATools.writelog(sql);
            rs.execute(sql);
        } catch (NumberFormatException e) {
            logger.info("catch exception:"+e.getMessage());
        }
        map.put("flag","1");
        return map;
    }


    /**
     * 将”1,2,3,...“这样的字符串转换成list<String>
     */
    public List<String> convertStringToList(String strs){
        if (StringUtils.isNotBlank(strs)){
            String[] idStrs = strs.trim().split(",");
            if (idStrs.length > 0){
                List<String> strsList = new ArrayList<String>();
                for (String str : idStrs) {
                    if (StringUtils.isNotBlank(str)){
                        strsList.add(str.trim());
                    }
                }
                if (strsList.size() > 0){
                    return strsList;
                }
            }
        }
        return  null;
    }

    /**
     * 将List集合转换成  "'1','2','3',...." 格式的字符串
     * @param strList
     * @return
     */
    public String convertListToString(List<String> strList){
        StringBuffer sb = new StringBuffer();
        if (CollectionUtils.isNotEmpty(strList)){
            for (int i = 0; i < strList.size(); i++) {
                if (i == 0){
                    sb.append("'").append(strList.get(i)).append("'");
                }else {
                    sb.append(",").append("'").append(strList.get(i)).append("'");
                }
            }
        }
        return sb.toString();
    }

    /**
     * 远程删除日程
     * @param billid
     */
    public void del(int billid){
        PropBean pb = new PropBean();
        String tgpt_del_url = pb.getPropName("tgpt_del_url");
        RecordSet rs = new RecordSet();
        RecordSet rs2 = new RecordSet();
        String appToken = getAppToken();
        String tgpt_deleteRcModeid = pb.getPropName("tgpt_deleteRcModeid");
        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("HH:mm:ss");
        HashMap<String,String> header = new HashMap<>();
        header.put("JTXT-AUTH-TOKEN",appToken);
        header.put("JTXT-AUTH-TYPE","APP");
        String sql ="select * from uf_jdhdrcts where jdhdid =   "+billid ;
        rs.execute(sql);
        while (rs.next()){
            String rcid = rs.getString("rcid");
            String updateSql = "";
            // 1.删除日程前，把日程id和删除状态插入建模表（状态默认为0 未删除）
            if (StringUtils.isNotBlank(rcid)){
                LocalDateTime now2 = LocalDateTime.now();
                String nowDateStr = now2.format(formatter1);
                String nowTimeStr = now2.format(formatter2);
                String insertSql="insert into uf_deleteRcfzb (RCID,billid,SCZT,FORMMODEID,MODEDATACREATER,MODEDATACREATERTYPE,MODEDATACREATEDATE,MODEDATACREATETIME) values ('"+rcid+"',"+billid+",'0','"+tgpt_deleteRcModeid+"','1','0','"+nowDateStr+"','"+nowTimeStr+"')";
                rs2.execute(insertSql);
            }
            // 2.调接口，执行删除
            String res = httpPostRaw(tgpt_del_url + "/" + rcid, "", header, null);
            JAVATools.writelog("delRc--res:"+res);
            // 3.删除成功 则更改删除状态为 1（已删除）,删除失败不做操作
            if ("true".equals(res)){
                updateSql = "update uf_deleteRcfzb set SCZT = '1' where RCID = '"+rcid+"'";
                JAVATools.writelog(updateSql);
                rs2.execute(updateSql);
            }
        }
    }

    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 响应结果
     */
    public 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) {
            logger.info("catch exception:"+e.getMessage());
        } finally {
            try {
                httpResponse.close();
            } catch (IOException e) {
                logger.info("catch exception:"+e.getMessage());
            }
        }
        try {  //关闭连接、释放资源
            closeableHttpClient.close();
        } catch (IOException e) {
            logger.info("catch exception:"+e.getMessage());
        }
        return content;
    }

}
