package weaver.interfaces.htsc.tgpt;

import com.alibaba.fastjson.JSONObject;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
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 weaver.interfaces.schedule.BaseCronJob;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @Title: ecology-9
 * @Company: 泛微软件
 * @author: K1810039
 * @version: 1.0
 * @CreateDate: 2022-08-19
 * @Description: 这是一个更新 E互动 的定时任务
 * @ModifyLog:
 **/
public class UpdateEhdDataCorn extends BaseCronJob {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Override
    public void execute() {
        JAVATools.writelog("---UpdateEhdDataCorn begin---");
        PropBean pb = new PropBean();
        RecordSet rs = new RecordSet();
        RecordSet upRs = new RecordSet();
        String modeid = pb.getPropName("ehd_modeid");

        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("HH:mm:ss");
        LocalDateTime now2 = LocalDateTime.now();
        String nowDateStr = now2.format(formatter1);
        String nowTimeStr = now2.format(formatter2);

        String  eSql = "select * from  uf_ehd order by id desc ";
        rs.execute(eSql);
        /**
         * 第一次E互动应该没有数据，全部插入同步过来的值
         */
        if(!rs.next()){
            int startrow = 0;
            int hasData = 0;
            int dataCount = 0;
            List<Map<String,Object>> allDataList = new ArrayList<>();
            Map<String,Object> param = new HashMap<>();
            // 指定华泰个股下的数据
            String[] arr = {"601688"};
            param.put("TRADINGCODE",arr);
            // 调接口取数据
            Map<String, Object> dataMap = getEhdData(String.valueOf(startrow),param);
            hasData = (int) dataMap.get("dataCount");
            dataCount = (int) dataMap.get("dataCount");
            if (hasData > 0){
                List<Map<String,Object>> dataList = (List<Map<String, Object>>) dataMap.get("dataList");
                allDataList.addAll(dataList);

                // 增量获取全部数据（由于接口请求数据量要求单次200）
                while (dataCount >= 200){
                    startrow += 200;
                    Map<String, Object> newDataMap = getEhdData(String.valueOf(startrow),param);
                    dataCount = (int) newDataMap.get("dataCount");
                    int resCount = (int) newDataMap.get("dataCount");
                    if (resCount > 0){
                        List<Map<String,Object>> newDataList = (List<Map<String, Object>>) newDataMap.get("dataList");
                        allDataList.addAll(newDataList);
                    }
                }

                // 遍历allDataList 获取每条数据，插入uf_ehd
                for (Map<String, Object> insertDataMap : allDataList) {
                    //问题标题
                    String id = ((BigDecimal)(insertDataMap.get("ID"))).stripTrailingZeros().toPlainString();
                    //问题标题
                    String question = (String) insertDataMap.get("QUESTION");
                    //问题答案
                    String answer = (String) insertDataMap.get("ANSWER");
                    //提问人
                    String questioner = (String) insertDataMap.get("QUESTIONER");
                    //提问时间
                    String reqdate = convertTimeStampToDate(String.valueOf(insertDataMap.get("REQDATE")));
                    //回复时间
                    String rspdate = convertTimeStampToDate(String.valueOf(insertDataMap.get("RSPDATE")));
                    //回复状态
                    String hfzt = org.apache.commons.lang.StringUtils.isBlank(answer)?"0":"1";
                    //来源
                    String ly = com.engine.integration.util.StringUtils.isBlank(answer)?"1":"0";
                    String insertSql="insert into uf_ehd (wtbt,wtda,twr,twsj,hfsj,hfzt,ly,zxid,FORMMODEID,MODEDATACREATER,MODEDATACREATERTYPE,MODEDATACREATEDATE,MODEDATACREATETIME) values ('"+question+"','"+answer+"','"+questioner+"','"+reqdate+"','"+rspdate+"','"+hfzt+"','"+ly+"','"+id+"','"+modeid+"','1','0','"+nowDateStr+"','"+nowTimeStr+"')";
                    boolean b = rs.execute(insertSql);
                    if (b){
                        // 建模权限重构
                        ModeRightInfo modeRightInfo = new ModeRightInfo();
                        modeRightInfo.setNewRight(true);
                        if (rs.execute("select max(id) as maxid from uf_ehd") && rs.next()){
                            int billid = rs.getInt("maxid");
                            modeRightInfo.editModeDataShare(1, Integer.parseInt(modeid),billid);
                        }
                    }
                }
            }
            JAVATools.writelog("---UpdateEhdDataCorn already end---");
        }else{
            /**
             * 回答时间在24小时之内的更新
             */
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime now = LocalDateTime.now();
            String nowStr = now.format(formatter);
            LocalDateTime beforeTime = now.plusHours(-24);
            String beforeTimeStr = beforeTime.format(formatter);

            Map<String,Object> param = new HashMap<>();
            // 指定华泰个股下的数据
            String[] arr = {"601688"};
            String[] rspDateArr = {"["+beforeTimeStr+","+nowStr+")"};
            param.put("TRADINGCODE",arr);
            param.put("RSPDATE",rspDateArr);

            int startrow = 0;
            int hasData = 0;
            int dataCount = 0;
            List<Map<String,Object>> allDataList = new ArrayList<>();

            // 调接口取数据
            Map<String, Object> dataMap = getEhdData(String.valueOf(startrow),param);
            dataCount = (int) dataMap.get("dataCount");
            hasData = (int) dataMap.get("dataCount");
            if (hasData > 0){
                List<Map<String,Object>> dataList = (List<Map<String, Object>>) dataMap.get("dataList");
                allDataList.addAll(dataList);

                // 增量获取全部数据（由于接口请求数据量要求单次200）
                while (dataCount >= 200){
                    startrow += 200;
                    Map<String, Object> newDataMap = getEhdData(String.valueOf(startrow),param);
                    dataCount = (int) newDataMap.get("dataCount");
                    int resCount = (int) newDataMap.get("dataCount");
                    if (resCount > 0){
                        List<Map<String,Object>> newDataList = (List<Map<String, Object>>) newDataMap.get("dataList");
                        allDataList.addAll(newDataList);
                    }
                }

                // 遍历allDataList 获取每条数据，插入uf_ehd
                for (Map<String, Object> insertDataMap : allDataList) {
                    //问题标题
                    String id = ((BigDecimal)(insertDataMap.get("ID"))).stripTrailingZeros().toPlainString();
                    //问题答案
                    String answer = (String) insertDataMap.get("ANSWER");
                    //回复时间
                    String rspdate = convertTimeStampToDate(String.valueOf(insertDataMap.get("RSPDATE")));

                    String ehdSql  ="select * from  uf_ehd";
                    rs.execute(ehdSql);
                    while(rs.next()){
                        if(Objects.equals(id,rs.getString("zxid"))){
                            String upSql = "update uf_ehd set wtda ='"+answer+"',hfsj='"+rspdate+"',hfzt=1,ly=0  where izxid ="+id;
                            upRs.execute(upSql);
                        }
                    }
                }
            }


            /**
             * 提问时间在24小时之内的新增
             */
            Map<String,Object> param2 = new HashMap<>();
            // 指定华泰个股下的数据
            String[] arr2 = {"601688"};
            String[] reqDateArr = {"["+beforeTimeStr+","+nowStr+")"};
            param2.put("TRADINGCODE",arr2);
            param2.put("REQDATE",reqDateArr);

            int startrow2 = 0;
            int hasData2 = 0;
            int dataCount2 = 0;
            List<Map<String,Object>> allDataList2 = new ArrayList<>();

            // 调接口取数据
            Map<String, Object> dataMap2 = getEhdData(String.valueOf(startrow2),param2);
            dataCount2 = (int) dataMap2.get("dataCount");
            hasData2 = (int) dataMap2.get("dataCount");
            if (hasData2 > 0){
                List<Map<String,Object>> dataList2 = (List<Map<String, Object>>) dataMap2.get("dataList");
                allDataList2.addAll(dataList2);

                // 增量获取全部数据（由于接口请求数据量要求单次200）
                while (dataCount2 >= 200){
                    startrow2 += 200;
                    Map<String, Object> newDataMap = getEhdData(String.valueOf(startrow2),param2);
                    dataCount2 = (int) newDataMap.get("dataCount");
                    int resCount2 = (int) newDataMap.get("dataCount");
                    if (resCount2 > 0){
                        List<Map<String,Object>> newDataList = (List<Map<String, Object>>) newDataMap.get("dataList");
                        allDataList2.addAll(newDataList);
                    }
                }

                // 遍历allDataList 获取每条数据，插入uf_ehd
                for (Map<String, Object> insertDataMap : allDataList2) {
                    //问题标题
                    String id = ((BigDecimal)(insertDataMap.get("ID"))).stripTrailingZeros().toPlainString();
                    //问题标题
                    String question = (String) insertDataMap.get("QUESTION");
                    //问题答案
                    String answer = (String) insertDataMap.get("ANSWER");
                    //提问人
                    String questioner = (String) insertDataMap.get("QUESTIONER");
                    //提问时间
                    String reqdate = convertTimeStampToDate(String.valueOf(insertDataMap.get("REQDATE")));
                    //回复时间
                    String rspdate = convertTimeStampToDate(String.valueOf(insertDataMap.get("RSPDATE")));
                    //回复状态
                    String hfzt = org.apache.commons.lang.StringUtils.isBlank(answer)?"0":"1";
                    //来源
                    String ly = com.engine.integration.util.StringUtils.isBlank(answer)?"1":"0";
                    String insertSql="insert into uf_ehd (wtbt,wtda,twr,twsj,hfsj,hfzt,ly,zxid,FORMMODEID,MODEDATACREATER,MODEDATACREATERTYPE,MODEDATACREATEDATE,MODEDATACREATETIME) values ('"+question+"','"+answer+"','"+questioner+"','"+reqdate+"','"+rspdate+"','"+hfzt+"','"+ly+"','"+id+"','"+modeid+"','1','0','"+nowDateStr+"','"+nowTimeStr+"')";
                    boolean b = rs.execute(insertSql);
                    if (b){
                        // 建模权限重构
                        ModeRightInfo modeRightInfo = new ModeRightInfo();
                        modeRightInfo.setNewRight(true);
                        if (rs.execute("select max(id) as maxid from uf_ehd") && rs.next()){
                            int billid = rs.getInt("maxid");
                            modeRightInfo.editModeDataShare(1, Integer.parseInt(modeid),billid);
                        }
                    }
                }
            }
        }
        JAVATools.writelog("---UpdateEhdDataCorn already end---");
    }


    /**
     * 将时间戳转换成指定格式的date
     * @param timeStamp 时间戳字符串
     * @return 指定格式的date
     */
    public String convertTimeStampToDate(String timeStamp){
        Long timeLong = Long.parseLong(timeStamp);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");//要转换的时间格式
        Date date;
        try {
            date = sdf.parse(sdf.format(timeLong));
            return sdf.format(date);
        } catch (ParseException e) {
            logger.info("catch exception:"+e.getMessage());
            return null;
        }
    }


    /**
     * E互动，调接口获取全部数据
     */
    public Map<String, Object> getEhdData(String startrow,Map<String,Object> param) {
        PropBean pb = new PropBean();
        HashMap<String, Object> map = new HashMap<>();
        HttpRequestUtil httpRequestUtil = new HttpRequestUtil();
        Map<String,Object> paramMap = new HashMap<>();
        try {
            String url = pb.getPropName("tgpt_zxzxUrl");
            String key = pb.getPropName("ehd_key");
            JAVATools.writelog("url:"+url);
            paramMap.put("key",key);
            paramMap.put("resource","ZX_TEXTEINTERACTNEW");
            paramMap.put("paramMaps",param);
            paramMap.put("startrow",startrow);
            paramMap.put("rownum","200");
            paramMap.put("orderBy","");
            paramMap.put("selectedFields",null);
            String requestParams = JSONObject.toJSONString(paramMap);
            JAVATools.writelog("requestParams-->"+requestParams);
            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");
            int dataCount = (int) resJsonObject.get("dataCount");
            map.put("dataList",dataList);
            map.put("dataCount",dataCount);
        } catch (Exception e) {
            logger.info("catch exception:"+e.getMessage());
        }
        return map;
    }

}