package com.sv.service.oms;
import com.github.pagehelper.PageHelper;
import com.sv.dto.api.MemberTokenDTO;
import com.sv.entity.MemberAuth;
import com.sv.entity.MemberToken;
import com.sv.exception.api.ExceptionCodeTemplate;
import com.sv.exception.oms.OmsException;
import com.sv.mapper.MemberMapper;
import com.sv.service.api.MemberAuthService;
import com.sv.service.api.MemberTokenService;
import com.sv.service.common.MemberCardCommonService;
import com.sv.service.common.MemberMoney;
import com.ydd.framework.core.common.Pagination;
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 com.sv.entity.Member;

import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Service - 用户
 *
 * @author yechanglin
 * @since 2018-08-03
 */
@Service("members")
@Transactional
public class MemberService extends MemberCardCommonService {

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

	@Resource
	private MemberMapper memberMapper;
	@Resource
	private MemberAuthService memberAuthService;
	@Resource
	private MemberTokenService memberTokenService;

	/**
	 * 创建用户
	 *
	 * @param member 用户
	 */

	@Transactional
    public void save(Member member) {
		if (member.getId() != null && member.getId() > 0) {
			// 更新
			memberMapper.update(member);
		} else {
			// 新建
			memberMapper.insert(member);
		}
	}

	/**
	 * 更新用户
 	 *
	 * @param member 用户
	 */

	@Transactional
    public void update(Member member) {
		memberMapper.update(member);
	}

	/**
	 * 删除用户
	 *
	 * @param id 编号
   	 * @return 删除数量
	 */

	@Transactional
    public Integer delete(Integer id) {
		if (id == null || id <= 0) {
			return 0;
		}
		return memberMapper.delete(id);
	}

	/**
	 * 删除用户
	 *
	 * @param ids 编号数组
	 * @return 删除数量
	 */

	@Transactional
    public Integer deleteByIds(Integer[] ids) {
		if (ids == null || ids.length == 0) {
			return 0;
		}
		return memberMapper.deleteByIds(ids);
	}

	/**
	 * 查询用户
	 *
	 * @param id 编号
	 * @return 用户
	 */
	public Member findById(Integer id) {
		return memberMapper.findById(id);
	}

	/**
	 * 查询用户
	 *
	 * @param pagination 分页信息
	 * @return 分页结果
	 */

	public Pagination findPage(Pagination pagination) {
		PageHelper.startPage(pagination.getPage(), pagination.getPageSize());
		PageHelper.orderBy("id desc");
		pagination.setQueryResult(memberMapper.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 memberMapper.updateStatus(ids, status);
	}

	/**
	 * 保存用户
	 */
	public void saveMember(Member member){
		ValidationUtils.assertNotBlank(member.getMobile(), "请输入手机号码");
		ValidationUtils.assertMobile(member.getMobile());

		synchronized (member.getMobile()){
			// 根据手机号码创建新用户
			Member memberInfo = createByMobile(member);
		}
	}

	/**
	 * 创建新用户
	 *
	 * @return 新用户
	 */
	@Transactional(readOnly = false)
	public Member createByMobile(Member member) {
		// 参数校验
		ValidationUtils.assertNotNull(member.getMobile());
		ValidationUtils.assertMobile(member.getMobile());

		// 创建用户
		String regEx = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\n|\r|\t";
		Pattern pattern = Pattern.compile(regEx);
		member.setMobile(member.getMobile());
		if (member.getName() != null) {
			Matcher matcher = pattern.matcher(member.getName());
			if (matcher.find()){
				throw new OmsException("姓名不能包含特殊字符");
			}
			if (member.getName().length() > 8){
				throw new OmsException("姓名不能超过8位");
			}
			member.setName(member.getName());
		}
		if (member.getSex() != null) {
			member.setSex(member.getSex());
		}
		if (member.getAge() != null) {
			if (member.getAge().intValue() < 10 || member.getAge().intValue() > 100) {
				throw new OmsException("年龄在10-100之间");
			}
			member.setAge(member.getAge());
		}
		if (member.getAddress() != null) {
			Matcher matcher = pattern.matcher(member.getAddress());
			if (matcher.find()){
				throw new OmsException("地址不能包含特殊字符");
			}
			member.setAddress(member.getAddress());
		}
		member.setPlatformId(1);
        if (member.getId() != null && member.getId() > 0) {
            Member memberInfo = memberMapper.findById(member.getId());
            if (!memberInfo.getMobile().equals(member.getMobile())){
                assertMobileNotUsed(member.getMobile(), null);
            }
            memberMapper.update(member);
        }else {
            MemberTokenDTO memberTokenDTO = null;
            assertMobileNotUsed(member.getMobile(), null);
            String inviteCode = "";
            Integer count = 1;
            while (count == 1) {
                inviteCode = RandomStringUtils.randomNumeric(10);
                count = memberMapper.checkInviteCode(inviteCode);
            }
            member.setInviteCode(inviteCode);
			if (member.getNickname() != null){
				Matcher matcher = pattern.matcher(member.getNickname());
				if (matcher.find()){
					throw new OmsException("昵称不能包含特殊字符");
				}
				member.setNickname(member.getNickname());
			}
            memberMapper.insert(member);
            // 查询认证
            MemberAuth memberAuth = memberAuthService.findByMobile(member.getMobile());
            if (memberAuth == null){
                // 创建用户登录认证
                memberAuth = memberAuthService.createByMobile(member.getId(),member.getPlatformId(),member.getMobile());
            }

            // 查询访问凭证，并强制更新
            memberTokenDTO = memberTokenService.findDTOByMemberId(memberAuth.getMemberId(), Boolean.TRUE);
        }
		return member;
	}

	/**
	 * 断言手机号码未使用
	 *
	 * @param mobile    手机号码
	 * @param excludeId 排除编号
	 */
	public void assertMobileNotUsed(String mobile, Integer excludeId) {
		// 验证手机号码是否存在
		if (isMobileExists(mobile, excludeId)) {
			throw new OmsException(ExceptionCodeTemplate.MOBILE_EXISTS);
		}
	}
	/**
	 * 手机号码是否存在
	 *
	 * @param mobile    手机号码
	 * @param excludeId 排除编号
	 * @return 存在返回 {@code true}，反之 {@code false}
	 */
	public Boolean isMobileExists(String mobile, Integer excludeId) {
		return memberMapper.countByMobile(mobile, excludeId) != 0;
	}
}

