package com.template.common.utils;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.template.config.WxOpenidConfig;
import com.template.model.enumModel.eOrgType;
import com.template.model.pojo.AlumniOrg;
import com.template.model.pojo.WxAccessToken;
import com.template.model.response.organizationPageResponse;
import com.template.model.result.CommonResult;
import com.template.model.result.Wx_user;
import com.template.services.AlumniOrgService;
import com.template.services.WxAccessTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: binguo
 * @Date: 2023/8/1 星期二 8:50
 * @Description: com.repair.common.utils
 * @Version: 1.0
 */
@Component
public class WeiXiaoUtil {
    @Autowired
    private WxOpenidConfig wxOpenidConfig;
    @Autowired
    private WxAccessTokenService wxAccessTokenService;

    @Autowired
    private AlumniOrgService alumniOrgService;

    /**
     * 获取token
     *
     * @return
     */
    public String getApplicationToken() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.MINUTE, 1);
        String dateNow = sdf.format(nowTime.getTime());
        System.out.println();
        WxAccessToken aData = wxAccessTokenService.getRepairByDate(dateNow);
        if (aData != null) {
            return aData.getAccessToken();
        }

        Map<String, Object> jsonMap = doGetApplicationToken();
        String accessToken = jsonMap.get("access_token").toString();
        String expiresIn = jsonMap.get("expires_in").toString();
        System.out.println("accessToken：" + accessToken + "；expires_in：" + expiresIn);

        aData = new WxAccessToken();
        aData.setAccessToken(accessToken);
        Calendar newTime = Calendar.getInstance();
        newTime.add(Calendar.SECOND, Integer.valueOf(expiresIn));
        aData.setExpiresTime(newTime.getTime());

        wxAccessTokenService.insertwxAccessToken(aData);
        return accessToken;
    }

    /**
     * 发送通知
     *
     * @param cards   卡号集合
     * @param digest  摘要
     * @param title   通知标题
     * @param content 通知内容
     * @param customs 自定义参数，长度为2，分别为提示文案和通知跳转链接
     */
    public CommonResult sendNotice(List<String> cards, String digest, String title, String content, List<String> customs) {
        String uri = "https://open.wecard.qq.com/cgi-bin/notice/send?access_token=" + getApplicationToken();
        Map<String, String> params = new HashMap<>();

        try {
            ObjectMapper mapper = new ObjectMapper();
            params.put("cards", mapper.writeValueAsString(cards));
            params.put("title", title);
            params.put("content", content);
            params.put("sender", "校友生态系统");
            params.put("digest", digest);
            if (customs != null && customs.size() == 2) {
                params.put("customs", mapper.writeValueAsString(customs));
            }

            RestTemplate client = new RestTemplate();
            ResponseEntity<String> tokenResponse = client.postForEntity(uri, params, String.class);
            String body = tokenResponse.getBody();
            //log.info("微校发送通知返回结果【{}】", body);
            System.out.println("微校发送通知返回结果：" + body);
            return CommonResult.ok("操作成功");
        } catch (Exception e) {
            System.out.println("微校发送通知错误：" + e.getMessage());
            //log.error("微校发送通知错误【{}】", e.getMessage());
            return CommonResult.fail("操作失败");
        }
    }

    /**
     * 获取部门
     */
    public CommonResult queryOrgs()  {
        String uri = "https://open.wecard.qq.com/cgi-bin/user/org-edu-list?access_token=" + getApplicationToken();
        Map<String, String> params = new HashMap<>();
        try {
            params.put("page", "1");
            params.put("page", "5000");
            RestTemplate client = new RestTemplate();
            ResponseEntity<String> tokenResponse = client.postForEntity(uri, params, String.class);
            String body = tokenResponse.getBody();
            System.out.println("获取部门组织返回结果：" + body);
            JSONObject jsonObject = JSONObject.parseObject(body);
            JSONArray jsonArray = jsonObject.getJSONArray("organization");
            List<organizationPageResponse> orgs = jsonArray.toJavaList(organizationPageResponse.class);
            //校友组织id：781933
            //离职校友：777239
            //教职工：573084
            //第0级：校友
            //第一级：学院
            //第二级：学段
            //第三级：专业
            //第四级：班级
            List<AlumniOrg> orgDatas = alumniOrgService.queryAlumniOrg();
            List<AlumniOrg> aos = new ArrayList<>();

            List<Integer> ids = new ArrayList<>();
            ids.add(781933);
            ids.add(573084);
            for (Integer id:ids ) {
                //父级
                Optional<AlumniOrg> existParentCount = orgDatas.stream().filter(e -> e.getId().intValue() == id.intValue()).findFirst();
                if(!(existParentCount != null && existParentCount.isPresent())){
                    Optional<organizationPageResponse> firstOrgs = orgs.stream().filter(e -> e.getId().intValue() == id.intValue()).findFirst();
                    if(firstOrgs != null && firstOrgs.isPresent()){
                        AlumniOrg fao = new AlumniOrg();
                        fao.setId(firstOrgs.get().getId());
                        fao.setName(firstOrgs.get().getName());
                        fao.setParentId(firstOrgs.get().getParent_id());
                        fao.setTypeId(0);
                        aos.add(fao);
                    }

                }
                //第一级
                List<organizationPageResponse> firstOrgs = orgs.stream().filter(e -> e.getParent_id().intValue() == id).collect(Collectors.toList());
                for (organizationPageResponse fo : firstOrgs) {
                    long existCount = orgDatas.stream().filter(e -> e.getId().intValue() == fo.getId().intValue()).count();
                    if (existCount <= 0) {
                        AlumniOrg fao = new AlumniOrg();
                        fao.setId(fo.getId());
                        fao.setName(fo.getName());
                        fao.setParentId(fo.getParent_id());
                        fao.setTypeId(eOrgType.College.getValue());
                        aos.add(fao);
                    }
                    //第二级
                    List<organizationPageResponse> SecordOrgs = orgs.stream().filter(e -> e.getParent_id().intValue() == fo.getId().intValue()).collect(Collectors.toList());
                    for (organizationPageResponse so : SecordOrgs) {
                        long sexistCount = orgDatas.stream().filter(e -> e.getId().intValue() == so.getId().intValue()).count();
                        if (sexistCount <= 0) {
                            AlumniOrg sao = new AlumniOrg();
                            sao.setId(so.getId());
                            sao.setName(so.getName());
                            sao.setParentId(so.getParent_id());
                            sao.setTypeId(eOrgType.Period.getValue());
                            aos.add(sao);
                        }
                        //第三级
                        List<organizationPageResponse> ThirdOrgs = orgs.stream().filter(e -> e.getParent_id().intValue() == so.getId().intValue()).collect(Collectors.toList());
                        for (organizationPageResponse to : ThirdOrgs) {
                            long texistCount = orgDatas.stream().filter(e -> e.getId().intValue() == to.getId().intValue()).count();
                            if (texistCount <= 0) {
                                AlumniOrg tao = new AlumniOrg();
                                tao.setId(to.getId());
                                tao.setName(to.getName());
                                tao.setParentId(to.getParent_id());
                                tao.setTypeId(eOrgType.Major.getValue());
                                aos.add(tao);
                            }
                            //第四级
                            List<organizationPageResponse> FourthOrgs = orgs.stream().filter(e -> e.getParent_id().intValue() == to.getId().intValue()).collect(Collectors.toList());
                            for (organizationPageResponse foo : FourthOrgs) {
                                long fexistCount = orgDatas.stream().filter(e -> e.getId().intValue() == foo.getId().intValue()).count();
                                if (fexistCount <= 0) {
                                    AlumniOrg foao = new AlumniOrg();
                                    foao.setId(foo.getId());
                                    foao.setName(foo.getName());
                                    foao.setParentId(foo.getParent_id());
                                    foao.setTypeId(eOrgType.ClassStr.getValue());
                                    aos.add(foao);
                                }
                            }
                        }
                    }
                }
            }

            if(aos != null && aos.size() > 0){
                boolean insertBatch = alumniOrgService.saveBatch(aos);
                if(!insertBatch){
                    return CommonResult.fail("操作失败");
                }
            }

            return CommonResult.ok("操作成功");
        } catch (Exception e) {
            System.out.println("获取部门组织错误：" + e.getMessage());
            //log.error("微校发送通知错误【{}】", e.getMessage());
            return CommonResult.fail("操作失败");
        }
    }


    /**
     * 获取部门
     */
    public CommonResult queryUserInfos(String cardNumber)  {
        String uri = "https://open.wecard.qq.com/cgi-bin/user/search?access_token=" + getApplicationToken();
        Map<String, String> params = new HashMap<>();
        Wx_user result = new Wx_user();
        try {
            params.put("keywords", cardNumber);
            RestTemplate client = new RestTemplate();
            ResponseEntity<String> tokenResponse = client.postForEntity(uri, params, String.class);
            String body = tokenResponse.getBody();
            System.out.println("获取用户信息返回结果：" + body);
            JSONObject jsonObject = JSONObject.parseObject(body);
            JSONArray jsonArray = jsonObject.getJSONArray("userlist");
            if(jsonArray != null && jsonArray.size() > 0){
                Gson gson = new Gson();
                result = gson.fromJson(jsonArray.getString(0), new TypeToken<Wx_user>() {
                }.getType());
            }

            //List<Wx_user> users = jsonArray.toJavaList(Wx_user.class);

            return CommonResult.ok(result);
        } catch (Exception e) {
            System.out.println("获取用户信息错误：" + e.getMessage());
            //log.error("微校发送通知错误【{}】", e.getMessage());

        }
        return CommonResult.fail("获取用户信息失败");
    }


    /**
     * 获取token
     *
     * @return
     */
    private Map<String, Object> doGetApplicationToken() {
        String uri = "https://open.wecard.qq.com/cgi-bin/oauth2/token";

        // 构建请求参数
        Map<String, String> tokenParams = new HashMap<>();
        tokenParams.put("app_key", wxOpenidConfig.getAppid());
        tokenParams.put("app_secret", wxOpenidConfig.getAppkey());
        tokenParams.put("grant_type", "client_credentials");
        tokenParams.put("scope", "base");
        tokenParams.put("ocode", wxOpenidConfig.getOcode());

        try {
            RestTemplate client = new RestTemplate();
            ResponseEntity<String> tokenResponse = client.postForEntity(uri, tokenParams, String.class);
            String body = tokenResponse.getBody();
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> jsonMap = mapper.readValue(body, new TypeReference<Map<String, Object>>() {
            });


            return jsonMap;
        } catch (Exception e) {
            String sss = e.getMessage();
        }
        return null;
    }


}
