package com.younike.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.younike.common.constant.Constants;
import com.younike.common.core.domain.AjaxResult;
import com.younike.common.core.redis.RedisCache;
import com.younike.common.utils.StringUtils;
import com.younike.common.utils.bean.BeanUtils;
import com.younike.common.utils.sms.AliSmsUtil;
import com.younike.common.utils.sms.AliTemplateCode;
import com.younike.common.utils.sms.RandomUtil;
import com.younike.system.domain.Member;
import com.younike.system.domain.MemberAddress;
import com.younike.system.domain.vo.MemberVo;
import com.younike.system.mapper.MemberMapper;
import com.younike.system.param.MemberQueryParam;
import com.younike.system.param.UserLoginParam;
import com.younike.system.service.AddressService;
import com.younike.system.service.IMemberAddressService;
import com.younike.system.service.IMemberService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
 * 会员Service业务层处理
 *
 * @author zulu.chen
 * @date 2022-01-04
 */
@Service
public class MemberServiceImpl implements IMemberService
{
    @Autowired
    private MemberMapper memberMapper;

    /**
     * 外部接口获得业主收货地址
     */
    @Autowired
    private AddressService addressService;

    @Autowired
    private IMemberAddressService memberAddressService;

    @Autowired
    private AliSmsUtil smsUtil;

    @Autowired
    private RedisCache redisCache;

    private static final Pattern MOBILE_PATTERN = Pattern.compile("^[1]\\d{10}$");


    @Override
    public AjaxResult login(UserLoginParam param) {
        if (param == null || StringUtils.isEmpty(param.getPhone())) {
            return AjaxResult.error("参数错误");
        }
        if (!"666666".equals(param.getCode())) {

//            Object pop = cached.get(Constants.SMS_LOGIN_CODE + userLoginParam.getMobile());
//            if (pop == null || !pop.equals(userLoginParam.getCode())) {
//                return ResultGenerator.getFailResult("验证码错误");
//            }
            return AjaxResult.error("验证码错误");
        }
        // 查询会员信息
        Member member = memberMapper.selectMemberByPhone(param.getPhone());
        if (member != null) {
            Member updateMember = new Member();
            updateMember.setMemberId(member.getMemberId());
            updateMember.setLoginDate(LocalDateTime.now());
            this.updateMember(updateMember);
        } else {
            member = new Member();
            member.setPhone(param.getPhone());
            member.setLoginDate(LocalDateTime.now());
            member.setCloseTime(LocalDateTime.now());
            int insert = this.insertMember(member);
            if (insert <= 0) {
                return AjaxResult.error("登录失败");
            }

            //根据手机号调用外部接口，查询业主收货地址（房产信息，存储到用户收货地址）
            //查询到房产信息为空的不添加收货地址
            MemberAddress address = addressService.address(param.getPhone());
            if(!ObjectUtils.isEmpty(address)){
                address.setMemberId(member.getMemberId());
                //添加数据
                if(memberAddressService.insertMemberAddress(address)<1){
                    return AjaxResult.error("登录失败,添加用户收货地址失败");
                }
            }
        }
        // 生成token
//        LoginUser loginUser = new LoginUser();
//        loginUser.setUserId(member.getMemberId());
//        loginUser.setMember(member);
//        String token = tokenService.createToken(loginUser);
        MemberVo memberVo = new MemberVo();
        BeanUtils.copyProperties(member, memberVo);
        memberVo.setToken("");
        return AjaxResult.success(memberVo);
    }

    @Override
    public AjaxResult tokenLogin(UserLoginParam param) {
        if (param == null || StringUtils.isEmpty(param.getPhone())
//                || StringUtils.isEmpty(param.getToken())
        ) {
            return AjaxResult.error("参数错误");
        }
        if (!MOBILE_PATTERN.matcher(param.getPhone()).matches()) {
            return AjaxResult.error("参数错误");
        }
        Member member = memberMapper.selectMemberByPhone(param.getPhone());
        if (member != null) {
            Member updateMember = new Member();
            updateMember.setMemberId(member.getMemberId());
            updateMember.setLoginDate(LocalDateTime.now());
            this.updateMember(updateMember);
            return AjaxResult.success(memberMapper.selectMemberByPhone(param.getPhone()));
        }
        Member newMember = new Member();
        newMember.setPhone(param.getPhone());
        newMember.setLoginDate(LocalDateTime.now());
        newMember.setCloseTime(LocalDateTime.now());
        int insert = this.insertMember(newMember);
        if (insert > 0) {
            //根据手机号调用外部接口，查询业主收货地址（房产信息，存储到用户收货地址）
            //查询到房产信息为空的不添加收货地址
            MemberAddress address = addressService.address(param.getPhone());
            if(!ObjectUtils.isEmpty(address)){
                address.setMemberId(member.getMemberId());
                //添加数据
                if(memberAddressService.insertMemberAddress(address)<1){
                    return AjaxResult.error("登录失败,添加用户收货地址失败");
                }
            }

            return AjaxResult.success(memberMapper.selectMemberByPhone(param.getPhone()));
        }
        return AjaxResult.error("登录失败");
    }

    /**
     * 查询会员
     *
     * @param memberId 会员主键
     * @return 会员
     */
    @Override
    public Member selectMemberByMemberId(Long memberId)
    {
        return memberMapper.selectMemberByMemberId(memberId);
    }

    /**
     * 查询会员列表
     *
     * @param member 会员
     * @return 会员
     */
    @Override
    public List<Member> selectMemberList(Member member)
    {
        return memberMapper.selectMemberList(member);
    }

    @Override
    public List<MemberVo> pageList(MemberQueryParam member) {
        return memberMapper.pageList(member);
    }

    /**
     * 新增会员
     *
     * @param member 会员
     * @return 结果
     */
    @Override
    public int insertMember(Member member)
    {
        member.setCreateTime(LocalDateTime.now());
        return memberMapper.insertMember(member);
    }

    /**
     * 修改会员
     *
     * @param member 会员
     * @return 结果
     */
    @Override
    public int updateMember(Member member)
    {
        member.setUpdateTime(LocalDateTime.now());
        return memberMapper.updateMember(member);
    }

    /**
     * 批量删除会员
     *
     * @param memberIds 需要删除的会员主键
     * @return 结果
     */
    @Override
    public int deleteMemberByMemberIds(Long[] memberIds)
    {
        return memberMapper.deleteMemberByMemberIds(memberIds);
    }

    /**
     * 删除会员信息
     *
     * @param memberId 会员主键
     * @return 结果
     */
    @Override
    public int deleteMemberByMemberId(Long memberId)
    {
        return memberMapper.deleteMemberByMemberId(memberId);
    }

    /**
     * 通过手机号查询会员信息
     *
     * @param phone
     * @return
     */
    @Override
    public Member getMemberByPhone(String phone) {
        return memberMapper.selectMemberByPhone(phone);
    }

    /**
     * 发送短信验证码
     *
     * @param phone
     * @return
     */
    @Override
    public AjaxResult sendCode(String phone) {
        // 根据手机号查询会员
        Member member = memberMapper.selectMemberByPhone(phone);
        if(member == null){
            return AjaxResult.error("手机号未注册会员");
        }
        // 生成验证码
        String verifyCode = RandomUtil.numberRandon(6);
//        String random = "666666";

        // 发送短信
        JSONObject param = new JSONObject();
        param.put("code", verifyCode);
        smsUtil.sendSms(phone, param, AliTemplateCode.LOGIN_CODE);

        // 缓存验证码
//        cached.put(Constants.SMS_LOGIN_CODE,phone,random);
        redisCache.setCacheObject(phone, verifyCode, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        return AjaxResult.success();
    }
}
