package com.mosty.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mosty.base.mapper.UserDeptMapper;
import com.mosty.base.model.vo.base.DeptInfoVo;
import com.mosty.base.service.UserDeptService;
import com.mosty.common.core.business.entity.SysDept;
import com.mosty.common.core.business.entity.SysUser;
import com.mosty.common.core.business.entity.SysUserDept;
import com.mosty.common.core.business.entity.vo.SysRoleVO;
import com.mosty.common.core.business.entity.vo.SysUserDeptVO;
import com.mosty.common.core.business.mapper.SysDeptMapper;
import com.mosty.common.core.business.mapper.SysUserDeptMapper;
import com.mosty.common.core.business.mapper.SysUserMapper;
import com.mosty.common.core.business.service.SysRoleService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author dw
 * @since 2022/8/8
 **/
@Service
@AllArgsConstructor
public class UserDeptServiceImpl extends ServiceImpl<UserDeptMapper, SysUser>
        implements UserDeptService {

    private final SysUserDeptMapper sysUserDeptMapper;
    private final SysDeptMapper sysDeptMapper;
    private final DeptServiceImpl deptServiceImpl;
    private final SysUserMapper sysUserMapper;

    private void getChildList(SysDept dept, List<String> deptIds) {
        deptIds.add(String.valueOf(dept.getId()));
        List<SysDept> tempList1 = this.sysDeptMapper.selectList(
                new LambdaQueryWrapper<SysDept>()
                        .eq(SysDept::getParentId, dept.getId())
        );
        if (tempList1.size() > 0) {
            deptIds.addAll(tempList1.stream().map(item -> String.valueOf(item.getId())).collect(Collectors.toList()));
            tempList1.forEach(item -> this.getChildList(item, deptIds));
        }
    }

    @Override
    public Integer getUserCount(String deptid) {
        SysDept dept = this.sysDeptMapper.selectById(deptid);
        List<String> deptIds = new ArrayList<>();
        this.getChildList(dept, deptIds);
        List<SysUser> userList = this.baseMapper.getUserListByDeptId(deptIds);
        return userList == null ? 0 : userList.size();
    }

    private final SysRoleService sysRoleService;

    @Override
    public boolean getDataPermission(String sfz, String deptcode) {
        SysUser user = this.sysUserMapper.selectOne(
                new QueryWrapper<SysUser>()
                        .eq("id_entity_card", sfz)
                        .last(" limit 1")
        );
        if (user == null) return false;
        // 查询用户权限
        List<SysRoleVO> userRoles = sysRoleService.getUserRoleList(user.getId());
        SysRoleVO role = null;
        if (!CollectionUtils.isEmpty(userRoles)) {
            int level = Integer.parseInt(userRoles.get(0).getDataPermissionLevel());
            role = userRoles.get(0);
            for (SysRoleVO item : userRoles) {
                if (level > Integer.parseInt(item.getDataPermissionLevel())) {
                    level = Integer.parseInt(item.getDataPermissionLevel());
                    role = item;
                }
            }
        }
        // 本部门及以下
        SysUserDept sysUserDept = this.sysUserDeptMapper.selectOne(
                new LambdaQueryWrapper<SysUserDept>()
                        .eq(SysUserDept::getUserId, user.getId())
                        .last(" limit 1")
        );
        if (sysUserDept == null) return false;
        SysDept dept = this.sysDeptMapper.selectById(sysUserDept.getDeptId());
        if (dept == null) return false;
        // 如果拥有权限,并不是本部门及以下权限
        if (role != null && !"5".equals(role.getDataPermissionLevel())) {
            String level = role.getDataPermissionLevel();
            // 全部，全省，全市 都是全部数据权限
            if ("1".equals(level) || "2".equals(level) || "3".equals(level)) return true;
            if ("4".equals(level)) {
                DeptInfoVo deptInfoVo = this.deptServiceImpl.getOrgByDeptId(String.valueOf(dept.getId()));
                // 前6位为县局数据权限，相等则表示有县局权限
                if (deptInfoVo.getFxjcode().substring(0, 6).equals(deptcode.substring(0, 6))) return true;
            }
            // 本部门权限，code全等
            return "6".equals(level) && dept.getOrgCode().equals(deptcode);
        } else {
            return this.level5Data(deptcode, dept);
        }
    }

    // 本部门及以下数据权限（根据orglevel判断权限）
    private boolean level5Data(String deptcode, SysDept dept) {
        String orglevel = dept.getOrgLevel();
        String userSsbmdm = dept.getOrgCode();
        if (StringUtils.isNotEmpty(orglevel)) {
            switch (orglevel) {
                case "10":
                case "11":
                    userSsbmdm = userSsbmdm.substring(0, 2);
                    break;
                case "21":
                case "31":
                    userSsbmdm = userSsbmdm.substring(0, 8);
                    break;
                case "12":
                case "32":
                case "22":
                    userSsbmdm = userSsbmdm.substring(0, 10);
                    break;
                case "20":
                    userSsbmdm = userSsbmdm.substring(0, 4);
                    break;
                case "30":
                    userSsbmdm = userSsbmdm.substring(0, 6);
                    break;
            }
        }
        return deptcode.indexOf(userSsbmdm) == 0;
    }

    @Override
    public List<SysUserDeptVO> getUserAll(String deptid) {
        SysDept dept = this.sysDeptMapper.selectById(deptid);
        List<String> deptIds = new ArrayList<>();
        this.getChildList(dept, deptIds);
        List<SysUser> userList = this.baseMapper.getUserListByDeptId(deptIds);
        List<SysUserDeptVO> list = new ArrayList<>();
        userList.forEach(user -> {
            SysUserDeptVO vo = new SysUserDeptVO();
            BeanUtils.copyProperties(user, vo);
            // 查询所在部门ID
            SysUserDept sysUserDept = this.sysUserDeptMapper.selectOne(
                    new QueryWrapper<SysUserDept>()
                            .eq("user_id", String.valueOf(user.getId()))
                            .last(" limit 1")
            );
            if (sysUserDept != null) {
                SysDept sysDept = this.sysDeptMapper.selectById(sysUserDept.getDeptId());
                if (sysDept != null) {
                    vo.setDeptId(sysDept.getId());
                    vo.setDeptName(sysDept.getOrgName());
                }
            }
            list.add(vo);
        });
        return list;
    }

    @Override
    public List<SysUserDeptVO> getUserList(String deptid) {
        List<SysUser> userList = this.baseMapper.getUserListByIdAll(deptid);
        List<SysUserDeptVO> list = new ArrayList<>();
        userList.forEach(user -> {
            SysUserDeptVO vo = new SysUserDeptVO();
            BeanUtils.copyProperties(user, vo);
            // 查询所在部门ID
            SysUserDept sysUserDept = this.sysUserDeptMapper.selectOne(
                    new QueryWrapper<SysUserDept>()
                            .eq("user_id", String.valueOf(user.getId()))
                            .last(" limit 1")
            );
            if (sysUserDept != null) {
                SysDept sysDept = this.sysDeptMapper.selectById(sysUserDept.getDeptId());
                if (sysDept != null) {
                    vo.setDeptId(sysDept.getId());
                    vo.setDeptName(sysDept.getOrgName());
                }
            }
            list.add(vo);
        });
        return list;
    }

    @Override
    public DeptInfoVo getDeptInfoByUserId(String userId) {
        SysUserDept sysUserDept = this.sysUserDeptMapper.selectOne(
                new QueryWrapper<SysUserDept>()
                        .eq("user_id", String.valueOf(userId))
                        .last(" limit 1")
        );
        if (sysUserDept != null) {
            SysDept sysDept = this.sysDeptMapper.selectById(sysUserDept.getDeptId());
            if (sysDept != null) {
                return this.deptServiceImpl.getOrgByDeptId(String.valueOf(sysDept.getId()));
            }
        }
        return null;
    }

    @Override
    public DeptInfoVo getDeptInfoBySfzh(String sfzh) {
        SysUser user = this.sysUserMapper.selectOne(
                new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getIdEntityCard, sfzh)
                        .last(" limit 1")
        );
        if (ObjectUtils.isEmpty(user)) {
            SysDept sysDept = this.sysDeptMapper.selectById(user.getId());
            if (sysDept != null) {
                return this.deptServiceImpl.getOrgByDeptId(String.valueOf(sysDept.getId()));
            }
        }
        return null;
    }

    public String getssbm(String ssbmdm) {
        if (StringUtils.isNotEmpty(ssbmdm) && ssbmdm.length() == 12) {
            String[] split = ssbmdm.split("");
            for (int i = split.length - 1; i >= 0; i--) {
                String s = split[i];
                if (!s.equals("0")) {
                    ssbmdm = ssbmdm.substring(0, i + 1);
                    break;
                }
            }
        }
        return ssbmdm;
    }
}
