package weaver.interfaces.htsc.tgpt;

import com.alibaba.fastjson.JSONObject;
import com.engine.integration.util.StringUtils;
import com.engine.workflow.util.CollectionUtil;
import com.weaver.formmodel.log.LogFactory;
import org.apache.commons.collections4.CollectionUtils;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.StringUtil;
import weaver.general.Util;
import weaver.integration.logging.Logger;
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: 这是一个更新 外部分析师 的定时任务
 * @ModifyLog:
 **/
public class UpdateWbfxsDataCorn extends BaseCronJob {
    @Override
    public void execute() {
        PropBean pb = new PropBean();
        RecordSet rs = new RecordSet();
        RecordSet rs2 = new RecordSet();
        RecordSet insertDt1Rs = new RecordSet();
        JAVATools.writelog("---UpdateWbfxsDataCorn begin---");
        String sql = "";
        // 根据 DCEAA7A09D441AAAE0538E123FA879C2 获取外部分析师 modeid
        String rwmodeid = pb.getPropName("WBFXS.MODELCUBEUUID");
        JSONObject jsonObject_rw = pb.getModeInfoByUUID(rwmodeid);
        int modeid = Util.getIntValue(jsonObject_rw.getString("modeid"));

        // 获取外部分析师数据
        List<Map<String, Object>> apidatas = new ArrayList<>();
        apidatas = getWebfxs();

        // 第一次外部分析师应该没有数据，全部插入同步过来的值
        sql = "select id from uf_wbfxsxxgl ";
        rs.execute(sql);
        if (!rs.next()) {
            // 遍历获取每一个分析师数据，插入表
            for (Map<String, Object> fxsMap : apidatas) {
                Map<String, Object> paramsMap = new HashMap<>();
                paramsMap.putAll(fxsMap);
                paramsMap.put("modeid",modeid);
                // 向外部分析师表 及明细表 插入数据
                updateData(paramsMap);
            }

        } else {// 做更新数据 已有的分析师更新所有数据，新的分析师插入数据
            // 获取已有的所有分析师的编码
            List<Object> xmcodeList = new ArrayList<>();
            sql = "select xmcode from uf_wbfxsxxgl ";
            rs2.execute(sql);
            while (rs2.next()){
                 if (!StringUtils.isBlank(rs2.getString("xmcode"))){
                     xmcodeList.add(rs2.getString("xmcode"));
                 }
            }

            // 遍历获取每一个分析师数据
            for (Map<String, Object> fxsMap : apidatas) {
                String xmcode = String.valueOf(fxsMap.get("xmcode"));
                String dzyx = String.valueOf(fxsMap.get("dzyx"));
                String dh = String.valueOf(fxsMap.get("dh"));
                String rzjgmc = String.valueOf(fxsMap.get("rzjgmc"));
                String dgszxpj = String.valueOf(fxsMap.get("dgszxpj"));
                String ysyqdbqk = String.valueOf(fxsMap.get("ysyqdbqk"));
                String zjynybsl = String.valueOf(fxsMap.get("zjynybsl"));
                String xgryhhjqk = String.valueOf(fxsMap.get("xgryhhjqk"));
                if (!StringUtils.isBlank(xgryhhjqk)){
                    xgryhhjqk = xgryhhjqk.substring(0,xgryhhjqk.indexOf("."));
                }
                Map<String, Object> titleAndAddrMap = (Map<String, Object>) fxsMap.get("titleAndAddrMap");

                // 拿到其中一个研报名称 和 研报地址 存入 研报名称辅助字段  研报地址辅助字段
                String ybmc = "";
                String ybdz = "";
                for (Map.Entry<String, Object> entry : titleAndAddrMap.entrySet()) {
                    ybmc = entry.getKey();
                    ybdz = String.valueOf(entry.getValue());
                    if (ybmc != null) {
                        break;
                    }
                }

                // 若该分析师已存在，则更新其所有数据,不存在则插入
                if (xmcodeList.contains(xmcode)){
                    String upSql = "update uf_wbfxsxxgl set ybmcfzzd = '"+ybmc+"',ybdzfzzd = '"+ybdz+"',dzyx = '"+dzyx+"',dh = '"+dh+"',rzjgmc = '"+rzjgmc+"',dgszxpj = '"+dgszxpj+"',ysyqdbqk = '"+ysyqdbqk+"',zjynybsl = '"+zjynybsl+"',xgryhhjqk = '"+xgryhhjqk+"'\n" +
                            "  where XMCODE = '"+xmcode+"'";
                    rs2.execute(upSql);

                    // 遍历titleAndAddrMap<title,地址>，更新/插入明细表
                    String newSql = "select id from uf_wbfxsxxgl where xmcode = '" + xmcode + "'";
                    rs2.execute(newSql);
                    if (rs2.next()){
                        String id = rs2.getString("id");
                        // 删除该人员原来的研报
                        String delSql = "delete from UF_WBFXSXXGL_DT1 where MAINID ="+id;
                        insertDt1Rs.execute(delSql);

                        for (String key : titleAndAddrMap.keySet()) {
                            // 全部更新研报数据
                            String insertDt1Sql = "insert into uf_wbfxsxxgl_dt1( mainid , ybdz,ybmc) values(" + id + ",'" + titleAndAddrMap.get(key) + "','" + key + "') ";
                            insertDt1Rs.execute(insertDt1Sql);
                        }
                    }

                }else {
                    Map<String, Object> paramsMap = new HashMap<>();
                    paramsMap.putAll(fxsMap);
                    paramsMap.put("ybmc",ybmc);
                    paramsMap.put("ybdz",ybdz);
                    paramsMap.put("modeid",modeid);
                    updateData(paramsMap);
                }
            }
        }
        JAVATools.writelog("---UpdateWbfxsDataCorn already end---");
    }

    /**
     * 向外部分析师表 及明细表 插入数据
     * @param paramsMap
     */
    public void updateData(Map<String, Object> paramsMap){
        RecordSet rsInsert = new RecordSet();
        RecordSet rs2 = new RecordSet();
        RecordSet insertDt1Rs = new RecordSet();
        String xm = String.valueOf(paramsMap.get("xm"));
        String xmcode = String.valueOf(paramsMap.get("xmcode"));
        String dzyx = String.valueOf(paramsMap.get("dzyx"));
        String dh = String.valueOf(paramsMap.get("dh"));
        String gxfzzd = String.valueOf(paramsMap.get("gxfzzd"));
        String rzjgmc = String.valueOf(paramsMap.get("rzjgmc"));
        String dgszxpj = String.valueOf(paramsMap.get("dgszxpj"));
        String ysyqdbqk = String.valueOf(paramsMap.get("ysyqdbqk"));
        String zjynybsl = String.valueOf(paramsMap.get("zjynybsl"));
        String xgryhhjqk = String.valueOf(paramsMap.get("xgryhhjqk"));
        String modeid = String.valueOf(paramsMap.get("modeid"));
        if (!StringUtils.isBlank(xgryhhjqk)){
            xgryhhjqk = xgryhhjqk.substring(0,xgryhhjqk.indexOf("."));
        }
        String uuid = String.valueOf(paramsMap.get("uuid"));
        String modeuuid = String.valueOf(paramsMap.get("modeuuid"));
        Map<String, Object> titleAndAddrMap = (Map<String, Object>) paramsMap.get("titleAndAddrMap");

        // 拿到其中一个研报名称 和 研报地址 存入 研报名称辅助字段  研报地址辅助字段
        String ybmc = "";
        String ybdz = "";
        for (Map.Entry<String, Object> entry : titleAndAddrMap.entrySet()) {
            ybmc = entry.getKey();
            ybdz = String.valueOf(entry.getValue());
            if (ybmc != null) {
                break;
            }
        }

        // 新数据插入
        String dateValue = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String time = new SimpleDateFormat("HH:mm:ss").format(new Date());
        String insertSql = "insert into uf_wbfxsxxgl " +
                "(ybmcfzzd,ybdzfzzd,xm,xmcode,dzyx,dh,gxfzzd,rzjgmc,dgszxpj,ysyqdbqk,zjynybsl,xgryhhjqk,uuid,modeuuid," +
                " FORMMODEID,MODEDATACREATER,MODEDATACREATERTYPE,MODEDATACREATEDATE,MODEDATACREATETIME) " +
                "values ('" + ybmc + "','" + ybdz + "','" + xm + "','" + xmcode + "','" + dzyx + "','" + dh + "','" + gxfzzd + "','" + rzjgmc + "','" + dgszxpj + "','" + ysyqdbqk + "','" + zjynybsl + "','" + xgryhhjqk + "','" + uuid + "','" + uuid + "','" + modeid + "','1','0','" + dateValue + "','" + time + "')";
        boolean b = rsInsert.execute(insertSql);
        if (b) {
            // 建模权限重构
            ModeRightInfo modeRightInfo = new ModeRightInfo();
            modeRightInfo.setNewRight(true);
            String mainSql = "select id from uf_wbfxsxxgl where uuid =  '" + uuid + "'";
            rs2.execute(mainSql);
            rs2.next();
            String id = rs2.getString("id");
            modeRightInfo.editModeDataShare(1, Integer.parseInt(modeid), Integer.parseInt(id));
        }

        // 遍历titleAndAddrMap<title,地址>，插入明细表
        String newSql = "select id from uf_wbfxsxxgl where uuid = '" + uuid + "'";
        rs2.execute(newSql);
        rs2.next();
        String id = rs2.getString("id");
        for (String key : titleAndAddrMap.keySet()) {
            String insertDt1Sql = "insert into uf_wbfxsxxgl_dt1( mainid , ybdz,ybmc) values(" + id + ",'" + titleAndAddrMap.get(key) + "','" + key + "') ";
            insertDt1Rs.execute(insertDt1Sql);
        }
    }

    /**
     * 获取外部分析师信息
     */
    public List<Map<String, Object>> getWebfxs() {
        List<Map<String, Object>> apidatas = new ArrayList<>();
        RecordSet rsTable8 = new RecordSet();
        int startrow = 0;
        int hasData = 0;
        int dataCount = 0;
        List<Map<String, Object>> allDataList = new ArrayList<>();
        // 调接口获取所有外部分析师数据
        Map<String, Object> dataMap = getWbfxsData(String.valueOf(startrow), "ZX_RPTFELLOWOUTER", null);
        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 = getWbfxsData(String.valueOf(startrow), "ZX_RPTFELLOWOUTER", null);
                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);
                }
            }
        }

        // 获取最近一年的研报和研报评级数据
        List<Map<String, Object>> allDataList_yb = new ArrayList<>();
        allDataList_yb.addAll(getYb());

        // 遍历每一个外部分析师
        for (Map<String, Object> insertDataMap : allDataList) {
            String sinducode = (String) insertDataMap.get("SINDUCODE");
            // 机构名称
            String agencyname = (String) insertDataMap.get("AGENCYNAME");
            // 筛选：根据SINDUCODE=490100取行业为证券Ⅱ的研究员，AGENCYNAME为任职机构名称，剔除AGENCYNAME里含”华泰“两个字的
            if ("490100".equals(sinducode) && !agencyname.contains("华泰")) {
                Map<String, Object> resMap = new HashMap<>();
                // 研究员编码
                String fellowcode = (String) insertDataMap.get("FELLOWCODE");
                // 研究员姓名
                String fellowname = (String) insertDataMap.get("FELLOWNAME");
                // 到表8匹配出电话，邮箱
                String telnumber = "";
                String email = "";
                String sqlTable8 = "select telnumber,email from EXP_ANALYSTINFO where ANALYSTNAME =  '"+fellowname+"'";
                rsTable8.execute(sqlTable8);
                if (rsTable8.next()) {
                    telnumber = rsTable8.getString("telnumber");
                    email = rsTable8.getString("email");
                }

                // 根据研究员编码和姓名 获取获奖信息
                String ranking = "";
                List<Map<String, Object>> hjxxList = gethjxx(fellowname, fellowcode);
                if (CollectionUtils.isNotEmpty(hjxxList)) {
                    Map<String, Object> hjxxMap = hjxxList.get(0);
                    // 新财富排名，插入时：”新财富排名：xxx“
                    if (org.apache.commons.lang.StringUtils.isNotBlank(String.valueOf(hjxxMap.get("RANKING")))) {
                        ranking = Util.null2String(String.valueOf(hjxxMap.get("RANKING")));
                        if (org.apache.commons.lang.StringUtils.isNotBlank(ranking) && !"null".equals(ranking)) {
                            ranking = "新财富排名：" + ranking;
                        } else {
                            ranking = "";
                        }
                    }
                }

                // 根据研究员编码和姓名 匹配研报信息
                // 最近一年研报数量
                int recentYearYbCount = 0;
                // 研报编码
                String reportCode = "";
                // 标题
                String title = "";
                // 地址
                String address = "";
                // 存放研报名称和对应的研报地址
                Map<String, String> titleAndAddrMap = new HashMap<>();
                //当前评级名称
                String gradename = "";
                // 评级变化名称 即，与上期对比情况
                String ratingchangename = "";
                // 撰写日期  2022/05/20 07:31:36
                // 研报对应的研究员姓名和编码
                String fellowcode_yb = "";
                String fellowname_yb = "";

                // 遍历最近一年的研报
                for (Map<String, Object> ybMap : allDataList_yb) {
                    fellowcode_yb = (String) ybMap.get("FELLOWCODE");
                    fellowname_yb = (String) ybMap.get("FELLOWNAME");
                    //  筛选该研究员的研报
                    if (fellowname.equals(fellowname_yb) && fellowcode.equals(fellowcode_yb)) {
                        reportCode = (String) ybMap.get("REPORTCODE");
                        title = (String) ybMap.get("TITLE");
                        gradename = (String) ybMap.get("GRADENAME");
                        if (!org.apache.commons.lang.StringUtils.isNotBlank(gradename) || "null".equals(gradename)) {
                            gradename = "";
                        }
                        ratingchangename = (String) ybMap.get("RATINGCHANGENAME");
                        if (!org.apache.commons.lang.StringUtils.isNotBlank(ratingchangename) || "null".equals(ratingchangename)) {
                            ratingchangename = "";
                        }

                        // 根据研报编码 reportCode，获取地址。取出之后存到map中 titleAndAddrMap.put(title,地址)
                        String ybSql = "select FILEFULLPATH from RPT_CONTENT where REPORTCODE = '"+reportCode+"'";
                        rsTable8.executeQuery(ybSql);
                        if (rsTable8.next()){
                            address = "https://000283-datayes-news.s3.cn-northwest-1.amazonaws.com.cn/"+rsTable8.getString("FILEFULLPATH");
                        }
                        titleAndAddrMap.put(title, address);
                    }
                }
                recentYearYbCount = titleAndAddrMap.size();
                String uuid = UUID.randomUUID().toString();
                resMap.put("xm", fellowname);
                resMap.put("xmcode", fellowcode);
                resMap.put("dzyx", email);
                resMap.put("dh", telnumber);
                resMap.put("gxfzzd", fellowcode);
                resMap.put("rzjgmc", agencyname);
                resMap.put("dgszxpj", gradename);
                resMap.put("ysyqdbqk", ratingchangename);
                resMap.put("zjynybsl", recentYearYbCount);
                resMap.put("xgryhhjqk", ranking);
                resMap.put("uuid", uuid);
                resMap.put("modeuuid", uuid);
                resMap.put("titleAndAddrMap", titleAndAddrMap);
                apidatas.add(resMap);
            }
        }
        return apidatas;
    }

    /**
     * 获取研报和研报评级信息
     *
     * @return
     */
    public List<Map<String, Object>> getYb() {
        int startrow = 0;
        int hasData = 0;
        int dataCount = 0;
        List<Map<String, Object>> allDataList = new ArrayList<>();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.YEAR, -1);
        Date y = c.getTime();
        String beforeYear = sdf.format(y);

        // 查询撰写日期是最近一年的研报
        Map<String,Object> param = new HashMap<>();
        String[] rspDateArr = {"["+beforeYear+",]"};
        param.put("WRITEDATE",rspDateArr);

        // 调接口取数据
        Map<String, Object> dataMap = getWbfxsData(String.valueOf(startrow), "ZX_RPTFELLOWGRADE", 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 = getWbfxsData(String.valueOf(startrow), "ZX_RPTFELLOWGRADE", 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);
                }
            }
        }
        return allDataList;
    }

    /**
     * 根据研究员编码和姓名获取获奖信息
     *
     * @return
     */
    public List<Map<String, Object>> gethjxx(String name, String code) {
        int startrow = 0;
        int hasData = 0;
        int dataCount = 0;
        List<Map<String, Object>> allDataList = new ArrayList<>();
        Map<String, Object> param = new HashMap<>();
        // 指定华泰个股下的数据
        String[] nameArr = {name};
        String[] codeArr = {code};
        param.put("FELLOWNAME", nameArr);
        param.put("FELLOWCODE", codeArr);
        // 调接口取数据
        Map<String, Object> dataMap = getWbfxsData(String.valueOf(startrow), "ZX_RPTFELLOWRANKING", param);
        dataCount = (int) dataMap.get("dataCount");
        if (dataCount > 0) {
            List<Map<String, Object>> dataList = (List<Map<String, Object>>) dataMap.get("dataList");
            allDataList.addAll(dataList);
        }
        return allDataList;
    }

    /**
     * 外部分析师，调接口获取全部数据
     */
    public Map<String, Object> getWbfxsData(String startrow, String resource, Map<String, Object> param) {
        PropBean pb = new PropBean();
        HashMap<String, Object> map = new HashMap<>();
        HttpRequestUtil httpRequestUtil = new HttpRequestUtil();
        Map<String, Object> paramMap = new HashMap<>();
        String url = pb.getPropName("tgpt_zxzxUrl");
        String key = pb.getPropName("wbfxs_key");
        paramMap.put("key", key);
        paramMap.put("resource", resource);
        paramMap.put("startrow", startrow);
        paramMap.put("paramMaps", param);
        paramMap.put("rownum", "200");
        paramMap.put("orderBy", "");
        paramMap.put("selectedFields", null);
        String requestParams = JSONObject.toJSONString(paramMap);
        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);
        return map;
    }

}



