package com.miaxis.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miaxis.sms.ISmsService;
import com.miaxis.sms.domain.SmsParameter;
import com.miaxis.user.domain.UserImages;
import com.miaxis.user.domain.UserPay;
import com.miaxis.user.domain.UserRegister;
import com.miaxis.user.dto.UserDto;
import com.miaxis.user.mapper.UserInfoMapper;
import com.miaxis.user.mapper.UserPayMapper;
import com.miaxis.user.mapper.UserRegisterMapper;
import com.miaxis.user.service.IUserImagesService;
import com.miaxis.user.service.IUserInfoService;
import com.miaxis.user.vo.UserVo;
import com.miaxis.common.core.domain.Response;
import com.miaxis.common.core.domain.entity.SysUser;
import com.miaxis.common.core.domain.entity.UserInfo;
import com.miaxis.common.exception.CustomException;
import com.miaxis.common.utils.RedisPrefixUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户信息Service业务层处理
 *
 * @author miaxis
 * @date 2020-12-23
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {

    @Resource
    private UserInfoMapper userInfoMapper;//用户信息

    @Resource
    private UserRegisterMapper userRegisterMapper;//用户报名信息

    @Resource
    private IUserImagesService userImagesService;//用户图片信息

    @Autowired
    private ISmsService smsService;//短信服务

    @Resource
    private UserPayMapper userPayMapper;//缴费信息

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询用户信息
     *
     * @param id 用户信息ID
     * @return 用户信息
     */
    @Override
    public UserInfo selectUserInfoById(Long id){
        return userInfoMapper.selectUserInfoById(id);
    }

    /**
     * 查询用户信息
     *
     * @param mobile mobile
     * @return 用户信息
     */
    @Override
    public UserInfo selectUserInfoByMoble(String mobile){
        return userInfoMapper.selectUserInfoByMobile(mobile);
    }



    /**
     * 修改用户信息
     *
     * @param userInfo 用户信息
     * @return 结果
     */
    @Override
    public int updateUserInfo(UserInfo userInfo){
        return userInfoMapper.updateById(userInfo);
    }

    /**
     * 批量删除用户信息
     *
     * @param ids 需要删除的用户信息ID
     * @return 结果
     */
    @Override
    public int deleteUserInfoByIds(Long[] ids){
        return userInfoMapper.deleteUserInfoByIds(ids);
    }


    /**
     * 修改手机号
     * @param phone
     * @param verificationCode
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response modifyPhoneNumber(String phone,String verificationCode,SysUser user) {

        //生成短信缓存前缀
        String smsKeyPrefix = RedisPrefixUtils.getSmsKeyPrefix("modify", phone);
        String smsKeyCountPrefix = RedisPrefixUtils.getSmsKeyCountPrefix("modify", phone);

        //查看验证码是否过期
        if (redisTemplate.hasKey(smsKeyCountPrefix) &&
                !redisTemplate.hasKey(smsKeyPrefix)){
            throw new CustomException("验证码已过期,请重新验证!");
        }
        //比对缓存中的验证码
        String smsCodeValue = redisTemplate.opsForValue().get(smsKeyPrefix).toString();
        if (!verificationCode.equals(smsCodeValue)){
            throw new CustomException("验证码错误,请重新输入!");
        }

        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getUserId());
        userInfo.setPhone(phone);
        //更新绑定手机号
        userInfoMapper.updateById(userInfo);

        return Response.success();
    }

    /**
     * 保存用户报名信息
     * @param userDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response saveUserInformation(UserDto userDto) {

        //生成短信缓存前缀
        String smsKeyPrefix = RedisPrefixUtils.getSmsKeyPrefix("signUp", userDto.getPhone());
        String smsKeyCountPrefix = RedisPrefixUtils.getSmsKeyCountPrefix("signUp", userDto.getPhone());

        //查看验证码是否过期
        if (redisTemplate.hasKey(smsKeyCountPrefix) &&
                !redisTemplate.hasKey(smsKeyPrefix)){
            throw new CustomException("验证码已过期,请重新验证!");
        }
        //比对缓存中的验证码
        String smsCodeValue = redisTemplate.opsForValue().get(smsKeyPrefix).toString();
        if (!userDto.getVerificationCode().equals(smsCodeValue)){
            throw new CustomException("验证码错误,请重新输入!");
        }

        //用户信息表
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(userDto,userInfo);
        userInfo.setCardtype(1l);
        userInfoMapper.insert(userInfo);


        //用户报名信息表
        UserRegister userRegister = new UserRegister();
        userRegister.setUserId(userInfo.getId());
        userRegister.setInscode(userDto.getInscode());
        userRegister.setBmcx(userDto.getTraintype());
        userRegister.setCoachnum(userDto.getCoachnum());
        userRegister.setClassId(userDto.getSchoolClassTypeId());
        userRegisterMapper.insert(userRegister);

        //报名缴费信息
        UserPay userPay = new UserPay();
        userPay.setUserId(userInfo.getId());
        userPay.setPrice(userDto.getSchoolClassTypePrice());
        userPay.setPayType(4l);
        userPay.setPayStatus(0l);
        userPayMapper.insert(userPay);


        //用户图片信息
        List<UserImages> userImagesList = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            UserImages userImages = new UserImages();
            userImages.setUserId(userInfo.getId());
            switch(i){
                case 0 :
                    userImages.setFileUrl(userDto.getIdCardFrontUrl());
                    userImages.setFilePath(userDto.getIdCardFrontPath());
                    userImages.setImageType(1l);
                    userImagesList.add(userImages);
                    break;
                case 1 :
                    userImages.setFileUrl(userDto.getIdCardReverseUrl());
                    userImages.setFilePath(userDto.getIdCardReversePath());
                    userImages.setImageType(2l);
                    userImagesList.add(userImages);
                    break;
                case 2 :
                    userImages.setFileUrl(userDto.getFacesUrl());
                    userImages.setFilePath(userDto.getFacesPath());
                    userImages.setImageType(3l);
                    userImagesList.add(userImages);
                    break;
                default :
                    break;
            }
        }
        userImagesService.saveBatch(userImagesList);

        return Response.success(userInfo);

    }

    /**
     * 注册报名获取短信验证码
     * @param phone
     * @return
     */
    @Override
    public Response sendSignUpVerificationCode(String phone) {
        SmsParameter smsParameter = new SmsParameter();
        smsParameter.setPhone(phone);
        smsParameter.setType("signUp");

        return smsService.sendVerificationCode(smsParameter);
    }


    /**
     * 修改手机号获取短信验证码
     * @param user
     * @param phone
     * @return
     */
    @Override
    public Response sendModifyVerificationCode(SysUser user, String phone) {
        if (user.getPhonenumber().equals(phone)){
            throw new CustomException("该手机号与当前绑定的手机号相同!");
        }

        SmsParameter smsParameter = new SmsParameter();
        smsParameter.setPhone(phone);
        smsParameter.setType("modify");

        return smsService.sendVerificationCode(smsParameter);
    }

    /**
     * 获取我的报名信息
     * @param userId
     * @return
     */
    @Override
    public Response getMyRegistrationInformation(String userId) {
        UserVo userVo = userInfoMapper.getMyRegistrationInformation(userId);
        return Response.success(userVo);
    }


}
