package org.dromara.work.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.dto.RoleDTO;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.SysDept;
import org.dromara.system.domain.SysRoleDept;
import org.dromara.system.domain.SysUser;
import org.dromara.system.mapper.SysDeptMapper;
import org.dromara.system.mapper.SysRoleDeptMapper;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.work.domain.TpYear;
import org.dromara.work.domain.bo.TpYearBo;
import org.dromara.work.domain.vo.TpYearVo;
import org.dromara.work.mapper.TpYearMapper;
import org.dromara.work.service.ITpYearService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 年目标Service业务层处理
 *
 * @author Maosw
 * @date 2024-08-12
 */
@RequiredArgsConstructor
@Service
public class TpYearServiceImpl extends MPJBaseServiceImpl<TpYearMapper, TpYear> implements ITpYearService {

    private final TpYearMapper baseMapper;

    private final SysUserMapper userMapper;

    private final SysDeptMapper deptMapper;

    private final SysRoleDeptMapper roleDeptMapper;

    /**
     * 查询年目标
     *
     * @param id 主键
     * @return 年目标
     */
    @Override
    public TpYearVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询年目标列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 年目标分页列表
     */
    @Override
    public TableDataInfo<TpYearVo> queryPageList(TpYearBo bo, PageQuery pageQuery) {
        MPJLambdaWrapper<TpYear> lqw = buildQueryWrapper(bo);
        lqw.selectAll(TpYear.class)
            .selectAs(SysUser::getNickName, TpYearVo::getNickName)
            .selectAs(SysUser::getRealName, TpYearVo::getRealName)
            .selectAs(SysDept::getDeptName, TpYearVo::getDeptName)
            .leftJoin(SysUser.class, SysUser::getUserId, TpYear::getSid)
            .leftJoin(SysDept.class, SysDept::getDeptId, SysUser::getDeptId)
            .orderByDesc(TpYear::getId);

        IPage<TpYearVo> result = baseMapper.selectJoinPage(new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize()), TpYearVo.class, lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的年目标列表
     *
     * @param bo 查询条件
     * @return 年目标列表
     */
    @Override
    public List<TpYearVo> queryList(TpYearBo bo) {
        MPJLambdaWrapper<TpYear> lqw = buildQueryWrapper(bo);
        lqw.selectAll(TpYear.class)
            .selectAs(SysUser::getNickName, TpYearVo::getNickName)
            .selectAs(SysUser::getRealName, TpYearVo::getRealName)
            .selectAs(SysDept::getDeptName, TpYearVo::getDeptName)
            .leftJoin(SysUser.class, SysUser::getUserId, TpYear::getSid)
            .leftJoin(SysDept.class, SysDept::getDeptId, SysUser::getDeptId)
            .orderByDesc(TpYear::getId);

        return baseMapper.selectJoinList(TpYearVo.class,lqw);
    }

    private MPJLambdaWrapper<TpYear> buildQueryWrapper(TpYearBo bo) {
        MPJLambdaWrapper<TpYear> lqw =new MPJLambdaWrapper<>();
        if(ObjectUtil.isNotNull(bo.getDeptId())){
            List<Long> deptIds = deptMapper.selectList(new LambdaQueryWrapper<SysDept>().like(SysDept::getAncestors, bo.getDeptId())).stream().map(SysDept::getDeptId).collect(Collectors.toList());
            deptIds.add(bo.getDeptId());
            lqw.in(TpYear::getDeptId, deptIds);
        }/*else {
            LoginUser loginUser = LoginHelper.getLoginUser();
            int scope = getDataScope();
            if(scope == 2){
                List<Long> deptIds = getDeptIds();
                lqw.in(TpYear::getDeptId, deptIds);
            }else if(scope == 3){
                lqw.in(TpYear::getDeptId, loginUser.getDeptId());
            }else if(scope == 4){
                List<Long> deptIds = deptMapper.selectList(new LambdaQueryWrapper<SysDept>().like(SysDept::getAncestors, loginUser.getDeptId())).stream().map(SysDept::getDeptId).collect(Collectors.toList());
                deptIds.add(loginUser.getDeptId());
                lqw.in(TpYear::getDeptId, deptIds);
            }else if(scope == 5){
                lqw.eq(TpYear::getSid,loginUser.getUserId());
            }
        }*/
        lqw.like(StringUtils.isNotBlank(bo.getNickName()), SysUser::getNickName, bo.getNickName());
        lqw.eq(bo.getSid() != null, TpYear::getSid, bo.getSid());
        lqw.in(bo.getUserIds() != null, TpYear::getSid, bo.getUserIds());
        lqw.eq(StringUtils.isNotBlank(bo.getYear()), TpYear::getYear, bo.getYear());
        lqw.eq(bo.getGeren() != null, TpYear::getGeren, bo.getGeren());
        lqw.eq(bo.getGongsi() != null, TpYear::getGongsi, bo.getGongsi());
        lqw.eq(bo.getAddTime() != null, TpYear::getAddTime, bo.getAddTime());
        return lqw;
    }

    public int getDataScope() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        List<String> ids = loginUser != null ?
            loginUser.getRoles().stream().filter(Objects::nonNull).map(role -> role.getDataScope()).filter(Objects::nonNull).collect(Collectors.toList()) :
            Collections.emptyList();

        if (ids.contains("1")) {
            return 1;
        } else if (ids.contains("2")) {
            return 2;
        } else if (ids.contains("3")) {
            return 3;
        } else if (ids.contains("4")) {
            return 4;
        } else if (ids.contains("5")) {
            return 5;
        }
        return 0;
    }

    public List<Long> getDeptIds(){
        LoginUser loginUser = LoginHelper.getLoginUser();
        List<Long> roleIds = loginUser.getRoles().stream().map(RoleDTO::getRoleId).collect(Collectors.toList());
        List<Long> getDeptIds = roleDeptMapper.selectList(new LambdaQueryWrapper<SysRoleDept>().in(SysRoleDept::getRoleId, roleIds)).stream().map(SysRoleDept::getDeptId).collect(Collectors.toList());
        return getDeptIds.stream().distinct().collect(Collectors.toList());
    }

    /**
     * 新增年目标
     *
     * @param bo 年目标
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(TpYearBo bo) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        DateTime now = DateTime.now();
        int year = now.year();
        boolean exists = baseMapper.exists(new LambdaQueryWrapper<TpYear>().eq(TpYear::getSid,bo.getSid()).eq(TpYear::getYear, bo.getYear()));
        if(exists){
            throw new ServiceException("该用户已存在该年的目标，请勿重复添加！");
        }
//        bo.setSid(bo.getSid());
//        bo.setYear(String.valueOf(year));
        bo.setAddTime(new Date());

        SysDept dept = deptMapper.selectById(bo.getDeptId());
        bo.setDeptId(dept.getDeptId());
        bo.setAncestors(dept.getAncestors());

        TpYear add = MapstructUtils.convert(bo, TpYear.class);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改年目标
     *
     * @param bo 年目标
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(TpYearBo bo) {
        /*LoginUser loginUser = LoginHelper.getLoginUser();
        DateTime now = DateTime.now();
        int year = now.year();
        TpYear update = baseMapper.selectOne(new LambdaQueryWrapper<TpYear>().eq(TpYear::getSid,loginUser.getUserId()).eq(TpYear::getYear, year));
        if (update != null) {
            update.setGeren(bo.getGeren());
            update.setAddTime(new Date());
            return baseMapper.updateById(update) > 0;
        }
        bo.setSid(loginUser.getUserId());
        bo.setYear(String.valueOf(year));*/
        bo.setAddTime(new Date());
        TpYear add = MapstructUtils.convert(bo, TpYear.class);
        return baseMapper.updateById(add) > 0;
    }

    /**
     * 校验并批量删除年目标信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public TpYearVo queryTpYear(TpYearBo yearBo) {
        return baseMapper.selectVoOne(new LambdaQueryWrapper<TpYear>().eq(TpYear::getSid, yearBo.getSid()).eq(TpYear::getYear, yearBo.getYear()));
    }
}
