package com.bonus.system.dept.service;

import com.bonus.common.core.constant.UserConstants;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.system.api.domain.MapVo;
import com.bonus.system.api.domain.SysUser;
import com.bonus.system.att.utils.AddressCoordinateFormatUtil;
import com.bonus.system.basic.dao.SysOrgDao;
import com.bonus.system.basic.domain.SysNotice;
import com.bonus.system.basic.domain.SysOrg;
import com.bonus.system.basic.service.SysNoticeService;
import com.bonus.system.dept.dao.ProDeptRoleDao;
import com.bonus.system.dept.dao.SubOrgDao;
import com.bonus.system.dept.entity.ProDeptRoleBean;
import com.bonus.system.dept.entity.ProDeptRoleDo;
import com.bonus.system.dept.entity.SubOrgBean;
import org.springframework.stereotype.Service;

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

/**
 * 组织 业务层处理
 *
 * @author zys
 */
@Service("SubOrgService")
public class SubOrgServiceImpl implements SubOrgService {

    @Resource
    private SubOrgDao orgDao;

    @Resource
    private SysOrgDao sysOrgDao;

    @Resource(name = "ProDeptRoleService")
    private ProDeptRoleService proDeptRoleService;

    /**
     * 消息推送库表
     */
    @Resource
    private SysNoticeService noticeService;

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

    @Override
    public List<SubOrgBean> selectSubOrgList(SubOrgBean subOrgBean) {
        //只能查自己分公司的人
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        List<String> roleId = sysUser.getRoleList();
        if(roleId !=null && !roleId.isEmpty() ) {
            if (Collections.frequency(roleId, "1") == 0) {
                List<MapVo> orgList = SecurityUtils.getLoginUser().getSysUser().getOrgList();
                if (!orgList.isEmpty()) {
                    ArrayList<String> ids = new ArrayList<>();
                    for (MapVo mapVo : orgList) {
                        ids.add(String.valueOf(mapVo.getId()));
                    }
                    subOrgBean.setOrgList(ids);
                }
            }
        }
        return orgDao.selectOrgList(subOrgBean);
    }

    @Override
    public SubOrgBean selectOrgById(Long orgId) {
        SubOrgBean subOrgBean = orgDao.selectOrgById(orgId);
        List<ProDeptRoleBean> list = orgDao.getDeptRoleList(orgId);
        subOrgBean.setRoleList(list);
        return subOrgBean;
    }


    @Override
    public int insertOrg(SubOrgBean org) {
        Map<String, BigDecimal> map = AddressCoordinateFormatUtil.addressToCoordinate(org.getAddress());
        if (map == null) {
            return 3;
        }
        org.setLon(map.get("longitude"));
        org.setLat(map.get("latitude"));
        //新增项目部默认待审批
        org.setReviewerStatus("0");
        //一定为项目部
        org.setIsDepartment("1");
        int i = orgDao.insertOrg(org);
        if (i == 1) {
            if (StringUtils.isNotBlank(org.getOrgHeadUserId())) {
                threadOrgHeadData(org);
            }
            //调用部门角色代码进行增量更新
            incrementalUpdate(org);
            //method 信息推送
            //获取部门负责人
            List<Long> userList = noticeService.getUserIdByOrgId(org.getParentId());
			Long loginId = SecurityUtils.getLoginUser().getSysUser().getUserId();
            // 将 List 转换为数组
            if (!userList.isEmpty()) {
                Long[] userIds = userList.toArray(new Long[0]);
                //发送审批消息
                SysNotice notice = new SysNotice();
                notice.setUserIds(userIds);
                notice.setUserId(loginId);
                notice.setTitle("分公司项目部新增");
                notice.setContent("分公司项目部新增");
                notice.setType("70");
                notice.setValue("");
                //推送消息
                noticeService.insertNotice(notice);
            }
        }

        return i;
    }

    public int threadOrgHeadData(SysOrg org) {
        List<String> listHead = new ArrayList<>();
        if (org.getOrgHeadUserId().contains(",")) {
            listHead = Arrays.asList(org.getOrgHeadUserId().split(","));
        } else {
            listHead.add(org.getOrgHeadUserId());
        }
        int j = sysOrgDao.insertOrgHead(listHead, org.getId());
        if (j >= listHead.size()) {
            return 1;
        }
        return j;
    }

    @Override
    public Boolean checkOrgNameUnique(SubOrgBean org) {
        long orgId = org.getId();
        SubOrgBean info = orgDao.checkOrgNameUnique(org.getOrgName(), org.getParentId());
        if (StringUtils.isNotNull(info) && info.getId() != orgId) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public int updateOrg(SubOrgBean org) {
        Map<String, BigDecimal> map = AddressCoordinateFormatUtil.addressToCoordinate(org.getAddress());
        if (map == null) {
            return 3;
        }
        org.setLon(map.get("longitude"));
        org.setLat(map.get("latitude"));
        //新增项目部默认待审批
        org.setReviewerStatus("0");
        //一定为项目部
        org.setIsDepartment("1");
        int i = orgDao.updateOrg(org);
        if (i == 1) {
            if (StringUtils.isNotBlank(org.getOrgHeadUserId())) {
                sysOrgDao.deleteOrgHead(org.getId());
                threadOrgHeadData(org);
            }
            //调用部门角色代码进行增量更新
            incrementalUpdate(org);
        }
        return i;
    }

    private void incrementalUpdate(SubOrgBean org) {
        List<ProDeptRoleBean> roleList = org.getRoleList();
        //先去查询八个角色是否已经添加过了
        List<ProDeptRoleBean> deptRoleList = orgDao.getDeptRoleByOrgId(org.getId());
        // 将 deptRoleList 转换为 Map，以 departmentId 为键，Role 对象为值
        Map<Long, ProDeptRoleBean> roleMap = deptRoleList.stream()
                .collect(Collectors.toMap(ProDeptRoleBean::getDeptRoleId, role -> role));
        // 比较并输出匹配的结果
        for (ProDeptRoleBean deptRole : roleList) {
            if (roleMap.containsKey(deptRole.getDeptRoleId())) {
                deptRole.setDepartmentId(roleMap.get(deptRole.getDeptRoleId()).getDepartmentId()); // 仅添加匹配的 DeptRole
            }
        }
        for (ProDeptRoleBean role : roleList) {
            ProDeptRoleDo bean = new ProDeptRoleDo();
            bean.setOrgId(org.getId());
            bean.setDeptRoleId(role.getDeptRoleId());
            if (role.getDepartmentId() != null) {
                bean.setDepartmentId(role.getDepartmentId());
            }
            bean.setUserId(role.getUserId());
            proDeptRoleService.updatePersonAssignment(bean, "0");
        }
    }

    @Override
    public boolean hasChildByOrgId(Long orgId) {
        int result = orgDao.hasChildByOrgId(orgId);
        return result > 0;
    }

    @Override
    public boolean checkOrgExistUser(Long orgId) {
        int result = orgDao.checkOrgExistUser(orgId);
        return result > 0;
    }

    @Override
    public int deleteOrgById(Long orgId) {
        Long updateUserId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        //查询组织下的角色表，角色绑定人员表（组织管理同样调用）
        syncDelRoleUser(orgId);
        return sysOrgDao.deleteOrgById(orgId, updateUserId);
    }

    /**
     * 同步删除组织下面的人员
     *
     * @param orgId
     */
    public void syncDelRoleUser(Long orgId) {
        List<Integer> deptIdList = orgDao.getDepartmentIdByOrgId(orgId);
        if (!deptIdList.isEmpty()) {
            orgDao.deleteDeptRoleUser(deptIdList);
            orgDao.deleteDeptRole(deptIdList);
        }
    }

    /**
     * 人员管理删除人员是调用
     *
     * @param orgId
     */
    public void syncDelUser(Long userId) {
        orgDao.delRoleUserByUserId(userId);
    }

    @Override
    public int changeStatus(SubOrgBean org) {
        Long updateUserId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        org.setUpdateUserId(updateUserId);
        //同步角色分配的状态
        //1.查询本角色所有分配角色
        List<ProDeptRoleDo> list = orgDao.getRoleListByOrgId(org.getId());
        //2.同步状态
        list.forEach(role -> {
            role.setReviewerStatus(org.getReviewerStatus());
            proDeptRoleService.checkPersonAssignment(role);
        });
        return orgDao.updateOrgStatus(org);
    }


}
