package com.dkl.web.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.dkl.common.core.controller.BaseController;
import com.dkl.common.core.domain.entity.SysDept;
import com.dkl.common.core.domain.entity.SysUser;
import com.dkl.common.core.domain.model.LoginUser;
import com.dkl.common.core.redis.RedisCache;
import com.dkl.common.utils.SecurityUtils;
import com.dkl.common.utils.StringUtils;
import com.dkl.system.service.ISysDeptService;
import com.dkl.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import okhttp3.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Component("obtainOutAll")
public class ObtainOutAll extends BaseController {


    @Autowired
    private RedisCache redisCache;

    @Autowired
    private BackendServiceToken backendServiceToken;

    @Autowired
    private ISysUserService userService;


    @Autowired
    private ISysDeptService deptService;

    @Value("${outData.url}")
    String outUrl;
    @Value("${outData.password}")
    String password;
    //获取用户
    public void getUserAll(String identification)
    {

        int deptId = 103;
        long deptInfo = deptId; // 自动转换为long

        int roleId=  2;
        long roleInfo=  roleId;
        OkHttpClient client = new OkHttpClient();
        System.out.println("getUserAll");
        //获取用户缓存信息
        SysUser user = userService.selectUserByUserName(identification);
        //判断 key是否存在
        //以身份证为key 判断redis中是否还有
        if(!redisCache.hasKey(user.getGmsfhm())){
            //没有token获取token
            backendServiceToken.subsystemToken(user.getPhonenumber());
        }
        //获取token
        String tokens = redisCache.getCacheObject(user.getPhonenumber());
        //开始获取用户
        // 构建请求体
        String json = "{\"entity\":{}}"; // 根据实际需求调整JSON内容
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        // 构建请求
        Request request = new Request.Builder()
                .url(outUrl+"/ht/system/sysUser/query")
                .post(body)
                .addHeader("Authorization", "Bearer "+tokens) // 替换YOUR_TOKEN
                .build();
        // 发送请求并处理响应
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                String jsonString = response.body().string();
                System.out.println(jsonString);
                // 创建ObjectMapper实例
                ObjectMapper objectMapper = new ObjectMapper();
                try {

                    // 解析JSON字符串为JsonNode对象
                    JsonNode rootNode = objectMapper.readTree(jsonString);

                    // 获取code字段的值
                    String code = rootNode.get("code").asText();
                    System.out.println("Code: " + code);

                    // 获取success字段的值
                    boolean success = rootNode.get("success").asBoolean();
                    System.out.println("Success: " + success);

                    // 获取data字段的值（是一个数组）
                    JsonNode dataNode = rootNode.get("data");

                    // 遍历data数组中的每个元素
                    for (JsonNode userNode : dataNode) {
                        // 获取每个用户的ywlsh字段的值
                        SysUser sysUser = new SysUser();
                        SysUser   userInfo  =new SysUser();
                        //用户唯一标识
//                        if(StringUtils.isNotEmpty( userNode.get("yhwybs").asText())){
//                            //根据用户唯一标识 判断系统是否有
//                          userInfo  = userService.selectUserByYhwybs(userNode.get("yhwybs").asText());
//                         if(userInfo!=null){
//                             sysUser = userInfo;
//                         }
//                        }

                        //登录账号 = 对接用户名 yhm
                        if(StringUtils.isNotEmpty( userNode.get("yhm").asText())){
                            sysUser.setUserName(userNode.get("yhm").asText());
                        }
                        //用户昵称 = 对接姓名 xm
                        if(StringUtils.isNotEmpty( userNode.get("xm").asText())){
                            sysUser.setNickName(userNode.get("xm").asText());
                        }
                        //登录账号 = 对接用户名 yhm
                        if(StringUtils.isNotEmpty( userNode.get("yhm").asText())){
                            sysUser.setUserName(userNode.get("yhm").asText());
                        }

                        //手机号码 = 对接 手机号码  yddh
                        if(StringUtils.isNotEmpty( userNode.get("yddh").asText())){
                            sysUser.setPhonenumber(userNode.get("yddh").asText());
                        }

                        //用户性别（0男 1女 2未知 =对接性别编码 xbdm
                        if(StringUtils.isNotEmpty( userNode.get("xbdm").asText())){
                            sysUser.setSex(userNode.get("xbdm").asText());
                        }
                        //帐号状态（0正常 1停用）
                        sysUser.setStatus("0");
                        //删除状态
                        sysUser.setDelFlag("0");
                        //创建时间
                        sysUser.setCreateTime(new Date());
                        //创建人
                        sysUser.setCreateBy("admin");
                        //修改时间
                        sysUser.setUpdateTime(new Date());
                        //修改人
                        sysUser.setUpdateBy("admin");
                            sysUser.setRoleId(roleInfo);
                             sysUser.setDeptId(deptInfo);
                        //对接新增公民身份号
                        if(StringUtils.isNotEmpty( userNode.get("gmsfhm").asText())){
                            sysUser.setGmsfhm(userNode.get("gmsfhm").asText());
                        }

                        //对接工号
                        if(StringUtils.isNotEmpty( userNode.get("jh").asText())){
                            sysUser.setJh(userNode.get("jh").asText());
                        }

                        //用户唯一标识
                        if(StringUtils.isNotEmpty( userNode.get("yhwybs").asText())){
                            sysUser.setYhwybs(userNode.get("yhwybs").asText());
                        }

                        //对接居住地行政区划代码
                        if(StringUtils.isNotEmpty( userNode.get("jzdxzqhdm").asText())){
                            sysUser.setJzdxzqhdm(userNode.get("jzdxzqhdm").asText());
                        }
                        sysUser.setPassword(SecurityUtils.encryptPassword(password));

                            userService.insertUser(sysUser);


                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                throw new IOException("Unexpected code " + response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //获取部门
    public void getDeptAll(String identification){

        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(100000, TimeUnit.SECONDS)  // 连接超时
                .readTimeout(30000, TimeUnit.SECONDS)     // 读取超时
                .writeTimeout(30000, TimeUnit.SECONDS)    // 写入超时
                .build();

        System.out.println("getDeptAll");
        //获取用户缓存信息
//        LoginUser user = SecurityUtils.getLoginUser();
        SysUser user = userService.selectUserByUserName(identification);
        //判断 key是否存在
        //以身份证为key 判断redis中是否还有
        if(!redisCache.hasKey(user.getGmsfhm())){
            //没有token获取token
            backendServiceToken.subsystemToken(user.getPhonenumber());
        }
        //获取token
        String tokens = redisCache.getCacheObject(user.getPhonenumber());
        //开始获取用户
        // 构建请求体
//        String json = "{\"entity\":{}}"; // 根据实际需求调整JSON内容
//        String json = "{\"entity\":{},\"offset\":18,\"limit\":1000}";
        String json = "{\"entity\":{},\"page\":5,\"limit\":\"2500\"}";

        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        // 构建请求
        Request request = new Request.Builder()
                .url(outUrl+"/ht/system/sysDept/queryPage")
                .post(body)
                .addHeader("Authorization", "Bearer "+tokens) // 替换YOUR_TOKEN
                .build();
        // 发送请求并处理响应
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                String jsonString = response.body().string();

//                String jsonString="";
                // 创建ObjectMapper实例
                ObjectMapper objectMapper = new ObjectMapper();
                try {

                    // 解析JSON字符串为JsonNode对象
                    JsonNode rootNode = objectMapper.readTree(jsonString);

                    // 获取code字段的值
                    String code = rootNode.get("code").asText();
                    System.out.println("Code: " + code);

                    // 获取success字段的值
                    boolean success = rootNode.get("success").asBoolean();
                    System.out.println("Success: " + success);

                    // 获取data字段的值（是一个数组）
                    JsonNode dataNode = rootNode.get("data");
                    JsonNode dataList= dataNode.get("list");
                    List<SysDept> nodes= new ArrayList<>();
                    // 遍历data数组中的每个元素
                    for (JsonNode deptNode : dataList) {
                        //获取所有部门
                        SysDept sysDept =new SysDept();
                        //先判断sjgajgjgdm 上级是不是0

                        if(StringUtils.isNotEmpty( deptNode.get("gajgjgdm").asText())){
                            SysDept gainfo = deptService.selectDeptBygajgjgdm(deptNode.get("gajgjgdm").asText());
                            if (gainfo == null) {
                                //上级组织机构不能不空
                                if(StringUtils.isNotEmpty( deptNode.get("sjgajgjgdm").asText())){
                                    SysDept info = deptService.selectDeptBysjgajgjgdm(deptNode.get("sjgajgjgdm").asText());
                                    if (info != null) {
                                        //部门名称 = 对接组织机构名称 gajgmc
                                        if(StringUtils.isNotEmpty( deptNode.get("gajgmc").asText())){
                                            sysDept.setDeptName(deptNode.get("gajgmc").asText());
                                        }
                                        sysDept.setParentId(info.getDeptId());

                                        //显示顺序  = 对接显示顺序 xssx
                                        if(StringUtils.isNotEmpty( deptNode.get("xssx").asText())){
                                            sysDept.setOrderNum(Integer.valueOf(deptNode.get("xssx").asText()));
                                        }

                                        //单位类别
                                        if(StringUtils.isNotEmpty( deptNode.get("dwlb").asText())){
                                            sysDept.setDwlb(deptNode.get("dwlb").asText());
                                        }

                                        //组织机构单位性质类别
                                        if(StringUtils.isNotEmpty( deptNode.get("gajgmclbdm").asText())){
                                            sysDept.setGajgbmlbdm(deptNode.get("gajgmclbdm").asText());
                                        }



                                        //单位级别
                                        if(StringUtils.isNotEmpty( deptNode.get("gajgbmlbdm").asText())){
                                            sysDept.setGajgbmlbdm(deptNode.get("gajgbmlbdm").asText());
                                        }

                                        //组织机构代码
                                        if(StringUtils.isNotEmpty( deptNode.get("gajgjgdm").asText())){
                                            sysDept.setGajgjgdm(deptNode.get("gajgjgdm").asText());
                                        }

                                        //上级组织机构不能不空
                                        if(StringUtils.isNotEmpty( deptNode.get("sjgajgjgdm").asText())){
                                            sysDept.setSjgajgjgdm(deptNode.get("sjgajgjgdm").asText());
                                        }

                                        //帐号状态（0正常 1停用）
                                        sysDept.setStatus("0");
                                        //删除状态
                                        sysDept.setDelFlag("0");
                                        //创建时间
                                        sysDept.setCreateTime(new Date());
                                        //创建人
                                        sysDept.setCreateBy("admin");
                                        //修改时间
                                        sysDept.setUpdateTime(new Date());
                                        //修改人
                                        sysDept.setUpdateBy("admin");
                                        deptService.insertDept(sysDept);
                                    }
                                }

                            }
                            }
                        }





                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                throw new IOException("Unexpected code " + response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }




}


