package com.engine.web.Avatar;


import com.alibaba.fastjson.JSONObject;
import com.engine.cube.util.InterfaceUtil;
import lombok.extern.slf4j.Slf4j;
import tebie.applib.api.O;
import weaver.conn.RecordSet;
import weaver.general.StringUtil;
import weaver.general.Util;


import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
public class Avatar  {

    private static Pattern pattern = Pattern.compile("^[0-9,]+$");

    @Path("/getAvatarList")
    @POST
    @Produces("application/json")
    public String newMeet(@Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException {
        try {
            InterfaceUtil interfaceUtil = new InterfaceUtil();
            JSONObject requestJson = getJson(request);
            log.error("请求参数"+requestJson);
            //验证权限
            JSONObject header = requestJson.getJSONObject("header");
            RecordSet rs = new RecordSet();
            String interfaceConfigId = "";
            rs.executeQuery("select id from CubeInterfaceConfig where interfacePK=?", "getAvatarList");
            if (rs.next()) {
                interfaceConfigId = rs.getString("id");
            }
            interfaceUtil.checkHeaderNode(header, interfaceConfigId);
            //验证权限完成,处理业务
            JSONObject body = requestJson.getJSONObject("body");
            log.error("请求参数body"+body);
            String workcode = body.getString("workcode");
            if (StringUtil.isEmpty(workcode)) {
                return getResultStr("1", "工号为空", null);
            }
            //判断下工号是否为数字,含其他字符报错,防止下sql注入
            if (!containsOnlyDigitsAndCommas(workcode)) {
                return getResultStr("1", "工号只能为数字", null);
            }
            List<String> workcodeList = Arrays.asList(workcode.split(","));
            List<String> workcodeStrList = workcodeList.stream()
                    .map(item -> "'" + item + "'")
                    .collect(Collectors.toList());
            // 封装数据
            ArrayList<Map<String, String>> dataList = new ArrayList<>();
            rs.executeQuery("select WORKCODE ,LASTNAME ,MESSAGERURL from HRMRESOURCE where LOGINID in ( " + String.join(",",workcodeStrList) + ")");
            log.error("头像sql"+"select WORKCODE ,LASTNAME ,MESSAGERURL from HRMRESOURCE where LOGINID in ( " + String.join(",",workcodeStrList) + ")");

            while (rs.next()) {
                HashMap<String, String> data = new HashMap<>();
                data.put("LASTNAME", Util.null2String(rs.getString("LASTNAME")));
                data.put("WORKCODE", Util.null2String(rs.getString("WORKCODE")));
                data.put("MESSAGERURL", Util.null2String(rs.getString("MESSAGERURL")));
                dataList.add(data);
            }
            return getResultStr("0", "", dataList);
        } catch (Exception e) {
            log.error("错误"+e.getMessage());
            e.printStackTrace();
            return getResultStr("0", e.getMessage(), null);
        }

    }

    public static JSONObject getJson(HttpServletRequest request) throws IOException {
        //从前端获取输入字节流
        ServletInputStream requestInputStream = request.getInputStream();
        //将字节流转换为字符流,并设置字符编码为utf-8
        InputStreamReader ir = new InputStreamReader(requestInputStream, "utf-8");
        //使用字符缓冲流进行读取
        BufferedReader br = new BufferedReader(ir);
        StringBuilder sb = new StringBuilder();
        try {
            //开始拼装json字符串
            String line = null;

            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            requestInputStream.close();
            ir.close();
            br.close();
        }
        JSONObject json = JSONObject.parseObject(sb.toString());
        return json;
        // StringBuilder stringBuilder = new StringBuilder();
        // BufferedReader reader = request.getReader();
        // try {
        //     String line;
        //     while ((line = reader.readLine()) != null) {
        //         stringBuilder.append(line).append('\n');
        //     }
        // } finally {
        //     reader.close();
        // }
        // return JSONObject.parseObject(stringBuilder.toString()) ;
    }

    //
    public static String getResultStr(String status, String msg, List<Map<String, String>> list) {
        HashMap<String, Object> result = new HashMap<>();
        result.put("status", status);
        result.put("msg", msg);
        if (list != null) {
            result.put("data", list);
        }
        return JSONObject.toJSONString(result);
    }


    public static boolean containsOnlyDigitsAndCommas(String input) {
        // 使用正则表达式来匹配只包含数字和英文逗号的字符串
        Matcher matcher = pattern.matcher(input);
        return matcher.matches();
    }

    public static void main(String[] args) {
        ArrayList<Map<String, String>> dataList = new ArrayList<>();
        HashMap<String, String> data = new HashMap<>();
        data.put("LASTNAME", Util.null2String("LASTNAME"));
        data.put("WORKCODE", Util.null2String("WORKCODE"));
        data.put("MESSAGERURL", Util.null2String("MESSAGERURL"));
        dataList.add(data);

        System.out.println(getResultStr("0","1111",dataList));
    }

}
