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 java.util.*;
import java.util.stream.Collectors;

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

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

    String isProblem="1";
    @Value("${myapps.screeninng.api}")
    private  String BaseUrl;

    private ScreeningDTO getScreeningDTO(String idnum,List<String> logList){
        String detail="";//for 循环进来后会被重新赋值

        HttpResponse execute = HttpUtil.createGet(BaseUrl + idnum).execute();
        if (execute.isOk()) {//ture
            JSONObject jsonObject = JSON.parseObject(execute.body());//body转换json对象
            if (!(jsonObject.get("data")==null)) {//判断data是否为空
                JSONObject dataJson = (JSONObject) jsonObject.get("data");
                String censorResult = dataJson.get("censorResult").toString();
                if (censorResult.equals("[]")){
                    isProblem="0";//没问题
                    detail="";//无犯罪详情
                }else {
                    isProblem="1";
                    JSONArray censorArry = JSONArray.parseArray(censorResult);
                    for (int i = 0; i < censorArry.size(); i++) {
                        JSONObject object = (JSONObject) censorArry.get(i);
                        JSONObject data = (JSONObject) object.get("data");
                        detail+=data.get("detail").toString()+",";//拿到第一个detail
                    }
                    if (detail.length()>0){
                        detail=detail.substring(0,detail.length()-1);
                    }
                }

            }else{//data返回值为null
                isProblem="0";//没问题
                detail="";//无犯罪详情
            }
        }else{
            return null;
        }
        setLogList(logList,"2",idnum,detail,execute.body());
        return new ScreeningDTO(idnum,isProblem,detail);
    }
    /**
     * <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 screening(String idnum) {
//        报文日志记录（bg_screening_user_exec_logs） 通过调setLogList()可以添加多次日志报文
//        setLogList(logList,"背景筛查","350621199901210770","1","xxxx");
//        saveLog(logList);
        List<String> logList = new ArrayList<>();
        ScreeningDTO screeningDTO=this.getScreeningDTO(idnum,logList);
        //设置日志
        saveLog(logList);

        return new Result().success(Result.SUCCESS_MSG,screeningDTO);
    }

    /**
     * <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<String> logList = new ArrayList<>();
        List<ScreeningDTO> list = Lists.newArrayList();
        ScreeningDTO screen;
        for (String idnum : idnums) {
            screen=this.getScreeningDTO(idnum,logList);
            if(screen == null){
                continue;
            }
            list.add(screen);
        }
        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());
        }
    }
}
