package com.docus.server.service.impl;

import com.docus.infrastructure.core.db.KeyGenerator;
import com.docus.infrastructure.core.db.dao.IBaseDao;
import com.docus.infrastructure.redis.service.IdService;
import com.docus.infrastructure.shiro.ShiroUtil;
import com.docus.infrastructure.web.exception.ApiException;
import com.docus.infrastructure.web.exception.ExceptionCode;
import com.docus.infrastructure.web.request.SearchDTO;
import com.docus.infrastructure.web.response.PageResult;
import com.docus.server.common.auth.RedisStringService;
import com.docus.server.constants.BusinessConstant;
import com.docus.server.convert.RcvSysUserConvert;
import com.docus.server.dto.recovery.rcvsysuser.AddRcvSysUserDTO;
import com.docus.server.dto.recovery.rcvsysuser.DeleteRcvSysUserDTO;
import com.docus.server.dto.recovery.rcvsysuser.EditRcvSysUserDTO;
import com.docus.server.entity.recovery.RcvSysUser;
import com.docus.server.enums.EffectiveEnum;
import com.docus.server.infrastructure.dao.IRcvSysUserDao;
import com.docus.server.service.IRcvSysUserService;
import com.docus.server.vo.recovery.UserInfoView;
import com.docus.server.vo.recovery.rcvsysuser.RcvSysUserVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 系统登录用户表 服务实现类
 *
 * @author AutoGenerator
 * @since 2023-09-13
 */
@Service
public class RcvSysUserServiceImpl implements IRcvSysUserService {
    @Resource
    private IRcvSysUserDao iRcvSysUserDao;
    @Resource
    private IdService idService;
    @Resource
    private RedisStringService redisStringService;

    /**
     * 按主键查询
     *
     * @param id 主键Id
     * @return 实体
     */
    @Override
    public RcvSysUserVO findById(Serializable id) {
        return RcvSysUserConvert.INSTANCE.convertVO(iRcvSysUserDao.findById(id));
    }

    /**
     * 按主键集合查询
     *
     * @param ids 主键ids
     * @return 实体列表
     */
    @Override
    public List<RcvSysUserVO> findByIds(List<Serializable> ids) {
        return RcvSysUserConvert.INSTANCE.convertVO(iRcvSysUserDao.findByIds(ids));
    }

    /**
     * 按属性查询
     *
     * @param propertyName  属性名
     * @param propertyValue 属性值
     * @return 实体列表
     */
    @Override
    public List<RcvSysUserVO> findBy(String propertyName, Object propertyValue) {
        return RcvSysUserConvert.INSTANCE.convertVO(iRcvSysUserDao.findBy(propertyName, propertyValue));
    }

    /**
     * 按属性查询
     *
     * @param propertyName  属性名
     * @param propertyValue 属性值
     * @return 实体列表
     */
    @Override
    public List<RcvSysUserVO> findBy(String propertyName, Collection<?> propertyValue) {
        return RcvSysUserConvert.INSTANCE.convertVO(iRcvSysUserDao.findBy(propertyName, propertyValue));
    }

    /**
     * 按属性查询
     *
     * @param propertyName  属性名
     * @param propertyValue 属性值
     * @return 实体
     */
    @Override
    public RcvSysUserVO findOneBy(String propertyName, Object propertyValue) {
        return RcvSysUserConvert.INSTANCE.convertVO(iRcvSysUserDao.findOneBy(propertyName, propertyValue));
    }

    /**
     * 按属性查询
     *
     * @param propertyName  属性名
     * @param propertyValue 属性值
     * @return 实体
     */
    @Override
    public RcvSysUserVO findOneBy(String propertyName, Collection<?> propertyValue) {
        return RcvSysUserConvert.INSTANCE.convertVO(iRcvSysUserDao.findOneBy(propertyName, propertyValue));
    }

    /**
     * 查询所有
     *
     * @return 实体列表
     */
    @Override
    public List<RcvSysUserVO> findAll() {
        return RcvSysUserConvert.INSTANCE.convertVO(iRcvSysUserDao.findAll());
    }

    /**
     * 关键字搜索
     *
     * @param searchDTO 搜索参数
     * @return 分页列表
     */
    @Override
    public PageResult<RcvSysUserVO> search(SearchDTO searchDTO) {
        return RcvSysUserConvert.INSTANCE.convertVO(iRcvSysUserDao.search(searchDTO));

        //PageResult<RcvSysUserVO> result = RcvSysUserConvert.INSTANCE.convertVO(iRcvSysUserDao.search(searchDTO));

        //if (CollectionUtils.isEmpty(result.getList())) {
        //return new PageResult<>();
        //}

        //Map<String, SchSystemParams> map = iSchSystemParamsService.find(ListUtils.distinctSelect(result.getList(), SchCollectorVO::getCollectorId));

        //result.getList().forEach(p -> {
        // String collectorId = String.valueOf(p.getCollectorId());
        // if (map.containsKey(collectorId)) {
        //     p.setCollectorName(map.get(collectorId).getParamName());
        // }
        //});

        //return result;
    }

    /**
     * 新增
     *
     * @param addRcvSysUserDTO 编辑参数
     * @return 成功或失败
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(AddRcvSysUserDTO addRcvSysUserDTO) {
        RcvSysUser rcvSysUser = RcvSysUserConvert.INSTANCE.convertDO(addRcvSysUserDTO);
        rcvSysUser.setUserId(idService.getDateSeq());
        return iRcvSysUserDao.add(rcvSysUser);

        // String name = addRcvSysUserDTO.getName();

        //RcvSysUser rcvSysUser = iRcvSysUserDao.findOneBy("name", name);

        //if (Func.notNull(rcvSysUser)) {
        // throw new ApiException(ExceptionCode.ParamIllegal.getCode(), "系统登录用户表已经存在");
        // }

        // RcvSysUser rcvSysUser =RcvSysUserConvert.INSTANCE.convertDO(addRcvSysUserDTO);
        // rcvSysUser.setId(idService.getDateSeq());

        // return iRcvSysUserDao.add(schCollector);

    }

    /**
     * 批量新增
     *
     * @param addRcvSysUserDTOList 编辑参数
     * @return 成功或失败
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addBatch(List<AddRcvSysUserDTO> addRcvSysUserDTOList) {

        List<RcvSysUser> rcvSysUserList = RcvSysUserConvert.INSTANCE.convertAddDOList(addRcvSysUserDTOList);

        rcvSysUserList.forEach(p -> {
            p.setUserId(idService.getDateSeq());
        });

        return iRcvSysUserDao.saveBatch(rcvSysUserList, IBaseDao.DEFAULT_BATCH_SIZE);
    }

    /**
     * 新增或编辑
     *
     * @param editRcvSysUserDTO 新增或编辑参数
     * @return 成功或失败
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addOrEdit(EditRcvSysUserDTO editRcvSysUserDTO) {
        RcvSysUser rcvSysUser = RcvSysUserConvert.INSTANCE.convertDO(editRcvSysUserDTO);
        return iRcvSysUserDao.saveOrUpdate(rcvSysUser);
    }

    /**
     * 批量新增或编辑
     *
     * @param editRcvSysUserDTOList 新增或编辑参数
     * @return 成功或失败
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addOrEditBatch(List<EditRcvSysUserDTO> editRcvSysUserDTOList) {
        List<RcvSysUser> rcvSysUserList = RcvSysUserConvert.INSTANCE.convertEditDOList(editRcvSysUserDTOList);
        return iRcvSysUserDao.saveOrUpdateBatch(rcvSysUserList, IBaseDao.DEFAULT_BATCH_SIZE);
    }

    /**
     * 编辑
     *
     * @param editRcvSysUserDTO 编辑参数
     * @return 成功或失败
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean edit(EditRcvSysUserDTO editRcvSysUserDTO) {
        RcvSysUser rcvSysUser = RcvSysUserConvert.INSTANCE.convertDO(editRcvSysUserDTO);
        return iRcvSysUserDao.edit(rcvSysUser);

        // Long id = editRcvSysUserDTO.getId();

        //  RcvSysUser rcvSysUser = iRcvSysUserDao.findById(id);

        // if (Func.isNull(rcvSysUser)) {
        //     throw new ApiException(ExceptionCode.ParamIllegal.getCode(), "系统登录用户表，无法更新！");
        // }

        // rcvSysUser.setUpdateTime(LocalDateTime.now());
        // return iRcvSysUserDao.edit(rcvSysUser);
    }

    /**
     * 批量编辑
     *
     * @param editRcvSysUserDTOList 编辑参数
     * @return 成功或失败
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean editBatchById(List<EditRcvSysUserDTO> editRcvSysUserDTOList) {
        List<RcvSysUser> rcvSysUserList = RcvSysUserConvert.INSTANCE.convertEditDOList(editRcvSysUserDTOList);
        return iRcvSysUserDao.updateBatchById(rcvSysUserList, IBaseDao.DEFAULT_BATCH_SIZE);
    }

    /**
     * 批量删除
     *
     * @param deleteRcvSysUserDTO 删除参数
     * @return 成功或失败
     */
    @Override
    public int delete(DeleteRcvSysUserDTO deleteRcvSysUserDTO) {
        return iRcvSysUserDao.delete(deleteRcvSysUserDTO.getIds());
    }

    /**
     * 按主键删除
     *
     * @param id 删除参数
     * @return 成功或失败
     */
    @Override
    public int delete(Serializable id) {
        return iRcvSysUserDao.delete(id);
    }

    /**
     * 按属性删除
     *
     * @param propertyName  删除属性名
     * @param propertyValue 删除属性值
     * @return 成功或失败
     */
    @Override
    public int deleteBy(String propertyName, Object propertyValue) {
        return iRcvSysUserDao.deleteBy(propertyName, propertyValue);
    }

    /**
     * 按属性删除
     *
     * @param propertyName  删除属性名
     * @param propertyValue 删除属性值集合
     * @return 成功或失败
     */
    @Override
    public int deleteBy(String propertyName, Collection<?> propertyValue) {
        return iRcvSysUserDao.deleteBy(propertyName, propertyValue);
    }

    /**
     * 按主键集合批量删除
     *
     * @param ids 删除参数
     * @return 成功或失败
     */
    @Override
    public int deleteByIds(Collection<? extends Serializable> ids) {
        return iRcvSysUserDao.deleteByIds(ids);
    }

    /**
     * 名称不重复
     *
     * @param id   主键
     * @param name 名称
     * @return 名称重复数量
     */
    @Override
    public int findByIdAndName(Serializable id, String name) {
        return iRcvSysUserDao.findByIdAndName(id, name);
    }

    @Override
    public String doLogin(String userName, String userPwd) {
        if (StringUtils.isBlank(userName) || StringUtils.isBlank(userPwd)) {
            throw new ApiException(ExceptionCode.ParamIllegal.getCode(), "用户名或密码不能为空！");
        }
        RcvSysUser user = iRcvSysUserDao.findOneBy("userName", userName);
        String md5Pwd = ShiroUtil.md5(userPwd, null);
        if (user == null) {
            throw new ApiException(ExceptionCode.ParamIllegal.getCode(), "登录失败，用户不存在！");
        }
        if (!EffectiveEnum.EFFECTIVE.equals(user.getEffective())) {
            throw new ApiException(ExceptionCode.ParamIllegal.getCode(), "登录失败，用户状态未启用！");
        }
        if (!user.getUserPwd().equals(md5Pwd)) {
            throw new ApiException(ExceptionCode.ParamIllegal.getCode(), "登录失败：密码错误！");
        }


        String token = KeyGenerator.genId();
        UserInfoView userInfoview = new UserInfoView();
        userInfoview.setToken(token);
        userInfoview.setUserName(userName);
        userInfoview.setUserId(userName);
        userInfoview.setPassword(userPwd);
        redisStringService.setValue(BusinessConstant.REDIS_KEY_USER_TOKEN_PREFIX + token, userInfoview, 3, TimeUnit.MINUTES);

        return token;
    }

    @Override
    public void logout() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String token = request.getHeader(BusinessConstant.HEADER_API_TOKEN);
        redisStringService.delete(BusinessConstant.REDIS_KEY_USER_TOKEN_PREFIX + token);

    }

}

