package com.sckw.system.dubbo;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sckw.core.exception.SystemException;
import com.sckw.core.model.constant.Global;
import com.sckw.core.model.page.PageHelperUtil;
import com.sckw.core.model.page.PageResult;
import com.sckw.core.utils.BeanUtils;
import com.sckw.core.utils.CollectionUtils;
import com.sckw.core.utils.PasswordUtils;
import com.sckw.core.web.constant.HttpStatus;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.system.api.RemoteUserService;
import com.sckw.system.api.model.dto.req.*;
import com.sckw.system.api.model.dto.res.*;
import com.sckw.system.dao.KwsEnterpriseDao;
import com.sckw.system.dao.KwsUserLoginDao;
import com.sckw.system.dao.SysAreaDao;
import com.sckw.system.dao.SysDictDao;
import com.sckw.system.model.*;
import com.sckw.system.model.pojo.FindEntUserPojo;
import com.sckw.system.model.pojo.FindMenuTreePojo;
import com.sckw.system.model.vo.req.FindListReqVo;
import com.sckw.system.model.vo.req.ForgetPasswordReqVo;
import com.sckw.system.model.vo.res.KwsMenuResVo;
import com.sckw.system.model.vo.res.KwsUserResVo;
import com.sckw.system.service.*;
import jakarta.annotation.Resource;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Service;

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

/**
 * @author czh
 * @desc 远程接口
 * @date 2023/6/12
 */

@DubboService(group = "design", version = "1.0.0")
public class RemoteUserServiceImpl implements RemoteUserService {

    @Resource
    private RemoteBaseService remoteBaseService;

    @Resource
    private KwsUserService kwsUserService;

    @Resource
    private KwsRoleService kwsRoleService;

    @Resource
    private KwsMenuService kwsMenuService;

    @Resource
    private KwsUserLoginDao kwsUserLoginDao;

    @Resource
    private KwsEnterpriseService kwsEnterpriseService;

    @Resource
    private KwsEnterpriseDao kwsEnterpriseDao;

    @Resource
    private SysDictDao sysDictDao;

    @Resource
    private SysAreaDao sysAreaDao;

    @Resource
    private CommonService commonService;


    @Override
    public KwsEnterpriseResDto queryEnterpriseById(Long id) {
        return remoteBaseService.queryEnterpriseById(id);
    }

    @Override
    public List<KwsRoleResDto> queryRoleInfoByUserId(Long userId) {
        return remoteBaseService.queryRoleInfoByUserId(userId);
    }

    @Override
    public List<UserAccessMenuInfoResDto> queryUserAccessMenu(long id) {
        FindMenuTreePojo findMenuTreePojo = new FindMenuTreePojo();
        List<KwsUserRole> kwsUserRoles = kwsRoleService.findAllByUserId(id);
        if (CollectionUtils.isEmpty(kwsUserRoles)) {
            return Collections.emptyList();
        }
        findMenuTreePojo.setRoleIds(kwsUserRoles.stream().map(KwsUserRole::getRoleId).toList());

        List<KwsMenuResVo> kwsMenuResVos = kwsMenuService.findList(findMenuTreePojo);
        if (CollectionUtils.isEmpty(kwsMenuResVos)) {
            return Collections.emptyList();
        }

        return BeanUtils.copyToList(kwsMenuResVos, UserAccessMenuInfoResDto.class);
    }

    @Override
    public void forgetPassword(ForgetPasswordReqDto reqDto) throws SystemException {
        com.sckw.system.model.vo.req.ForgetPasswordReqVo forgetPasswordReqVo = new ForgetPasswordReqVo();
        BeanUtils.copyProperties(reqDto, forgetPasswordReqVo);
        kwsUserService.forgetPassword(forgetPasswordReqVo);
    }

    @Override
    public void saveUserLogin(UserLoginReqDto userLoginReqDto) {
        KwsUserLogin kwsUserLogin = new KwsUserLogin();
        BeanUtils.copyProperties(userLoginReqDto, kwsUserLogin);
        kwsUserLoginDao.insert(kwsUserLogin);
    }

    @Override
    public UserLoginReqDto currentDayLogin(long userId) {
        KwsUserLogin kwsUserLogin = kwsUserLoginDao.currentDayLogin(userId);
        if (Objects.isNull(kwsUserLogin)) {
            return null;
        }
        UserLoginReqDto userLoginReqDto = new UserLoginReqDto();
        BeanUtils.copyProperties(kwsUserLogin, userLoginReqDto);
        return userLoginReqDto;
    }

    @Override
    public List<EntCertificateResDto> queryCertificateByEntId(Long entId) {
        return remoteBaseService.queryCertificateByEntId(entId);
    }

    @Override
    public List<EntCheckTrackResDto> checkTrackByEntId(Long entId) {
        return remoteBaseService.checkTrackByEntId(entId);
    }


    @Override
    public void updatePassword(UpdatePasswordReqDto updatePassword) {
        kwsUserService.updatePassword(updatePassword);
    }

    @Override
    public void resetPassword(Long id) {
        kwsUserService.resetPassword(id);
    }

    @Override
    public void bindManager(Long entId, Long userId) {
        KwsEnterprise kwsEnterprise = kwsEnterpriseService.queryKwsEnterpriseById(entId);
        if (Objects.isNull(kwsEnterprise)) {
            return;
        }
        kwsEnterprise.setManager(userId);
        if (kwsEnterpriseDao.update(kwsEnterprise) <= 0) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.INSERT_FAIL);
        }
    }

    @Override
    public Map<Long, SysDictResDto> querySysDictByIds(List<Long> ids) {
        List<SysDict> sysDictList = sysDictDao.selectByKeys(ids);
        if (CollectionUtils.isEmpty(sysDictList)) {
            return Collections.emptyMap();
        }
        List<SysDictResDto> sysDictResDtos = BeanUtils.copyToList(sysDictList, SysDictResDto.class);
        return sysDictResDtos.stream().collect(Collectors.toMap(SysDictResDto::getId, item -> item, (oldValue, newValue) -> newValue));
    }

    @Override
    public void checkRegisterParam(String entName, String phone, Integer systemType) {
        commonService.checkEntRepeat(entName, phone);
        kwsUserService.checkAccountValid(phone, systemType);
    }

    @Override
    public List<EntTypeResDto> queryEntTypeById(Long entId) {
        return remoteBaseService.queryEntTypeById(entId);
    }


    /**
     * @param reqDto{cityCode 区域code  entTypeList 企业类型  entIdList 企业id page 页数 pageSize页大小}
     * @return PageResult
     * @desc: 根据区域code和企业类型分页查询企业信息
     * @author: czh
     * @date: 2023/9/1
     */
    @Override
    public PageResult queryEntInfoByCityCodeAndEntTypesWithPage(QueryEntInfoByCityCodeAndEntTypesWithPageReqDto reqDto) {
        PageHelper.startPage(reqDto.getPage(), reqDto.getPageSize());
        List<KwsEnterprise> list = remoteBaseService.queryEntInfoByCityCodeAndEntTypesWithPage(reqDto.getCityCode(), reqDto.getEntTypeList(), reqDto.getEntIdList(), reqDto.getEntName());
        return PageHelperUtil.getPageResult(new PageInfo<>(list));
    }


    /**
     * @param id 用户id
     * @return List
     * @desc: 根据用户id查数据权限
     * @author: czh
     * @date: 2023/9/4
     */
    @Override
    public List<Long> queryAuthUserList(Long id) {
        if (Objects.isNull(id)) {
            return Collections.emptyList();
        }

        List<Long> list = new ArrayList<>();
        list.add(id);
        List<KwsRoleResDto> kwsRoleResDtos = remoteBaseService.queryRoleInfoByUserId(id);
        if (CollectionUtils.isEmpty(kwsRoleResDtos)) {
            return list;
        }

        List<KwsAuthority> kwsAuthorities = remoteBaseService.queryAuthorityByRoles(kwsRoleResDtos.stream().map(KwsRoleResDto::getId).toList());
        if (CollectionUtils.isEmpty(kwsAuthorities)) {
            return list;
        }

        List<Long> deptIds = kwsAuthorities.stream().map(KwsAuthority::getDeptId).toList();
        List<KwsUser> kwsUsers = remoteBaseService.queryUserByDeptIds(deptIds);
        if(CollectionUtils.isEmpty(kwsUsers)) {
            return list;
        }

        list.addAll(kwsUsers.stream().filter(item -> item.getIsMain().equals(Global.NO) && !item.getId().equals(id)).map(KwsUser::getId).distinct().toList());
        return list;
    }

    @Override
    public List<FindEntUserResDto> findEntUser(Long entId) {
        FindListReqVo findListReqVo = new FindListReqVo();
        findListReqVo.setId(entId);
        List<FindEntUserPojo> entUser = kwsEnterpriseService.findEntUser(findListReqVo);
        if(CollectionUtils.isEmpty(entUser)) {
            return Collections.emptyList();
        }
        return BeanUtils.copyToList(entUser,FindEntUserResDto.class);
    }


    /**
     * @param code 区域code
     * @desc: 查某区域下的所有区域
     * @author: czh
     * @date: 2023/10/8
     */
    @Override
    public List<AreaTreeFrontResDto> findAllArea(Integer code) {
        List<SysArea> list = sysAreaDao.findAllArea(code);
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        return BeanUtils.copyToList(list, AreaTreeFrontResDto.class);
    }

    /**
     * @param firmName 企业名称
     * @param entTypes 企业类型
     * @desc 根据企业名称搜索企业ID（适用于关键字搜索）
     * @author zk
     * @date 2023/10/11
     **/
    @Override
    public List<Long> findEntIds(List<Integer> entTypes, String firmName) {
        Map<String, Object> params  = new HashMap<>(Global.NUMERICAL_SIXTEEN){{
            put("entTypes", entTypes);
            put("firmName", firmName);
        }};
        List<KwsEnterprise> ents = remoteBaseService.findEnts(params);
        List<Long> endIds = new ArrayList<>();
        ents.forEach(ent -> endIds.add(ent.getId()));
        return endIds;
    }

    /**
     * @param entIds 企业ID
     * @param userName 用户名称
     * @desc 根据企业ID或用户名称搜索用户ID（适用于关键字搜索）
     * @author zk
     * @date 2023/10/11
     **/
    @Override
    public List<Long> findUserIds(List<Long> entIds, String userName) {
        Map<String, Object> params = new HashMap<>(Global.NUMERICAL_SIXTEEN){{
            put("entIds", entIds);
            put("userName", userName);
        }};
        List<KwsUserResVo> users = kwsUserService.findList(params);
        List<Long> userIds = new ArrayList<>();
        users.forEach(user -> userIds.add(user.getId()));
        return userIds;
    }


    /**
     * 根据用户名查用户信息
     * @param username 用户账号
     * @return
     */
    @Override
    public KwsUserResDto getUserByAccount(String username) {
        return remoteBaseService.getUserByAccount(username);
    }


    /**
     * 根据用户姓名模糊查用户信息
     * @param name 用户姓名
     * @return list
     */
    @Override
    public List<KwsUserResDto> getUserByName(String name) {
        return remoteBaseService.getUserByName(name);
    }

    @Override
    public List<KwsUserDeptResDto> queryUserDeptByUserId(Long userId) {
        return remoteBaseService.queryUserDeptByUserId(userId);
    }

    @Override
    public List<KwsDeptResDto> queryDeptByIds(List<Long> ids) {
        return remoteBaseService.queryDeptByIds(ids);
    }

    @Override
    public void register(RegisterReqDto reqDto) throws SystemException {
        kwsUserService.register(reqDto);
    }

    @Override
    public void checkPassword(String password, String currentPwd) throws SystemException {
        kwsUserService.checkPassword(password, currentPwd);
    }

    @Override
    public List<KwsUserResDto> checkUserBase(String account, int systemType) throws SystemException {
        KwsUser kwsUser = kwsUserService.checkUserBase(account, systemType);
        KwsUserResDto kwsUserService = new KwsUserResDto();
        BeanUtils.copyProperties(kwsUser, kwsUserService);
        return Collections.singletonList(kwsUserService);
    }

}
