package com.bonus.system.att.service;

import com.bonus.common.core.constant.Constants;
import com.bonus.common.core.utils.DateTimeHelper;
import com.bonus.common.core.utils.bean.BeanUtils;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.system.att.dao.AttGroupDao;
import com.bonus.system.att.dao.AttSourceDataDao;
import com.bonus.system.att.entity.AttDataBean;
import com.bonus.system.att.entity.AttGroupBean;
import com.bonus.system.att.entity.AttGroupCheckOrgBean;
import com.bonus.system.att.utils.TreeUtils;
import com.bonus.system.basic.domain.SysTree;
import com.bonus.system.dept.dao.ProDeptRoleDao;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 考勤组-业务层
 *
 * @author zys
 */
@Service("attGroupService")
public class AttGroupServiceImpl implements AttGroupService {

    @Resource(name = "attGroupDao")
    private AttGroupDao attGroupDao;

    @Resource(name = "ProDeptRoleDao")
    private ProDeptRoleDao proDeptRoleDao;

    @Resource(name = "attSourceDataDao")
    private AttSourceDataDao attSourceDataDao;

    @Resource(name = "AttCalService")
    private AttCalService attCalService;

    @Override
    public List<AttGroupBean> selectAttGroupList(AttGroupBean bean) {
        return attGroupDao.selectAttGroupList(bean);
    }

    @Override
    public List<SysTree> selectOrgList() {
        List<SysTree> listTree = attGroupDao.getAttGroupCheckPerson(null);
        // 返回处理后的树形结构
        return listTree.stream()
                .filter(m -> m.getParentId() == null)
                .peek(m -> m.setChildren(TreeUtils.getOrgTreeChild(m, listTree, 0)))
                .collect(Collectors.toList());
    }

    @Override
    public int deleteAttGroup(Long groupId) {
        return attGroupDao.deleteAttGroup(groupId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertAttGroup(AttGroupBean bean) {
        int result = 0;
        bean.setCreateUserId(SecurityUtils.getLoginUser().getSysUser().getUserId());
        //只有部门的将部门变成部门下所有人(去除掉其他考勤组选的人)
        List<AttGroupCheckOrgBean> checkOrgAllList = dealWithOrgUser(bean, null);
        if (checkOrgAllList.isEmpty()) {
            return -1;
        }
        //新增考勤组表
        int i = attGroupDao.insertAttGroup(bean);
        if (i > 0) {
            //新增考勤组设置表
            int j = attGroupDao.insertAttGroupSetting(bean);
            //新增考勤组绑定人员表
            for (int k = 0; k < checkOrgAllList.size(); k++) {
//                checkOrgAllList.get[k].setGroupId(bean.getGroupId());
                checkOrgAllList.get(k).setGroupId(bean.getGroupId());
            }
            int x = attGroupDao.insertAttGroupPerson(checkOrgAllList);
            addAttData(bean, checkOrgAllList);
            if (j > 0 && (x == checkOrgAllList.size())) {
                result = 1;
            }
        }
        return result;
    }

    @Override
    public AttGroupBean selectAttGroupById(Long groupId) {
        //查出选择的人员
//        List<AttGroupCheckOrgBean> checkList = attGroupDao.selectAttGroupUserById(groupId);
        //查出组织人员
        List<SysTree> orgList = attGroupDao.getAttGroupCheckPerson(groupId);
        //查出考勤组详细数据
        AttGroupBean attGroupBean = attGroupDao.selectAttGroupById(groupId);
//        List<SysTree> treeList = getOrgCheckList(orgList, checkList);
        attGroupBean.setTreeList(orgList.stream().filter(m -> m.getParentId() == null).peek((m) ->
                m.setChildren(TreeUtils.getOrgTreeChild(m, orgList, 0))).collect(Collectors.toList()));
        return attGroupBean;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateAttGroup(AttGroupBean bean) {
        int result = 0;
        bean.setUpdateUserId(SecurityUtils.getLoginUser().getSysUser().getUserId());
        List<AttGroupCheckOrgBean> checkOrgAllList = dealWithOrgUser(bean, null);
        if (checkOrgAllList.isEmpty()) {
            return -1;
        }
        //新增考勤组表
        int i = attGroupDao.updateAttGroup(bean);
        if (i > 0) {
            //新增考勤组设置表
            int j = attGroupDao.updateAttGroupSetting(bean);

//            //删除考勤组绑定人员
//            attGroupDao.deleteAttGroupRelationPerson(bean.getGroupId());
//            //新增考勤组绑定人员表
//            int x = attGroupDao.insertAttGroupPerson(checkOrgAllList);
//            if (j > 0 && (x == bean.getCheckOrgList().size())) {
//                result = 1;
//            }
            //代码逻辑修改，改为增量更新
            //1.先去查目前考勤组有哪些人员
            List<AttGroupCheckOrgBean> checkOrgList = attGroupDao.selectAttGroupUserById(bean.getGroupId());
            //2.比较新的人员与目前考勤组人员做对比，如果目前考勤组人员独有，则删除，如果新选人员独有，则新增，两个都有，则不动
            //2.1对比人员，生成各自的list
            Map<String, List<AttGroupCheckOrgBean>> stringListMap = compareByUserId(checkOrgAllList, checkOrgList);
            List<AttGroupCheckOrgBean> addList = stringListMap.get("onlyInList1");
            List<AttGroupCheckOrgBean> delList = stringListMap.get("onlyInList2");
            //2.2 删除人员,新增人员
            if (!delList.isEmpty()) {
                //删除考勤组绑定人员
                attGroupDao.deleteAttGroupPersonByUserId(delList);
            }
            if (!addList.isEmpty()) {
                //添加考勤组绑定人员
                attGroupDao.insertAttGroupPerson(addList);
                addAttData(bean, addList);
            }
            return 1;
        }
        return result;
    }

    /**
     * 新增的人员 生成当天的考勤模板/与考勤规则进行绑定
     *
     * @param bean
     * @param addList
     * @return void
     * @author cwchen
     * @date 2025/2/18 13:56
     */
    public void addAttData(AttGroupBean bean, List<AttGroupCheckOrgBean> addList) {
        // 新增的人员 生成当天的考勤模板/与考勤规则进行绑定
        List<AttGroupBean> list = new ArrayList<>();
        List<AttDataBean> listPerson = new ArrayList<>();
        for (AttGroupCheckOrgBean attGroupCheckOrgBean : addList) {
            AttGroupBean groupBean = new AttGroupBean();
            groupBean.setGroupId(attGroupCheckOrgBean.getGroupId());
            groupBean.setUserId(Long.parseLong(attGroupCheckOrgBean.getUserId()));
            groupBean.setCurrentDay(DateTimeHelper.getNowDate());
            list.add(groupBean);
        }
        attCalService.insertAttTempData(DateTimeHelper.getNowDate(),2);
        /*// 新增考勤人员列表
        attSourceDataDao.insertAttSettingHistoryData(list);
        // 查询人员组织机构ID
        listPerson = attGroupDao.getUserInfo(bean, addList);
        // 新增人员考勤模板数据
        attSourceDataDao.insertAttDataList(listPerson);*/
    }

    public Map<String, List<AttGroupCheckOrgBean>> compareByUserId(
            List<AttGroupCheckOrgBean> list1,
            List<AttGroupCheckOrgBean> list2) {

        // 创建 userId 到 AttGroupCheckOrgBean 的映射
        Map<String, AttGroupCheckOrgBean> map1 = new HashMap<>();
        for (AttGroupCheckOrgBean bean : list1) {
            map1.put(bean.getUserId(), bean);
        }

        Map<String, AttGroupCheckOrgBean> map2 = new HashMap<>();
        for (AttGroupCheckOrgBean bean : list2) {
            map2.put(bean.getUserId(), bean);
        }
        // 存储结果
        Map<String, List<AttGroupCheckOrgBean>> resultMap = new HashMap<>();
        resultMap.put("onlyInList1", new ArrayList<>());
        resultMap.put("onlyInList2", new ArrayList<>());
        resultMap.put("intersection", new ArrayList<>());
        // 计算交集和差集
        Set<String> allKeys = new HashSet<>(map1.keySet());
        allKeys.addAll(map2.keySet());
        for (String key : allKeys) {
            if (map1.containsKey(key) && map2.containsKey(key)) {
                // 交集
                resultMap.get("intersection").add(map1.get(key));
            } else if (map1.containsKey(key)) {
                // 仅存在于list1中
                resultMap.get("onlyInList1").add(map1.get(key));
            } else if (map2.containsKey(key)) {
                // 仅存在于list2中
                resultMap.get("onlyInList2").add(map2.get(key));
            }
        }
        return resultMap;
    }


    private List<AttGroupCheckOrgBean> dealWithOrgUser(AttGroupBean bean, Long bean1) {
        //只有部门的将部门变成部门下所有人(去除掉其他考勤组选的人)
        List<AttGroupCheckOrgBean> checkOrgAllList = bean.getCheckOrgList();
        List<AttGroupCheckOrgBean> checkOrgList = new ArrayList<>();
        checkOrgAllList.forEach(c -> {
                    if (!"".equals(c.getOrgId()) && "".equals(c.getUserId())) {
                        String id = proDeptRoleDao.getOrgChildById(Long.valueOf(c.getOrgId()));
                        // 使用 Arrays.asList() 将数组转换为 ArrayList
                        ArrayList<String> idList = new ArrayList<>(Arrays.asList(id.split(",")));
                        List<AttGroupCheckOrgBean> userList = attGroupDao.getUserByOrg(idList, bean1);
                        checkOrgList.addAll(userList);
                    }
                }
        );
        checkOrgAllList.addAll(checkOrgList);
        // 使用 Iterator 来安全地遍历并移除元素
        Iterator<AttGroupCheckOrgBean> iterator = checkOrgAllList.iterator();
        while (iterator.hasNext()) {
            AttGroupCheckOrgBean person = iterator.next();
            if (person.getUserId().isEmpty()) {
                // 如果 userId 为空或空字符串，则移除该元素
                iterator.remove();
            } else {
                // 否则，设置 groupId
                person.setGroupId(bean.getGroupId());
            }
        }
        return checkOrgAllList;
    }

    private List<SysTree> getOrgCheckList(List<SysTree> orgList, List<AttGroupCheckOrgBean> checkList) {
        // 使用forEach结合stream进行比对
//        checkList.forEach(c -> orgList.stream().filter(v -> (c.getUserId() + Constants.VERTICAL +
//                c.getOrgId()).equals(v.getId())).forEach(x -> x.setIsChecked(true)));
        return orgList;
    }

}
