package com.hc.business.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hc.business.dto.*;
import com.hc.business.mapper.UserMapper;
import com.hc.business.model.User;
import com.hc.business.model.jwt.GenerateAuthToken;
import com.hc.business.model.login.AccessEntity;
import com.hc.business.model.login.AuthEntity;
import com.hc.business.service.UserService;
import com.hc.core.utils.enums.InfoEnum;
import com.hc.core.utils.exception.ResponseException;
import com.hc.core.utils.msm.MessageService;
import com.hc.core.utils.tool.IdGenerator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 用户表(User)表服务实现类
 *
 * @author java
 * @since 2020-11-09 10:04:14
 */

@Service("userService")
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    private final MessageService messageService;

    private final GenerateAuthToken generateAuthToken;

    public UserServiceImpl(UserMapper userMapper,
                           MessageService messageService,
                           GenerateAuthToken generateAuthToken) {
        this.userMapper = userMapper;
        this.messageService = messageService;
        this.generateAuthToken = generateAuthToken;
    }

    /**
     * 通过ID查询单条数据
     *
     * @param userId 主键
     * @return 实例对象
     */
    @Override
    public User queryById(Integer userId) {
        return this.userMapper.selectByPrimaryKey(userId);
    }

    /**
     * 新增数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Override
    public User insert(User user) {
        String userMobile = user.getUserMobile();
        List<User> users = queryByMobile(userMobile);
        if (!CollectionUtils.isEmpty(users)) {
            return users.get(0);
        }
        user.setCreateTime(System.currentTimeMillis());
        user.setUserType(1);
        String userPass = StringUtils.substring(userMobile, 5, 11);
        user.setUserPassword(IdGenerator.passwordToHash(userPass));
        this.userMapper.insert(user);
        return user;
    }

    /**
     * 修改数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Override
    public User update(User user) {
        String userPassword = user.getUserPassword();
        if (!Objects.isNull(userPassword)) {
            user.setUserPassword(IdGenerator.passwordToHash(userPassword));
        }
        this.userMapper.updateByPrimaryKeySelective(user);
        return this.queryById(user.getUserId());
    }

    @Override
    public User updateMobile(User user) {
        this.userMapper.updateByPrimaryKeySelective(user);
        return this.queryById(user.getUserId());
    }

    /**
     * 通过主键删除数据
     *
     * @param userId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer userId) {
        return this.userMapper.deleteByPrimaryKey(userId) > 0;
    }

    /**
     * 分页查询多条数据
     *
     * @param page 页码
     * @param size 查询条数
     * @return 对象列表
     */
    @Override
    public PageInfo queryAllByLimit(int page, int size) {
        return PageHelper.startPage(page, size).doSelectPageInfo(this.userMapper::selectAll);
    }

    @Override
    public AccessEntity userLogin(AuthEntity authEntity) {
        String userMobile = authEntity.getUserName().trim();
        List<User> users = queryByMobile(userMobile);
        if (CollectionUtils.isEmpty(users)) {
            throw new ResponseException(InfoEnum.LOGIN_USER_NAME_ERROR);
        }
        User user1 = users.get(0);
        String userPassword = user1.getUserPassword();
        validatePass(authEntity, userPassword);
        return generateAuthToken.generateToken(authEntity, user1, null);
    }

    @Override
    public AccessEntity userLoginSms(SmsLoginDto smsLoginDto) {
        String sessionId = smsLoginDto.getSessionId();
        String code = smsLoginDto.getCode();
        //校验验证码
        validCode(sessionId, code);
        //登录
        String userMobile = smsLoginDto.getUserMobile().trim();
        List<User> users = queryByMobile(userMobile);
        AuthEntity authEntity = new AuthEntity();
        authEntity.setUserName(userMobile);
        authEntity.setPassword(StringUtils.substring(userMobile, 5, 11));
        if (!CollectionUtils.isEmpty(users)) {
            return generateAuthToken.generateToken(authEntity, users.get(0), null);
        }
        User user = new User();
        user.setUserMobile(userMobile);
        insert(user);
        return generateAuthToken.generateToken(authEntity, user, null);
    }

    /**
     * 密码校验
     *
     * @param authEntity 实例对象
     * @param userPass   实例对象
     */
    private void validatePass(AuthEntity authEntity, String userPass) {
        String password = IdGenerator.passwordToHash(authEntity.getPassword());
        if (!Objects.equals(password, userPass)) {
            throw new ResponseException(InfoEnum.LOGIN_PASSWORD_ERROR);
        }
    }

    @Override
    public AccessEntity userRegister(RetrievePasswordDto retrievePasswordDto) {
        String sessionId = retrievePasswordDto.getSessionId();
        String code = retrievePasswordDto.getCode();
        //校验验证码
        validCode(sessionId, code);
        //查询重复用户
        String userMobile = retrievePasswordDto.getUserMobile().trim();
        String password = retrievePasswordDto.getPassword();
        String passwordToHash = IdGenerator.passwordToHash(password);
        String userGender = retrievePasswordDto.getUserGender().trim();
        String userCompany = retrievePasswordDto.getUserCompany().trim();
        String userEmail = retrievePasswordDto.getUserEmail().trim();

        //手机号注册
        List<User> users = queryByMobile(userMobile);
        if (!CollectionUtils.isEmpty(users)) {
            throw new ResponseException(InfoEnum.LOGIN_REGISTER_RE);
        }
        //注册用户
        User user = User.builder()
                .createTime(System.currentTimeMillis())
                .userMobile(userMobile)
                .userPassword(passwordToHash)
                .userName(retrievePasswordDto.getUserName())
                .userGender(userGender)
                .userCompany(userCompany)
                .userEmail(userEmail)
                .userType(1)
                .userLogo("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1605516088299&di=33e95d78e4ad99b4784665961f1af6e4&imgtype=0&src=http%3A%2F%2Fku.90sjimg.com%2Felement_origin_min_pic%2F01%2F48%2F88%2F16574444edb24ea.jpg")
                .build();
        this.userMapper.insertSelective(user);

        AuthEntity authEntity = new AuthEntity();
        authEntity.setUserName(userMobile);
        authEntity.setPassword(password);
        return generateAuthToken.generateToken(authEntity, user, null);
    }

    @Override
    public String sendAuthCode(String phone) {
        return messageService.sendValidShortMessage(phone);
    }

    @Override
    public User retrievePassword(RetrievePasswordDto retrievePasswordDto) {
        String sessionId = retrievePasswordDto.getSessionId();
        String code = retrievePasswordDto.getCode();
        //校验验证码
        validCode(sessionId, code);
        //修改密码
        String userMobile = retrievePasswordDto.getUserMobile().trim();
        List<User> users = queryByMobile(userMobile);
        assert users.size() != 0;
        User user = users.get(0);
        String password = retrievePasswordDto.getPassword().trim();
        user.setUserPassword(password);
        return update(user);
    }




    @Override
    public List<User> queryByMobile(String userMobile) {
        return userMapper.queryUserByMobile(userMobile);
    }

    @Override
    public List<User> queryUserByCard(String cardId) {
        return userMapper.queryOneByCardId(cardId);
    }

    @Override
    public List<User> queryUserByName(String name) {
        return userMapper.queryUserByName(name);
    }

    @Override
    public List<UserListDto> queryUserByClassName(String name, int pay) {

        if((null == name) || (name.isEmpty())){
            return null;
        }else {

            if(1 == pay){
                //只搜已经支付得
                return  this.userMapper.queryUserByClassNameAndPay(name);

            }else {

                //所有订单
                return this.userMapper.queryUserByClassName(name);
            }

        }
    }



    @Override
    public UserTimeTotal queryUserCount() {
        UserTimeTotal userTimeTotal = new UserTimeTotal();
        userTimeTotal.setTotalUserCount(this.userMapper.queryTotal());
        userTimeTotal.setTodayUserCount(checkNullInt(this.userMapper.queryToday()));
        userTimeTotal.setMonthUserCount(checkNullInt(this.userMapper.queryMonth()));
        userTimeTotal.setYearUserCount(checkNullInt(this.userMapper.queryYear()));
        return userTimeTotal;
    }

    private int checkNullInt(Integer count) {
        if (Objects.isNull(count)) {
            return 0;
        }
        return count;
    }

    @Override
    public List<StaTimeTable> queryByUserCount() {
        List<StaTimeTable> staTimeTableList = this.userMapper.queryByUserCount();
        Collections.reverse(staTimeTableList);
        return staTimeTableList;
    }

    private void validCode(String sessionId, String code) {
        boolean b = messageService.validCode(
                sessionId,
                code);
        if (!b) {
            throw new ResponseException(InfoEnum.AUTHCODE_ERROR);
        }
    }


}