package com.slodon.b2b2c.controller.member.front.advich;

import com.slodon.b2b2c.core.constant.RedisConst;
import com.slodon.b2b2c.core.constant.ResponseConst;
import com.slodon.b2b2c.core.controller.BaseController;
import com.slodon.b2b2c.core.i18n.Language;
import com.slodon.b2b2c.core.response.JsonResult;
import com.slodon.b2b2c.core.response.SldResponse;
import com.slodon.b2b2c.core.util.AssertUtil;
import com.slodon.b2b2c.core.util.Md5;
import com.slodon.b2b2c.core.util.StringUtil;
import com.slodon.b2b2c.dao.read.member.MemberReadMapper;
import com.slodon.b2b2c.dao.write.member.MemberWriteMapper;
import com.slodon.b2b2c.member.example.MemberExample;
import com.slodon.b2b2c.member.pojo.Member;
import com.slodon.b2b2c.model.member.MemberModel;
import com.slodon.b2b2c.model.member.advich.MemberEnquiryModel;
import com.slodon.b2b2c.model.member.advich.MemberRegisterActiveModel;
import com.slodon.b2b2c.model.seller.VendorModel;
import com.slodon.b2b2c.seller.dto.VendorRegisterDTO;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @author cyan
 */
@Api(tags = "front-邮箱会员激活管理")
@RestController
@RequestMapping("v3/member/front/active")
@Slf4j
public class MemberEmailActiveController extends BaseController {

    @Resource
    private MemberRegisterActiveModel memberRegisterActiveModel;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private MemberReadMapper memberReadMapper;

    @Resource
    private MemberWriteMapper memberWriteMapper;

    @Resource
    private MemberModel memberModel;

    @Resource
    private MemberEnquiryModel memberEnquiryModel;

    @Resource
    private VendorModel vendorModel;

//    /**
//     * @param request
//     * @param email
//     * @return
//     */
//    @GetMapping("/test")
//    public JsonResult<Object> sendEmailActiveLink(HttpServletRequest request, String email) {
//        if (StringUtil.isEmpty(email)) {
//            email = "cyan95@hotmail.com";
//        }
//        memberRegisterActiveModel.sendEmailActiveLink(email);
//        return SldResponse.success(Language.translate("发送验证邮件成功", Language.EN_LANGUAGE_TYPE));
//    }
//
//    /**
//     * @param request
//     * @param email
//     * @return
//     */
//    @GetMapping("/forget")
//    public JsonResult<Object> sendEmailForgetPasswordLink(HttpServletRequest request, String email) {
//        if (StringUtil.isEmpty(email)) {
//            email = "cyan95@hotmail.com";
//        }
//        memberRegisterActiveModel.sendEmailForgetPasswordLink(email, "cyan");
//        return SldResponse.success(Language.translate("发送验证邮件成功", Language.EN_LANGUAGE_TYPE));
//    }
//
//    /**
//     * @param request
//     * @param email
//     * @return
//     */
//    @GetMapping("/success")
//    public JsonResult<Object> sendRegisterSuccessEmail(HttpServletRequest request, String email) {
//        if (StringUtil.isEmpty(email)) {
//            email = "cyan95@hotmail.com";
//        }
//        memberRegisterActiveModel.sendRegisterSuccessEmail(email, "cyan");
//        return SldResponse.success(Language.translate("发送验证邮件成功", Language.EN_LANGUAGE_TYPE));
//    }
//
//    @GetMapping("/sms")
//    public JsonResult<Object> sendEnquirySms(HttpServletRequest request) {
//        memberEnquiryModel.sendEnquirySms(null);
//        return SldResponse.success();
//    }
//
//    @GetMapping("/sms/vendor")
//    public JsonResult<Object> sendVendorRegisterOkSms(HttpServletRequest request) {
//        VendorRegisterDTO vendorRegisterDTO = new VendorRegisterDTO();
//        vendorRegisterDTO.setVendorMobile("18762032916");
//        vendorModel.sendVendorRegisterOkSms(vendorRegisterDTO);
//        return SldResponse.success();
//    }

    /**
     * 发送用户邮箱注册链接
     *
     * @param request
     * @param email
     * @param source
     * @return
     */
    @PostMapping("/link")
    public JsonResult<Object> getMemberEmailLink(HttpServletRequest request, String email, Integer source) {
        log.info("getMemberEmailLink - email:{},source:{}", email, source);
        if (StringUtil.isEmpty(email)) {
            return SldResponse.fail(Language.translate("邮件不能为空", Language.EN_LANGUAGE_TYPE));
        }
        AssertUtil.emailCheck(email);

        int count = memberRegisterActiveModel.sendRegisterUserEmail(email, source);
        AssertUtil.isTrue((count == 0), Language.translate("发送验证邮件失败，请重试", Language.EN_LANGUAGE_TYPE));
        AssertUtil.isTrue((count == 2), Language.translate("该邮箱已注册，请登录", Language.EN_LANGUAGE_TYPE));
        return SldResponse.success(Language.translate("发送验证邮件成功", Language.EN_LANGUAGE_TYPE));
    }

    /**
     * 用户邮箱链接激活
     *
     * @param request
     * @param email
     * @param code
     * @param verifyKey
     * @param verifyCode
     * @param nickName
     * @param password
     * @return
     */
    @PostMapping("/email")
    public JsonResult<Object> activeMemberEmailInfo(HttpServletRequest request, String email, String code, String verifyKey, String verifyCode, String nickName, String password) {
        log.info("activeMemberEmailInfo - email:{},code:{},verifyKey:{},verifyCode:{},nickName:{},password:{}", email, code, verifyKey, verifyCode, nickName, password);
        if (StringUtil.isEmpty(email) || StringUtil.isEmpty(code)) {
            return SldResponse.fail(ResponseConst.STATE_FAIL, Language.translate("注册链接不正确，请重新注册", Language.EN_LANGUAGE_TYPE));
        }

        //获得redis中的验证码
        String verify_number = stringRedisTemplate.opsForValue().get(verifyKey);
        AssertUtil.isTrue(verify_number == null || !verify_number.equalsIgnoreCase(verifyCode), Language.translate("图形验证码不正确", Language.EN_LANGUAGE_TYPE));

        MemberExample memberExample = new MemberExample();
        memberExample.setMemberEmail(email.toLowerCase());
        List<Member> memberList = memberReadMapper.listByExample(memberExample);
        if (CollectionUtils.isEmpty(memberList)) {
            return SldResponse.fail(ResponseConst.STATE_FAIL, Language.translate("会员邮箱不存在，请重新注册", Language.EN_LANGUAGE_TYPE));
        }

        Member memberInfo = memberList.get(0);
        if (memberInfo.getIsEmailActive() != null && memberInfo.getIsEmailActive() == 1) {
            return SldResponse.fail(ResponseConst.STATE_FAIL, Language.translate("会员邮箱已激活，无需重复注册，请登录", Language.EN_LANGUAGE_TYPE));
        }

        String activeEmailKey = RedisConst.SLD_PC_NEW_REGISTER_USER_EMAIL + email;
        log.info("activeEmailKey:{}", activeEmailKey);
        if (stringRedisTemplate.hasKey(activeEmailKey)) {
            String verifyNumber = stringRedisTemplate.opsForValue().get(activeEmailKey);
            log.info("verifyNumber:{}", verifyNumber);
            if (!code.equals(verifyNumber)) {
                return SldResponse.fail(ResponseConst.STATE_FAIL, Language.translate("注册链接激活码已失效，请重新注册", Language.EN_LANGUAGE_TYPE));
            }

            // 更新用户邮箱激活状态
            Member memberNew = new Member();
            memberNew.setMemberId(memberInfo.getMemberId());
            memberNew.setIsEmailActive(1);
            memberNew.setUpdateTime(new Date());
            memberNew.setMemberNickName(nickName);
            memberNew.setLoginPwd(Md5.getMd5String(password));
            memberModel.updateMember(memberNew);

            stringRedisTemplate.delete(activeEmailKey);

            // 发送账户注册成功邮件
            memberRegisterActiveModel.sendRegisterSuccessEmail(email, nickName);

            return SldResponse.success(Language.translate("会员邮箱账户激活成功", Language.EN_LANGUAGE_TYPE));
        }
        return SldResponse.fail(ResponseConst.STATE_FAIL, Language.translate("注册链接已失效，请重新注册", Language.EN_LANGUAGE_TYPE));
    }

    /**
     * 发送用户邮箱忘记密码链接
     *
     * @param request
     * @param email
     * @return
     */
    @PostMapping("/forget/pwd")
    public JsonResult<Object> getMemberEmailForgetPwdLink(HttpServletRequest request, String email, String verifyKey, String verifyCode) {
        log.info("getMemberEmailForgetPwdLink - email:{},verifyKey:{},verifyCode:{}", email, verifyKey, verifyCode);
        if (StringUtil.isEmpty(email)) {
            return SldResponse.fail(Language.translate("邮件不能为空", Language.EN_LANGUAGE_TYPE));
        }
        AssertUtil.emailCheck(email);

        //获得redis中的验证码
        String verify_number = stringRedisTemplate.opsForValue().get(verifyKey);
        AssertUtil.isTrue(verify_number == null || !verify_number.equalsIgnoreCase(verifyCode), Language.translate("图形验证码不正确", Language.EN_LANGUAGE_TYPE));

        int count = memberRegisterActiveModel.checkMemberUserInfo(email);
        AssertUtil.isTrue((count == 0), Language.translate("发送重置密码邮件失败，请重试", Language.EN_LANGUAGE_TYPE));
        AssertUtil.isTrue((count == 2), Language.translate("该邮箱未激活，请先激活", Language.EN_LANGUAGE_TYPE));
        AssertUtil.isTrue((count == 3), Language.translate("该邮箱未注册，请先注册", Language.EN_LANGUAGE_TYPE));
        return SldResponse.success(Language.translate("重置密码链接已发送", Language.EN_LANGUAGE_TYPE));
    }

    /**
     * 用户邮箱重置忘记密码
     *
     * @param request
     * @param email
     * @param code
     * @param loginPwd
     * @param verifyKey
     * @param verifyCode
     * @return
     */
    @PostMapping("/email/reset/pwd")
    public JsonResult<Object> emailResetPwd(HttpServletRequest request, String email, String code, String loginPwd, String verifyKey, String verifyCode) {
        log.info("emailResetPwd - email:{},code:{},loginPwd:{},verifyKey:{},verifyCode:{}", email, code, loginPwd, verifyKey, verifyCode);
        if (StringUtil.isEmpty(email) || StringUtil.isEmpty(code)) {
            return SldResponse.fail(ResponseConst.STATE_FAIL, Language.translate("重置密码链接不正确，请重新获取忘记密码链接", Language.EN_LANGUAGE_TYPE));
        }

        //获得redis中的验证码
        String verify_number = stringRedisTemplate.opsForValue().get(verifyKey);
        AssertUtil.isTrue(verify_number == null || !verify_number.equalsIgnoreCase(verifyCode), Language.translate("图形验证码不正确", Language.EN_LANGUAGE_TYPE));

        MemberExample memberExample = new MemberExample();
        memberExample.setMemberEmail(email.toLowerCase());
        List<Member> memberList = memberReadMapper.listByExample(memberExample);

        if (CollectionUtils.isEmpty(memberList)) {
            return SldResponse.fail(ResponseConst.STATE_FAIL, Language.translate("该邮箱不存在，请先注册", Language.EN_LANGUAGE_TYPE));
        }

        Member memberInfo = memberList.get(0);
        if (memberInfo.getIsEmailActive() != null && memberInfo.getIsEmailActive() == 0) {
            return SldResponse.fail(ResponseConst.STATE_FAIL, Language.translate("该邮箱未激活，请先激活", Language.EN_LANGUAGE_TYPE));
        }

        String forgetPwdEmailKey = RedisConst.SLD_PC_FORGET_PWD_USER_EMAIL + email;
        log.info("forgetPwdEmailKey:{}", forgetPwdEmailKey);
        if (stringRedisTemplate.hasKey(forgetPwdEmailKey)) {
            String verifyNumber = stringRedisTemplate.opsForValue().get(forgetPwdEmailKey);
            log.info("verifyNumber:{}", verifyNumber);
            if (!code.equals(verifyNumber)) {
                return SldResponse.fail(ResponseConst.STATE_FAIL, Language.translate("重置密码链接激活码已失效，请重新获取", Language.EN_LANGUAGE_TYPE));
            }

            // 更新用户密码
            Member memberNew = new Member();
            memberNew.setMemberId(memberInfo.getMemberId());
            memberNew.setLoginPwd(Md5.getMd5String(loginPwd));
            memberNew.setUpdateTime(new Date());
            memberModel.updateMember(memberNew);

            stringRedisTemplate.delete(forgetPwdEmailKey);

            return SldResponse.success(Language.translate("重置登录密码成功", Language.EN_LANGUAGE_TYPE));
        }
        return SldResponse.fail(ResponseConst.STATE_FAIL, Language.translate("重置密码链接已失效，请重新获取", Language.EN_LANGUAGE_TYPE));
    }
}
