package com.sv.service.common;

import com.common.Sms;
import com.enums.SmsEnum;
import com.github.pagehelper.PageHelper;
import com.sv.exception.api.ExceptionCodeTemplate;
import com.sv.mapper.SmsMapper;
import com.sv.service.api.MemberAuthService;
import com.sv.service.api.MemberService;
import com.ydd.framework.core.common.Pagination;
import com.ydd.framework.core.common.sms.enums.SmsPlatformEnum;
import com.ydd.framework.core.common.sms.enums.SmsStatusEnum;
import com.ydd.framework.core.common.sms.enums.SmsTypeEnum;
import com.ydd.framework.core.common.utils.ValidationUtils;
import com.ydd.framework.core.entity.enums.StatusEnum;
import com.ydd.framework.core.exception.ServiceException;
import com.ydd.framework.core.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * Service - 短信
 *
 * @author lh
 * @since 2018-08-01
 */
@Service
@Transactional(readOnly = true)
public class SmsService extends BaseServiceImpl {

    private final Logger logger = LoggerFactory.getLogger(SmsService.class);

    @Resource
    private SmsMapper smsMapper;

    @Resource
    private MemberService memberService;

    @Resource
    private MemberAuthService memberAuthService;

    @Resource
    private CaptchaCacheServiceImpl captchaCacheService;

    @Resource
    private JuheSmsProvider juheSmsProvider;

    /**
     * 创建短信
     *
     * @param sms 短信
     */
    @Transactional
    public void create(Sms sms) {
        smsMapper.insert(sms);
    }

    /**
     * 发送注册验证码
     * type 1绑定手机，2手机号码注册
     *
     * @param mobile 手机号码
     */
    @Transactional
    public void sendRegisterCaptcha(String mobile, Integer type) {
        ValidationUtils.assertNotBlank(mobile, "请输入手机号码");
        ValidationUtils.assertMobile(mobile);

        // 验证码手机号码是否存在
        String prefix = ApiConstants.REGISTER_SMS_CAPTCHA_PREFIX;
        if (type == 2) {
            if (memberService.isMobileExists(mobile, null)) {
                // 手机号码已存在
                throw new ServiceException(ExceptionCodeTemplate.MOBILE_EXISTS);
            }
        }
        if (type == 1) {
            prefix = ApiConstants.PHONE_SMS_CAPTCHA_PREFIX;
            if (memberAuthService.isMobileExists(mobile, null)) {
                // 手机号码已存在
                throw new ServiceException("手机号码已被绑定");
            }
        }


        String captcha = generateRandomCaptcha();
        String tplValue = "#code#=" + captcha;
        String content = "【智慧云馆】您的验证码是" + captcha + "。如非本人操作，请忽略本短信";
        juheSmsProvider.send(mobile, 96450, tplValue, content);

        // 放入缓存中
        captchaCacheService.setCaptcha(mobile, captcha, ApiConstants.CAPTCHA_EXPIRED_IN, prefix);
    }

    /**
     * 发送登录验证码
     *
     * @param mobile 手机号码
     */
    @Transactional
    public void sendLoginCaptcha(String mobile) {
        ValidationUtils.assertNotBlank(mobile, "请输入手机号码");
        ValidationUtils.assertMobile(mobile);

        if (!memberService.isMobileExists(mobile, null)) {
            // 手机号码不存在
            throw new ServiceException(ExceptionCodeTemplate.LOGIN_ERROR);
        }

        // 生成随机验证码
        String randomStr = generateRandomCaptcha();
        String tplValue = "#code#=" + randomStr;
        String content = "【智慧云馆】您的验证码是" + randomStr + "。如非本人操作，请忽略本短信";
        juheSmsProvider.send(mobile, 96450, tplValue, content);

        // 放入缓存中
        captchaCacheService.setCaptcha(mobile, randomStr, ApiConstants.CAPTCHA_EXPIRED_IN, ApiConstants.LOGIN_SMS_CAPTCHA_PREFIX);
    }

    /**
     * 发送修改手机号码验证码
     *
     * @param mobile 手机号码
     */
    @Transactional
    public void sendUpdatePhoneCaptcha(String mobile) {
        ValidationUtils.assertNotBlank(mobile, "请输入手机号码");
        ValidationUtils.assertMobile(mobile);

        if (memberService.isMobileExists(mobile, null)) {
            // 手机号码已存在
            throw new ServiceException(ExceptionCodeTemplate.PHONE_ERROR);
        }

        // 生成随机验证码
        String randomStr = generateRandomCaptcha();
        String tplValue = "#code#=" + randomStr;
        String content = "【智慧云馆】您的验证码是" + randomStr + "。如非本人操作，请忽略本短信";
        juheSmsProvider.send(mobile, 96450, tplValue, content);

        // 放入缓存中
        captchaCacheService.setCaptcha(mobile, randomStr, ApiConstants.CAPTCHA_EXPIRED_IN, ApiConstants.UPDATE_PHONE_SMS_CAPTCHA_PREFIX);
    }

    /**
     * 生成随机验证码
     *
     * @return 验证码
     */
    private String generateRandomCaptcha() {
        return RandomUtils.nextInt(1000, 10000) + "";
    }

    /**
     * 更新短信
     *
     * @param sms 短信
     */
    @Transactional
    public void update(Sms sms) {
        smsMapper.update(sms);
    }

    /**
     * 删除短信
     *
     * @param id 编号
     * @return 删除数量
     */
    @Transactional
    public Integer delete(Integer id) {
        if (id == null || id <= 0) {
            return 0;
        }
        return smsMapper.delete(id);
    }

    /**
     * 删除短信
     *
     * @param ids 编号数组
     * @return 删除数量
     */
    @Transactional
    public Integer deleteByIds(Integer[] ids) {
        if (ids == null || ids.length == 0) {
            return 0;
        }
        return smsMapper.deleteByIds(ids);
    }

    /**
     * 查询短信
     *
     * @param id 编号
     * @return 短信
     */
    public Sms findById(Integer id) {
        return smsMapper.findById(id);
    }

    /**
     * 查询短信
     *
     * @param pagination 分页信息
     * @return 分页结果
     */
    public Pagination findPage(Pagination pagination) {
        PageHelper.startPage(pagination.getPage(), pagination.getPageSize());
        PageHelper.orderBy("id desc");
        pagination.setQueryResult(smsMapper.findAll());
        return pagination;
    }

    /**
     * 更新状态
     *
     * @param ids    编号
     * @param status 状态
     * @return 更新数量
     */
    @Transactional
    public Integer updateStatus(Integer[] ids, Byte status) {
        if (ids == null) {
            return 0;
        }
        if (status == null) {
            status = StatusEnum.DISABLE.value;
        }

        return smsMapper.updateStatus(ids, status);
    }

    /**
     * 更新状态
     *
     * @param id     编号
     * @param status 状态
     * @return 更新数量
     */
    @Transactional
    public Integer updateStatus(Integer id, Byte status) {
        if (id == null) {
            return 0;
        }
        if (status == null) {
            status = StatusEnum.DISABLE.value;
        }

        return smsMapper.updateStatus(new Integer[]{id}, status);
    }

    /**
     * 记录短信
     *
     * @param mobile   手机号码
     * @param content  短信内容
     * @param type     类型
     * @param status   状态
     * @param platform 平台
     */
    @Transactional
    public void record(String mobile, String content, SmsTypeEnum type, SmsStatusEnum status, SmsEnum platform) {
        ValidationUtils.assertNotNull(mobile, content, type, status, platform);
        ValidationUtils.assertMobile(mobile);

        // 保存短信内容
        Sms sms = new Sms();
        sms.setMobile(mobile);
        sms.setContent(content);
        sms.setType(type.value);
        sms.setStatus(status.value);
        sms.setPlatform(platform.value);
        create(sms);
    }
}

