package com.xjrsoft.module.organization.service.impl;


import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xjrsoft.common.enums.DeleteMark;
import com.xjrsoft.common.enums.EnabledMark;
import com.xjrsoft.common.utils.WeChatUtil;
import com.xjrsoft.module.organization.dto.WeChatDepartDto;
import com.xjrsoft.module.organization.dto.WeChatJsConfigDto;
import com.xjrsoft.module.organization.dto.WeChatSendMessageDto;
import com.xjrsoft.module.organization.dto.WeChatUserDto;
import com.xjrsoft.module.organization.entity.Department;
import com.xjrsoft.module.organization.entity.User;
import com.xjrsoft.module.organization.service.IDepartmentService;
import com.xjrsoft.module.organization.service.IUserService;
import com.xjrsoft.module.organization.service.IWeChatService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class WeChatServiceImgl implements IWeChatService {

    private List<WeChatDepartDto> deptDepartlist = new ArrayList<>();


    private final WeChatUtil weChatUtil;

    private final IDepartmentService departmentService;

    private final IUserService userService;


    @Override
    public boolean updateInfo() {
        deptDepartlist.clear();
        this.getdept(null);
        return this.updatedepart();
    }

    @Override
    public  void sendTemplateMessage(WeChatSendMessageDto dto) {
        JSONObject object = new JSONObject();
        object.put("touser", dto.getUserId());
        object.put("template_id", dto.getTemplateId());
//        object.put("miniprogram", new JSONObject() {{
//            put("appid", weChatUtil.getAppletAppKey());
//            put("pagepath", dto.getUrl());
//        }});
        object.put("url", dto.getUrl());
        object.put("client_msg_id", dto.getMsgId());
        object.put("data", dto.getContent());
        weChatUtil.sendTemplateMessage(object);
    }

    private boolean updatedepart() {
//        List<Department> departmentList = departmentService.list(Wrappers.<Department>query().lambda().eq(Department::getEnabledMark, EnabledMark.ENABLED.getCode()).eq(Department::getDeleteMark, DeleteMark.NODELETE.getCode()));
//        ArrayList<Department> updateDeparts = new ArrayList<>();
//        ArrayList<Department> addDeparts = new ArrayList<>();

//        for (WeChatDepartDto weChatDepartDto : deptDepartlist) {
//            if(departmentList.indexOf(weChatDepartDto.getName())>0) {
//                for (int i = 0; i < departmentList.size(); i++) {
//                    Department department = departmentList.get(i);
//                    if (department.getName().equals(weChatDepartDto.getName())) {
//                        department.setParentId(Long.valueOf(weChatDepartDto.getParentid()));
//                        updateDeparts.add(department);
//                    } else if(!deptDepartlist.contains(department.getName())){
//                             department.setParentId(Long.valueOf(weChatDepartDto.getParentid()));
//                             department.setName(weChatDepartDto.getName());
//                             department.setEnabledMark(EnabledMark.ENABLED.getCode());
//                             department.setDeleteMark(DeleteMark.NODELETE.getCode());
//                             addDeparts.add(department);
//                    }
//                }
//            }else {
//                Department department = new Department();
//                department.setParentId(Long.valueOf(weChatDepartDto.getParentid()));
//                department.setName(weChatDepartDto.getName());
//                department.setEnabledMark(EnabledMark.ENABLED.getCode());
//                department.setDeleteMark(DeleteMark.NODELETE.getCode());
//                addDeparts.add(department);
//            }
//        }
        //        try {
//            departmentService.saveBatch(addDeparts);
//            departmentService.updateBatchById(updateDeparts);
//        } catch (DuplicateKeyException e) {
//            throw new MyException("用户和部门信息已更新到其他公司中!!!");
//        }
        //1.更新部门信息
        Set<WeChatDepartDto> departResponses=new HashSet<>();
        departResponses = deptDepartlist.stream().collect(Collectors.toSet());
        //获取数据库中的部门信息
        List<Department> departmentList = departmentService.list(Wrappers.<Department>query().lambda().eq(Department::getEnabledMark, EnabledMark.ENABLED.getCode()).eq(Department::getDeleteMark, DeleteMark.NODELETE.getCode()));
       Map<String, Department> departmentMap = departmentList.stream().collect(Collectors.toMap(v -> v.getName(), v -> v));
        Map<String, WeChatDepartDto> departResponsesMap = new HashMap<>();
        if (departResponses.size() > 0) {
            departResponsesMap = departResponses.stream().collect(Collectors.toMap(v->v.getName(),v->v));
        }
        //更新部门
        ArrayList<Department> updatedaparts = new ArrayList<>();
        Set<String> distinctId1 = CollUtil.intersectionDistinct(departmentMap.keySet(), departResponsesMap.keySet());
        if (distinctId1.size() > 0) {
            for (String distinctId : distinctId1) {
                Department department = departmentMap.get(distinctId);
                WeChatDepartDto weChatDepartDto = departResponsesMap.get(distinctId);
                department.setName(weChatDepartDto.getName());
                department.setParentId(Long.valueOf(weChatDepartDto.getParentid()));
                updatedaparts.add(department);
            }
        }
        //添加数据库中没有的部门
        List<String> subtractIds = CollUtil.subtractToList(departResponsesMap.keySet(), departmentMap.keySet());
        if (subtractIds.size() > 0) {
            for (String subtractId : subtractIds) {
                Department department = new Department();
                WeChatDepartDto weChatDepartDto = departResponsesMap.get(subtractId);
                department.setParentId(Long.valueOf(weChatDepartDto.getParentid()));
                department.setName(weChatDepartDto.getName());
                departmentService.save(department);
            }
        }
        departmentService.updateBatchById(updatedaparts);
        //2.更新部门下的用户信息；
        //更新用户信息
        Set<WeChatUserDto> userResponses = new HashSet<>();
        //微信中的用户信息
        for (WeChatDepartDto weChatDepartDto : deptDepartlist) {
            userResponses.addAll(weChatUtil.getDepartmentUser(Long.valueOf(weChatDepartDto.getId())));
        }
        userResponses = userResponses.stream().collect(Collectors.toSet());
        //获取数据库中的用户信息
        List<User> dbUsers = userService.list(Wrappers.<User>query().lambda().eq(User::getEnabledMark, EnabledMark.ENABLED.getCode()).eq(User::getDeleteMark, DeleteMark.NODELETE.getCode()));
        Map<String, User> dbUsersMap = dbUsers.stream().collect(Collectors.toMap(v -> v.getName(), v -> v));
        Map<String, WeChatUserDto> userResponsesMap = new HashMap<>();
        if (userResponses.size() > 0) {
            userResponsesMap = userResponses.stream().collect(Collectors.toMap(v -> v.getName(), v -> v));
        }
        //更新用户
        ArrayList<User> updateBaseUsers = new ArrayList<>();
        Set<String> distinctIds = CollUtil.intersectionDistinct(dbUsersMap.keySet(), userResponsesMap.keySet());
        if (distinctIds.size() > 0) {
            for (String distinctId : distinctIds) {
                User user = dbUsersMap.get(distinctId);
                WeChatUserDto weChatUserDto = userResponsesMap.get(distinctId);
                user.setName(weChatUserDto.getName());
                user.setAvatar(weChatUserDto.getAvatar());
                user.setEmail(weChatUserDto.getEmail());
              //  user.setId(Long.valueOf(weChatUserDto.getUserid()));
                List<Integer> department = weChatUserDto.getDepartment();
                for (int i = 0; i < department.size(); i++) {
                    user.setDepartmentId(Long.valueOf(department.get(i)));
                }
            //    user.setDepartmentId(weChatUserDto.getDepartment());
                updateBaseUsers.add(user);
            }
        }
        //添加数据库中没有的用户
        List<String> subtractIds2 = CollUtil.subtractToList(userResponsesMap.keySet(), dbUsersMap.keySet());
        if (subtractIds2.size() > 0) {
            for (String subtractId : subtractIds2) {
                User user = new User();
                WeChatUserDto weChatUserDto = userResponsesMap.get(subtractId);
                user.setName(weChatUserDto.getName());
                user.setNickName(weChatUserDto.getUserid());
                List<Integer> department = weChatUserDto.getDepartment();
                for (int i = 0; i < department.size(); i++) {
                    user.setDepartmentId(Long.valueOf(department.get(i)));
                }
                userService.save(user);
            }
        }
        userService.updateBatchById(updateBaseUsers);
        return true;
    }

    //拉取所有部门id
    private void getdept(Long dept_id) {
        List<WeChatDepartDto> departmentList = weChatUtil.getDepartmentList(dept_id);
        deptDepartlist.addAll(departmentList);
    }

    public WeChatJsConfigDto getJsConfig(String url)  throws Exception {
        WeChatJsConfigDto weChatJsConfigDto = new WeChatJsConfigDto();
        HashMap<String, Object> resultMap = weChatUtil.SdkSign(url, "jsapi");
        weChatJsConfigDto.setTimestamp(resultMap.get("timestamp").toString());
        weChatJsConfigDto.setUrl(resultMap.get("url").toString());
        weChatJsConfigDto.setSignature(resultMap.get("signature").toString());
        weChatJsConfigDto.setNonceStr(resultMap.get("nonceStr").toString());
        return weChatJsConfigDto;
    }

}
