/**
 * Copyright (C), 2022-04-28
 * FileName: UserTask
 * Author:   wanglongda
 * Date:     2022/4/28 12:03
 * Description: 同步用户
 */
package me.zhengjie.modules.quartz.task;/**
 * Created Name: wanglongda
 * Created Time: 2022/4/28 12:03
 * Description: iot-zhyd
 */

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.dm.user.domain.DmUser;
import me.zhengjie.modules.dm.user.repository.DmUserRepository;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.modules.system.domain.Job;
import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.DeptRepository;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * <功能简要> <br>
 * <同步用户>
 *
 * @Author wanglongda
 * @createTime 2022/4/28 12:03
 * @Version 1.0.0
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class UserTask {
    @Value("${zkApiUrl}")
    private String zkApiUrl;
    @Value("${deptApi}")
    private String deptApi;
    @Value("${userApi}")
    private String userApi;
    @Value("${headerKey}")
    private String header_key;
    @Value("${key}")
    private String key;

    private final UserRepository userRepository;
    private final DmUserRepository dmUserRepository;
    private final DeptRepository deptRepository;


    public void runDept(){
        log.info("deptsync 执行开始");
        deptSyncAll();
        log.info("deptsync 执行结束");
    }

    public void runUser(){
        log.info("usersync 执行开始");
        userSyncAll();
        log.info("usersync 执行结束");
    }



    /**
     * 部门数据同步(全量)
     */
    private void deptSyncAll() {
//        String api = "/api/thirdparty/v1/user/getzkdeps";

        //计算总页数
        int total = getDatas(deptApi,null,0,100,2).getJSONObject("data").getInteger("totalElements");
        int pageSize = 100;
        int pageTotal = (total / pageSize);
        if (total % pageSize != 0) {
            pageTotal++;
        }
        log.info("pageTotal:"+pageTotal);

        //按页获取
        for (int k = 0; k < pageTotal; k++) {
            JSONObject json = getDatas(deptApi,null,k,pageSize,2);
            JSONObject data = json.getJSONObject("data");
            JSONArray content = data.getJSONArray("content");
            for (int i = 0; i < content.size(); i++) {
                Dept dept = JSONObject.parseObject(content.getString(i), Dept.class);
                deptRepository.save(dept);
            }
        }
    }


    /**
     * 人员数据同步（全量）
     */
    private void userSyncAll() {

//        String api = "/api/thirdparty/v1/user/getZkSysUsers";

        //计算总页数
        int total = getDatas(userApi,null,0,1,2).getJSONObject("data").getInteger("totalElements");
        int pageSize = 10;
        int pageTotal = (total / pageSize);
        if (total % pageSize != 0) {
            pageTotal++;
        }
        log.info("pageTotal:"+pageTotal);

        //按页获取
        for (int k = 0; k <= pageTotal; k++) {
            JSONObject json = getDatas(userApi, null,k,pageSize,1);
            JSONObject data = json.getJSONObject("data");
            JSONArray content = data.getJSONArray("content");
            for (int i = 0; i < content.size(); i++) {
                User user = new User();
                JSONObject userData = content.getJSONObject(i);

                user.setId(userData.getString("id"));
                if(userData.containsKey("username")) {
                    user.setUsername(userData.getString("username"));
                }
                user.setPassword(userData.getString("password"));
                user.setOrgPassword("12345678");
                if(userData.containsKey("jobs")) {
                    Set<Job> jobs = new HashSet<>(JSONArray.parseArray(userData.getString("jobs"), Job.class));
                    user.setJobs(jobs);
                }
                if(userData.containsKey("roles")) {
                    Set<Role> roles = new HashSet<>(JSONArray.parseArray(userData.getString("roles"), Role.class));
                    user.setRoles(roles);
                }
                if(userData.containsKey("gender")) {
                    user.setGender(userData.getString("gender"));
                }

                if(userData.containsKey("dept")) {
                    user.setDept(JSONObject.parseObject(userData.getString("dept"), Dept.class));
                }

                if(userData.containsKey("email")) {
                    user.setEmail(userData.getString("email"));
                }

                if(userData.containsKey("nickName")) {
                    user.setNickName(userData.getString("nickName"));
                }

                if(userData.containsKey("phone")) {
                    user.setPhone(userData.getString("phone"));
                }

                if(userData.containsKey("enabled")) {
                    user.setEnabled(userData.getBoolean("enabled"));
                }

                if(userData.containsKey("userRootGroupId")) {
                    user.setUserRootGroupId(userData.getString("userRootGroupId"));
                }
                if(userData.containsKey("userRootGroupName")) {
                    user.setUserRootGroupName(userData.getString("userRootGroupName"));
                }

                DmUser dmUser = new DmUser();
                dmUser.setDept(user.getDept());
                dmUser.setId(user.getId());
                dmUser.setEmail(user.getEmail());
                dmUser.setContacts(user.getPhone());
                dmUser.setName(user.getNickName());
                dmUser.setSex(user.getGender());

                if(!ObjectUtils.isEmpty(userData.getJSONObject("dmUser"))){
                    JSONObject dmUserObject = userData.getJSONObject("dmUser");
                    if(dmUserObject.containsKey("cardid")) {
                        dmUser.setCardId(dmUserObject.getString("cardid"));
                    }
                    if(dmUserObject.containsKey("userNumber")) {
                        dmUser.setUserNumber(dmUserObject.getString("userNumber"));
                    }
                    if(dmUserObject.containsKey("type")) {
                        dmUser.setUsertype(dmUserObject.getString("type"));
                    }
                    if(dmUserObject.containsKey("faceid")) {
                        dmUser.setPicture(dmUserObject.getString("faceid"));
                    }
                }
                //判断是否是新离职的员工，如果是则修改门禁和停车权限
//                if(!user.getEnabled()){
//                    UserDto userDto = userService.findById(user.getId());
//                    if(!ObjectUtils.isEmpty(userDto)){
//                        if(userDto.getEnabled()){
//                            //删除门禁一楼进入设备权限
//                            JSONArray deviceInfoArray = new JSONArray();
//                            List<String> deviceList = Arrays.asList(deviceInfo.split(","));
//                            for(String device : deviceList){
//                                log.info("device:"+device);
//                                DmRoomDevice dmRoomDevice = dmRoomDeviceService.findByCode(device).get(0);
//                                if(!ObjectUtils.isEmpty(dmRoomDevice)){
//                                    JSONObject object = new JSONObject();
//                                    object.put("serialNumber",dmRoomDevice.getCode());
//                                    object.put("doorID",dmRoomDevice.getDoorID());
//                                    object.put("deviceType",dmRoomDevice.getDeviceType());
//                                    deviceInfoArray.add(object);
//                                }
//                            }
//                            JSONObject device = new JSONObject();
//                            device.put("userId",dmUser.getUserNumber());
//                            device.put("operateType","2");
//                            device.put("deviceInfo",deviceInfoArray);
//                            log.info("device:"+device.toJSONString());
//                            String msg = HttpRequest.post(synchronizationDeviceUrl).form("device", device.toJSONString()).execute().body();
//                            log.info("msg:"+msg);
//
//                            DmPlateNumberQueryCriteria dmPlateNumberQueryCriteria = new DmPlateNumberQueryCriteria();
//                            dmPlateNumberQueryCriteria.setUserNumber(dmUser.getId());
//                            List<DmPlateNumberDto> dmPlateNumberDtoList = dmPlateNumberService.queryAll(dmPlateNumberQueryCriteria);
//                            if(!ObjectUtils.isEmpty(dmPlateNumberDtoList)){
//                                for(DmPlateNumberDto dmPlateNumberDto : dmPlateNumberDtoList){
//                                    dmPlateNumberService.deleteYuePlate(dmPlateNumberDto.getPlateNumber());
//
//                                    JSONObject generateProcJson = new JSONObject();
//                                    generateProcJson.put("name",dmPlateNumberDto.getUserNumber().getName());
//                                    generateProcJson.put("phone",dmPlateNumberDto.getUserNumber().getContacts());
//                                    generateProcJson.put("carplate",dmPlateNumberDto.getPlateNumber());
//                                    SimpleDateFormat formater2 = new SimpleDateFormat("yyyy-MM-dd");
//                                    generateProcJson.put("startdate",formater2.format(dmPlateNumberDto.getStartTime()));
//                                    generateProcJson.put("enddate",formater2.format(dmPlateNumberDto.getEndTime()));
//                                    generateProcJson.put("cardtype","A");
//                                    generateProcJson.put("controllers", "3,4");
//                                    String generateProcData = BeanMapUtils.doPostForm(yueUrl,generateProcJson);
//                                    JSONObject generateProcDataJson = JSONObject.parseObject(generateProcData);
//                                    System.out.println("generateProcJson"+generateProcJson);
//                                    System.out.println("generateProcDataJson:"+generateProcDataJson);
//                                }
//                            }
//
//                        }
//                    }
//                }
                DmUser newDmUser = dmUserRepository.save(dmUser);
                user.setDmUser(newDmUser);
                userRepository.save(user);
            }
        }
    }

    private JSONObject getDatas(String api,JSONArray time, int pageNum, int pageSize,int type) {
        Map<String,Object> tokenData = SecurityUtils.getToken(key);
        JSONObject body = new JSONObject();
        body.put("timestamp",tokenData.get("timestamp"));
        body.put("nonce",tokenData.get("nonce"));
        JSONObject query = new JSONObject();
        if(type == 1){
            query.put("updateTime",time);
        }
        body.put("query",query);

        String res = HttpRequest.get(zkApiUrl + api+"?page="+pageNum+"&size="+pageSize)
                .header(header_key, tokenData.get("token").toString())
                .body(body.toString()).execute().body();
        JSONObject json = JSONObject.parseObject(res);
        log.info("json:"+json);
        return json;
    }
}
