package com.jsowell.pile.service.impl;

import java.math.BigDecimal;
import java.util.List;
import java.util.Locale;

import com.jsowell.common.enums.ykc.ReturnCodeEnum;
import com.jsowell.common.exception.BusinessException;
import com.jsowell.common.util.DateUtils;
import com.jsowell.common.util.StringUtils;
import com.jsowell.pile.domain.MemberBasicInfo;
import com.jsowell.pile.dto.MemberRegisterAndLoginDTO;
import com.jsowell.pile.dto.PileAuthCardDTO;
import com.jsowell.pile.service.IMemberBasicInfoService;
import com.jsowell.pile.vo.uniapp.AuthCardVO;
import com.jsowell.pile.vo.web.PileAuthCardVO;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jsowell.pile.mapper.PileAuthCardMapper;
import com.jsowell.pile.domain.PileAuthCard;
import com.jsowell.pile.service.IPileAuthCardService;

/**
 * 充电站鉴权卡Service业务层处理
 *
 * @author jsowell
 * @date 2023-03-16
 */
@Service
public class PileAuthCardServiceImpl implements IPileAuthCardService {
    @Autowired
    private PileAuthCardMapper pileAuthCardMapper;

    @Autowired
    private IMemberBasicInfoService memberBasicInfoService;

    /**
     * 查询充电站鉴权卡
     *
     * @param id 充电站鉴权卡主键
     * @return 充电站鉴权卡
     */
    // @Override
    // public PileAuthCard selectPileAuthCardById(Long id) {
    //     return pileAuthCardMapper.selectPileAuthCardById(id);
    // }

    @Override
    public PileAuthCardVO getCardInfoById(Long id) {
        return pileAuthCardMapper.getCardInfoById(id);
    }

    /**
     * 查询充电站鉴权卡信息
     * @param pileAuthCard
     * @return
     */
    @Override
    public PileAuthCard selectPileAuthCardInfo(PileAuthCard pileAuthCard) {
        return pileAuthCardMapper.selectPileAuthCardInfo(pileAuthCard);
    }

    /**
     * 查询充电站鉴权卡列表
     *
     * @param pileAuthCard 充电站鉴权卡
     * @return 充电站鉴权卡
     */
    @Override
    public List<PileAuthCard> selectPileAuthCardList(PileAuthCard pileAuthCard) {
        return pileAuthCardMapper.selectPileAuthCardList(pileAuthCard);
    }

    /**
     * 查询充电站鉴权卡列表
     *
     * @param dto 充电站鉴权卡
     * @return 充电站鉴权卡集合
     */
    @Override
    public List<PileAuthCardVO> getPileAuthCardInfoList(PileAuthCardDTO dto) {
        return pileAuthCardMapper.getPileAuthCardInfoList(dto);
    }

    /**
     * 新增充电站鉴权卡
     *
     * @param pileAuthCard 充电站鉴权卡
     * @return 结果
     */
    @Override
    public int insertPileAuthCard(PileAuthCard pileAuthCard) {
        return pileAuthCardMapper.insertPileAuthCard(pileAuthCard);
    }

    /**
     * 新增充电站鉴权卡(后管用)
     *
     * @param dto 充电站鉴权卡
     * @return 结果
     */
    @Override
    public int addAuthCard(PileAuthCardDTO dto) {
        MemberBasicInfo memberBasicInfo = new MemberBasicInfo();
        if (dto.getPhoneNumber() == null) {
            memberBasicInfo.setMemberId(null);
            memberBasicInfo.setStatus("0"); // 0-待激活
        }else {
            // 通过手机号查询memberId
            memberBasicInfo = memberBasicInfoService.selectInfoByMobileNumber(dto.getPhoneNumber());
            if (memberBasicInfo == null) {
                // 为空则说明未查到该用户的注册信息
                throw new BusinessException(ReturnCodeEnum.CODE_USER_IS_NOT_REGISTER);
            }
            memberBasicInfo.setStatus("1"); // 1-正常使用
        }
        String secretKey = RandomStringUtils.randomAlphanumeric(8).toUpperCase(Locale.ROOT); // 生成8位数的字母 + 数字随机数
        PileAuthCard pileAuthCard = PileAuthCard.builder()
                .logicCard(dto.getLogicCard())
                .memberId(memberBasicInfo.getMemberId())
                .status(memberBasicInfo.getStatus())
                .secretKey(secretKey)
                .build();
        return pileAuthCardMapper.insertPileAuthCard(pileAuthCard);
    }

    /**
     * 修改充电站鉴权卡
     *
     * @param pileAuthCard 充电站鉴权卡
     * @return 结果
     */
    @Override
    public int updatePileAuthCard(PileAuthCard pileAuthCard) {
        return pileAuthCardMapper.updatePileAuthCard(pileAuthCard);
    }

    @Override
    public int updateCardInfo(PileAuthCardDTO dto) {
        // 通过手机号查询memberId
        MemberBasicInfo memberBasicInfo = memberBasicInfoService.selectInfoByMobileNumber(dto.getPhoneNumber());
        if (memberBasicInfo == null) {
            // 为空则说明未查到该用户的注册信息
            throw new BusinessException(ReturnCodeEnum.CODE_USER_IS_NOT_REGISTER);
        }
        PileAuthCard pileAuthCard = PileAuthCard.builder()
                .id(dto.getId())
                .logicCard(dto.getLogicCard())
                .memberId(memberBasicInfo.getMemberId())
                .status("1")
                .build();
        return pileAuthCardMapper.updatePileAuthCard(pileAuthCard);
    }

    /**
     * 批量删除充电站鉴权卡
     *
     * @param ids 需要删除的充电站鉴权卡主键
     * @return 结果
     */
    @Override
    public int deletePileAuthCardByIds(Long[] ids) {
        return pileAuthCardMapper.deletePileAuthCardByIds(ids);
    }

    /**
     * 删除充电站鉴权卡信息
     *
     * @param id 充电站鉴权卡主键
     * @return 结果
     */
    @Override
    public int deletePileAuthCardById(Long id) {
        return pileAuthCardMapper.deletePileAuthCardById(id);
    }

    @Override
    public int deactivateCard(Long id) {
        return pileAuthCardMapper.deactivateCard(id);
    }

    @Override
    public int unBindingCard(PileAuthCard pileAuthCard) {
        return pileAuthCardMapper.unBindingCard(pileAuthCard);
    }

    /**
     * 根据逻辑卡号查询某状态的鉴权卡信息
     * @param status
     * @param logicCard
     * @return
     */
    @Override
    public PileAuthCard selectSomeStatusCardInfo(String status, String logicCard) {
        return pileAuthCardMapper.selectSomeStatusCardInfo(status, logicCard);
    }

    /**
     * 通过逻辑卡号查询卡信息
     * @param logicCard
     * @return
     */
    @Override
    public PileAuthCard selectCardInfoByLogicCard(String logicCard) {
        return selectSomeStatusCardInfo(null, logicCard);
    }

    /**
     * 通过memberId查询鉴权卡列表 （小程序用）
     * @param memberId
     * @return
     */
    @Override
    public List<AuthCardVO> getAuthCardListByMemberId(String memberId) {
        List<AuthCardVO> list = pileAuthCardMapper.getAuthCardListByMemberId(memberId);
        for (AuthCardVO authCardVO : list) {
            authCardVO.setAccountBalance(authCardVO.getPrincipalBalance().add(authCardVO.getGiftBalance()).setScale(2, BigDecimal.ROUND_HALF_UP));
        }
        return list;
    }

    /**
     * 用户绑定鉴权卡
     * @param dto
     */
    @Override
    public int bindAuthCard(PileAuthCardDTO dto) {
        String phoneNumber = dto.getPhoneNumber();
        // 判断此用户是否已注册小程序账号
        MemberBasicInfo memberBasicInfo = memberBasicInfoService.selectInfoByMobileNumber(phoneNumber);
        if (memberBasicInfo == null) {
            throw new BusinessException(ReturnCodeEnum.CODE_USER_IS_NOT_REGISTER);
        }
        // 判断此卡是否已被绑定
        PileAuthCard pileAuthCard = selectCardInfoByLogicCard(dto.getLogicCard());
        if (!StringUtils.equals(pileAuthCard.getStatus(), "0")) { // 0-待激活
            throw new BusinessException(ReturnCodeEnum.CODE_THIS_CARD_STATUS_ANOMALY);
        }
        // 验证密钥
        if (!StringUtils.equals(dto.getSecretKey(), pileAuthCard.getSecretKey())) {
            throw new BusinessException(ReturnCodeEnum.CODE_SECRET_KEY_NOT_SAME);
        }
        // 绑定操作
        pileAuthCard.setMemberId(dto.getMemberId());
        pileAuthCard.setStatus("1");
        return updatePileAuthCard(pileAuthCard);
    }

    /**
     * 用户解绑鉴权卡
     * @param dto
     * @return
     */
    @Override
    public int unbindAuthCard(PileAuthCardDTO dto) {
        // 根据传过来的卡号查询数据库
        PileAuthCard pileAuthCard = selectCardInfoByLogicCard(dto.getLogicCard());
        if (pileAuthCard == null) {
            throw new BusinessException(ReturnCodeEnum.CODE_THIS_CARD_HAS_NO_INFO);
        }
        // 如果memberId对应的上，则进行解绑操作 (将数据库中 del_flag 改为 1)
        if (!StringUtils.equals(pileAuthCard.getMemberId(), dto.getMemberId())) {
            throw new BusinessException(ReturnCodeEnum.CODE_THIS_CARD_BIND_INFO_ERROR);
        }
        pileAuthCard.setDelFlag("1");
        return updatePileAuthCard(pileAuthCard);
    }
}
