package com.ssm.manage.service.impl;

import com.github.pagehelper.PageInfo;
import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.AESUtils;
import com.ssm.core.utils.SmsType;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.manage.dao.SsmMemberDao;
import com.ssm.manage.entity.MemberList;
import com.ssm.manage.entity.SmsException;
import com.ssm.manage.query.MemberRequest;
import com.ssm.manage.query.StoreRequest;
import com.ssm.manage.response.MemberResponse;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.response.UserResponse;
import com.ssm.manage.service.SsmMemberService;
import com.ssm.manage.service.SsmStoreMemberService;
import com.ssm.manage.utils.Constant;
import com.ssm.util.RedisClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.Random;

@Service
@Slf4j
public class SsmMemberServiceImpl extends BaseServiceImpl<MemberList> implements SsmMemberService {
    @Autowired
    private RedisClient<MemberResponse> redisClient;
    @Autowired
    private SsmStoreMemberService ssmStoreMemberService;
    @Autowired
    private SsmMemberDao dao;

    @Override
    public SsmMemberDao getDao() {
        return dao;
    }


    @Override
    public PageInfo<MemberList> selectPage(MemberRequest memberRequest) {
        return dao.selectPage(memberRequest);
    }

//    @Override
//    public MemberResponse selectOne(MemberRequest memberRequest) {
//        MemberResponse memberResponse = new MemberResponse();
//        String key = "";
//        if (StringUtils.isNotBlank(memberRequest.getMobilePhone())) {
//            key = getKey(memberRequest.getMobilePhone());
//        }
//        if (redisClient.hasKey(key)){
//            memberResponse = redisClient.get(key);
//        }else {
//            //平台会员暂不考虑会员停用启用状态
////            memberList.setState(1);
//            MemberList memberList = new MemberList();
//            if (StringUtils.isNotBlank(memberRequest.getMobilePhone())) {
//                memberList.setMobilePhone(memberRequest.getMobilePhone());
//            }
//            if (StringUtils.isNotBlank(memberRequest.getCard())) {
//                memberList.setCard(memberRequest.getCard());
//            }
//            memberList = dao.selectOne(memberList);
//            BeanUtils.copyProperties(memberResponse,memberList);
//            key = getKey(memberList.getMobilePhone());
//            redisClient.set(key,memberResponse,RedisClient.EXPIRE_TIME_ONE_DAY);
//        }
//        return memberResponse;
//    }

    @Override
    public MemberList selectOne(MemberRequest memberRequest) {

        //平台会员暂不考虑会员停用启用状态
//            memberList.setState(1);
        MemberList memberList = new MemberList();
        if (StringUtils.isNotBlank(memberRequest.getMobilePhone())) {
            memberList.setMobilePhone(memberRequest.getMobilePhone());
        }
        if (StringUtils.isNotBlank(memberRequest.getCard())) {
            memberList.setCard(memberRequest.getCard());
        }
        memberList = dao.selectOne(memberList);

        return memberList;
    }


    @Override
    public MemberResponse addMember(MemberList memberList) throws SmsException {
        memberList.setState(1);
        memberList.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        String cashPassword = "";
        try{
            cashPassword = AESUtils.encrypt(memberList.getCashPassword());
        }catch (Exception e){
            throw new SmsException(ResponseCode.ENCRYPT_ERROR);
        }
        memberList.setCashPassword(cashPassword);
        //生成动态密码 发送到当前会员的手机上
        String code = ObjectUtils.toString((int)((Math.random()*9+1)*1000));
        String msg = code+"(登录验证码，请完成验证)，如非本人操作，请忽略本短信。";
        UserResponse userResponse = SmsType.sendSmsCode(Constant.smsUrl, Constant.smsAccount,
                Constant.smsPassword, memberList.getMobilePhone(), msg);
        if (userResponse.getSendSmsStatus()) {
            try {
                code = AESUtils.encrypt(code);
            } catch (Exception e) {
                throw new SmsException(ResponseCode.ENCRYPT_ERROR);
            }
        }
        memberList.setPassword(code);
        int i = dao.saveNotNull(memberList);
        MemberResponse memberResponse = new MemberResponse();
        if (i > 0){
            BeanUtils.copyProperties(memberResponse,memberList);
        }
        return memberResponse;
    }

    @Transactional(rollbackFor=Exception.class)
    @Override
    public int updateMember(MemberRequest memberRequest) throws SmsException {
        MemberList memberList = new MemberList();
        BeanUtils.copyProperties(memberRequest,memberList);
        int i = 0;
        try {
            //平台会员基本信息修改
            i = dao.updateByPrimaryKeySelective(memberList);
        }catch (Exception e){
            log.error("SsmMemberServiceImpl.updateMember",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.FAILED);
        }

        //平台会员和门店会员割裂开 不在关联
//        if (i > 0){
//            StoreMemberList storeMemberList = ssmStoreMemberService.selectByPrimaryKey(memberRequest.getId());
//            if (storeMemberList != null) {
//                try {
//                    //门店会员基本信息修改
//                    i = ssmStoreMemberService.updateStoreMember(memberList);
//                } catch (Exception e) {
//                    log.error("SsmMemberServiceImpl.updateMember", e);
//                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                    throw new SmsException(ResponseCode.FAILED);
//                }
//            }
//        }
        return i;
    }


    //    @Override
//    public int updateState(MemberRequest memberRequest) {
//        MemberList memberList = new MemberList();
//        return 0;
//    }


    public String getKey(String phone){
        String key = "";
        if (StringUtils.isNotBlank(phone)){
            key = Constant.memberKey + phone;
        }
        return key;
    }

}
