package com.bcxin.backend.domain.screening.service.impl;


import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bcxin.backend.domain.models.Result;
import com.bcxin.backend.domain.models.ScreeningDTO;
import com.bcxin.backend.domain.screening.service.BackgrounpScreeningProvider;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;


/**
 * <b> 背筛接口访问实现 湖南</b>
 *
 * @author ZXF
 * @create 2022/09/22 0022 15:10
 * @注意事项 </b>
 */
@Slf4j
@Component("bsp_hunan")
public class BackgrounpScreeningProviderHunanImpl implements BackgrounpScreeningProvider {

    @Autowired
    @Qualifier("primaryJdbcTemplate")
    protected JdbcTemplate jdbcTemplate;

    @Value("${myapps.screeninng.api}")
    private String baseUrl;//背景筛查接口url

    //调用背景筛查接口（实际调用的是认证服务提供的背景筛查接口，认证服务调核查库接口）
    public JSONObject getScreenOfAuth(String idnum) {
        HttpResponse execute = HttpUtil.createGet(baseUrl + idnum).execute();
        if (execute.isOk()) {
            //test
            /**
             * 湖南背筛有问题的结果返回值

            String testBody = "{\n" +
                    "    \"successful\": true,\n" +
                    "    \"code\": 0,\n" +
                    "    \"message\": \"请求成功\",\n" +
                    "    \"data\":{\"idNumber\": \"652322198609074012\",\n" +
                    "    \"censorResult\": [{\"code\": 200,\"data\": null,\"wffzry\": null,\"result\": 0,\n" +
                    "                      \"cxxt\": \"湖南省公安厅拘留所出入所人员信息\"},\n" +
                    "      {\"code\": 200,\"data\": null,\"wffzry\": null,\"result\": 1,\n" +
                    "      \"cxxt\": \"湖南省涉毒人员信息\"},\n" +
                    "      {\"code\": 200,\"data\": {\"AJLB\": \"01000000/\",\"LASSXQ\": \"\",\"SFZH\": \"xxxxxxxxxxx\",\n" +
                    "      \"DBJB\": \"\",\"XB\": \"1/男\",\"RYBH\": \"T6530010500002017101279\",\"CSRQ\": \"19870102\",\n" +
                    "      \"XZXXDZ\": \"xxxxxxxxxx\",\"AJBH\": \"A6530011009992017100239\",\"LXRDH\": \"13345378866\",\n" +
                    "      \"SG\": \"\", \"XM\": \"xxxxxxx\",\"HJDSSXQ\": \"xxxxxxxx\",\"XP\": \"\",\"GNTJBH\": \"\",\n" +
                    "      \"LADWMC\": \"阿图什市公安局\",\"TPRQ\": \"2017-06-07 00:00:00\",\"HYKY\": \"650000/新疆口音\",\n" +
                    "      \"JYAQ\": \"xxxxxxxx\",\"XZSSXQ\": \"xxxxxxx\"}},\n" +
                    "      {\"code\": 200,\"wffzry\": [{\n" +
                    "      \"HJDQH\": \"360721\",\n" +
                    "      \"AJLB\": \"05010300\",\n" +
                    "      \"SFZH\": \"xxxxxx\",\n" +
                    "      \"RSYY\": \"11\",\n" +
                    "      \"ZC\": \"25\",\n" +
                    "      \"XB\": \"1\",\n" +
                    "      \"JZDXZ\": \"xxxxxx\",\n" +
                    "      \"MZ\": \"01\",\n" +
                    "      \"CSYY\": \"01\",\n" +
                    "      \"CSRQ\": \"1999-01-01 00:00:00\",\n" +
                    "      \"AJBH\": \"14781257\",\n" +
                    "      \"SF\": \"09\",\n" +
                    "      \"SG\": \"170\",\n" +
                    "      \"XM\": \"xxxx\",\n" +
                    "      \"CYM\": \"无\",\n" +
                    "      \"RKSJ\": \"2021-02-09 19:23:34\",\n" +
                    "      \"JZDQH\": \"360721\",\n" +
                    "      \"XMPY\": \"\",\n" +
                    "      \"XP\": \"360124111202009230003\",\n" +
                    "      \"WHCD\": \"20\",\n" +
                    "      \"JYAQ\": \"xxxxxx\",\n" +
                    "      \"ZHUANC\": \"90\",\n" +
                    "      \"HJDXZ\": \"xxxxxx\"\n" +
                    "      }\n" +
                    "      ]\n" +
                    "      },\n" +
                    "      {\n" +
                    "      \"code\": 200,\n" +
                    "      \"data\": null,\n" +
                    "      \"wffzry\": null,\n" +
                    "      \"result\": 0,\n" +
                    "      \"cxxt\": \"获取湖南省情报重点人员信息\"\n" +
                    "      },\n" +
                    "      {\n" +
                    "      \"code\": 200,\n" +
                    "      \"data\": null,\n" +
                    "      \"wffzry\": null,\n" +
                    "      \"result\": 0,\n" +
                    "      \"cxxt\": \"湖南省工作对象信息\"\n" +
                    "      },\n" +
                    "      {\n" +
                    "      \"code\": 200,\n" +
                    "      \"data\": null,\n" +
                    "      \"wffzry\": null,\n" +
                    "      \"result\": 0,\n" +
                    "      \"cxxt\": \"湖南省公安厅看守所出入所人员信息\"\n" +
                    "      },\n" +
                    "      {\n" +
                    "      \"code\": 200,\n" +
                    "      \"data\": null,\n" +
                    "      \"wffzry\": null,\n" +
                    "      \"result\": 0,\n" +
                    "      \"cxxt\": \"湖南省执法办案违法人员信息(行政)\"\n" +
                    "      },\n" +
                    "      {\n" +
                    "      \"code\": 200,\n" +
                    "      \"data\": null,\n" +
                    "      \"wffzry\": null,\n" +
                    "      \"result\": 0,\n" +
                    "      \"cxxt\": \"湖南省公安厅戒毒所出入所人员信息\"\n" +
                    "      },\n" +
                    "      {\n" +
                    "      \"code\": 200,\n" +
                    "      \"data\": null,\n" +
                    "      \"wffzry\": null,\n" +
                    "      \"result\": 1,\n" +
                    "      \"cxxt\": \"湖南省执法办案违法人员信息(刑事)\"\n" +
                    "      },\n" +
                    "      {\n" +
                    "      \"code\": 200,\n" +
                    "      \"data\": null,\n" +
                    "      \"wffzry\": null,\n" +
                    "      \"result\": 0,\n" +
                    "      \"cxxt\": \"湖南省吸毒人员信息\"\n" +
                    "      }\n" +
                    "      ]\n" +
                    "      }}";
             */
            /**
             * 湖南背筛没问题的结果返回值

             String testBody = "{\n" +
             "    \"successful\": true,\n" +
             "    \"code\": 0,\n" +
             "    \"message\": \"请求成功\",\n" +
             "    \"data\":[]}";
             */
            JSONObject screenValue;
            //test
            //screenValue = JSONObject.parseObject(testBody);
            screenValue = JSON.parseObject(execute.body());
            return screenValue;

        }
        return null;
    }

    //处理背景筛查接口返回值（实际调用的是认证服务提供的背景筛查接口，认证服务调核查库接口）
    public ScreeningDTO getScreen(String idnum,List<String> logList) {
        //接收背筛接口返回值中的data
        JSONObject dataJson;
        //调用背景筛查接口
        JSONObject screenValue = getScreenOfAuth(idnum);
        String replaceScreenValue;
        //报文日志记录（bg_screening_user_exec_logs） 通过调setLogList()可以添加多次日志报文

        if (!ObjectUtils.isEmpty(screenValue)) {
            if (ObjectUtils.isEmpty(screenValue.get("data"))) {//data为空则人员没问题
                replaceScreenValue = JSON.toJSONString(screenValue).replace("\"", "\\\"");
                setLogList(logList, "2", idnum, null, replaceScreenValue);
                return new ScreeningDTO(idnum, "0", "");
            } else {//人员有问题，处理结果集
                dataJson = (JSONObject) screenValue.get("data");
                String hnProblemData = "公安部在逃人员";
                String hnProblemWffzry = "公安部违法犯罪人员";
                List<String> questiontypeList = new ArrayList<>();//问题类型List

                if (!ObjectUtils.isEmpty(dataJson.get("censorResult"))) {//获取湖南背景筛查，背筛内容

                    String censorResultArry = dataJson.get("censorResult").toString();
                    JSONArray jsonArray = JSONArray.parseArray(censorResultArry);
                    String data;
                    String wffzry;
                    JSONObject object;
                    //遍历censorResult，取值
                    for (int i = 0; i < jsonArray.size(); i++) {
                        object = jsonArray.getJSONObject(i);

                        //dataJson中的data、wffzry的值可能为null，json中可能不显示对应的键
                        if (object.containsKey("data")) {
                            data = object.get("data").toString();
                            //date不为null，返回值为map，data结果是{}，不为公安部在逃人员，反之则为公安部在逃人员
                            if (!ObjectUtils.isEmpty(data) && !data.equals("null")) {
                                JSONObject dJson = (JSONObject) object.get("data");
                                if (dJson.containsKey("detail")) {
                                    String detail = dJson.get("detail").toString();
                                    if (!ObjectUtils.isEmpty(detail) && !detail.equals("null")) {
                                        questiontypeList.add(detail);
                                    }
                                }
                            }
                        }
                        if (object.containsKey("wffzry")) {
                            wffzry = object.get("wffzry").toString();
                            //wffzry不为null，类型是数组, 空数组即不为公安部违法犯罪人员，反之则为公安部违法犯罪人员
                            if (!ObjectUtils.isEmpty(wffzry) && !wffzry.equals("null")) {
                                questiontypeList.add(hnProblemWffzry);
                            }
                        }
                        if (object.containsKey("result") || object.containsKey("cxxt")) {
                            String result = object.get("result").toString();
                            String cxxt = object.get("cxxt").toString();

                            if (!ObjectUtils.isEmpty(result) && !result.equals("null") && !result.equals("0")
                                    && !ObjectUtils.isEmpty(cxxt) && !cxxt.equals("null")) {
                                questiontypeList.add(cxxt);
                            }
                        }
                    }
                }else{
                    replaceScreenValue = JSON.toJSONString(screenValue).replace("\"", "\\\"");
                    setLogList(logList, "2", idnum, null, replaceScreenValue);
                    return new ScreeningDTO(idnum, "0", "");
                }
                replaceScreenValue = JSON.toJSONString(screenValue).replace("\"", "\\\"");
                setLogList(logList, "2", idnum, questiontypeList.toString().replace("[", "").replace("]", ""), replaceScreenValue);
                return new ScreeningDTO(idnum, "1", questiontypeList.toString().replace("[", "").replace("]", ""));
            }
        }
        return null;
    }

    /**
     * <b> 单个身份证背筛 </b>
     * 返回结果定义：Result 里面有fail() success() 快捷方法直接使用
     * Result.retType 放接口请求是否成功编码
     * Result.data 放下面json格式
     * [{"isProblem":"0/1","detail":"吸毒人员,在逃嫌疑犯","idnum":"1111"}]
     *
     * @author ZXF
     * @create 2022/09/22 0022 15:33
     * @version
     * @注意事项 </b>
     */
    @Override
    public Result<ScreeningDTO> screening(String idnum) {
//        报文日志记录（bg_screening_user_exec_logs） 通过调setLogList()可以添加多次日志报文
//        List<String> logList = new ArrayList<>();
//        setLogList(logList,"背景筛查","350621199901210770","1","xxxx");
//        setLogList(logList,"背景筛查","350621199001210766","1","nnn");
//        setLogList(logList,"背景筛查","350621198501218075","1","mmm");
//        saveLog(logList);
        List<String> logList = new ArrayList<>();
        ScreeningDTO screenOfAuth = getScreen(idnum,logList);
        saveLog(logList);
        return new Result().success(Result.SUCCESS_MSG, screenOfAuth);
    }


    /**
     * <b> 多个身份证背筛 </b>
     * 返回结果定义：Result 里面有fail() success() 快捷方法直接使用
     * Result.retType 放接口请求是否成功编码
     * Result.data 放下面json格式 （isProblem 0没问题1有问题 ，0时detail可以为空，1时detail不为空，idnum始终不能为空）
     * [{"isProblem":"0/1","detail":"吸毒人员,在逃嫌疑犯","idnum":"1111"},{"isProblem":"0/1","detail":"吸毒人员,在逃嫌疑犯","idnum":"222"}]
     *
     * @author ZXF
     * @create 2022/09/22 0022 15:33
     * @version
     * @注意事项 </b>
     */
    @Override
    public Result<List<ScreeningDTO>> screenings(String[] idnums) {

//        报文日志记录（bg_screening_user_exec_logs） 通过调setLogList()可以添加多次日志报文
//        List<String> logList = new ArrayList<>();
//        setLogList(logList,"背景筛查","350621199901210770","1","xxxx");
//        setLogList(logList,"背景筛查","350621199001210766","1","nnn");
//        setLogList(logList,"背景筛查","350621198501218075","1","mmm");
//        saveLog(logList);

        //调用背景筛查接口方法(该接口由实名认证服务提供，实名认证服务调用的才是真正的人口核查库)
        List<ScreeningDTO> list = Lists.newArrayList();
        List<String> logList = new ArrayList<>();
        ScreeningDTO screeningDTO = null;
        for (String idnum : idnums) {
            screeningDTO = getScreen(idnum,logList);
            if(screeningDTO == null){
                continue;
            }
            list.add(screeningDTO);
        }
        saveLog(logList);
        return new Result().success(Result.SUCCESS_MSG, list);
    }

    /**
     * <b> 日志sql组装多次数据 </b>
     *
     * @author ZXF
     * @create 2022/09/22 0022 16:58
     * @version
     * @注意事项 </b>
     */
    private void setLogList(List<String> list, String type, String idnum, String short_result, String result) {
        list.add("( '" + type + "',NOW(),'" + idnum + "','" + short_result + "','" + result + "' )");
    }

    /**
     * <b> 日志sql组装后保存 </b>
     *
     * @author ZXF
     * @create 2022/09/22 0022 16:58
     * @version
     * @注意事项 </b>
     */
    private void saveLog(List<String> list) {
        if(list.size()>0){
            String lStr = list.toString();
            StringBuilder sb = new StringBuilder();
            sb.append("INSERT INTO bg_screening_user_exec_logs (type,created_time,idnum,short_result,result) values" + lStr.substring(1,lStr.length()-1));
            jdbcTemplate.update(sb.toString());
        }
    }

}
