package com.jsowell.pile.service.impl;

import com.jsowell.common.constant.Constants;
import com.jsowell.common.enums.ykc.ReturnCodeEnum;
import com.jsowell.common.exception.BusinessException;
import com.jsowell.common.util.PageUtils;
import com.jsowell.common.util.StringUtils;
import com.jsowell.pile.domain.MemberBasicInfo;
import com.jsowell.pile.domain.PileAuthCard;
import com.jsowell.pile.dto.PileAuthCardDTO;
import com.jsowell.pile.mapper.PileAuthCardMapper;
import com.jsowell.pile.service.MemberBasicInfoService;
import com.jsowell.pile.service.PileMerchantInfoService;
import com.jsowell.pile.service.PileAuthCardService;
import com.jsowell.pile.util.UserUtils;
import com.jsowell.pile.vo.base.MerchantInfoVO;
import com.jsowell.pile.vo.uniapp.customer.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 java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

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

    @Autowired
    private MemberBasicInfoService memberBasicInfoService;

    @Autowired
    private PileMerchantInfoService pileMerchantInfoService;

    /**
     * 查询充电站鉴权卡
     *
     * @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) {
        // LoginUserDetailVO loginUserDetail = UserUtils.getLoginUserDetail();
        List<MerchantInfoVO> merchantInfoVOList = UserUtils.getMerchantInfoVOList();
        List<String> merchantIdList = merchantInfoVOList.stream().map(MerchantInfoVO::getMerchantId).collect(Collectors.toList());
        dto.setMerchantIdList(merchantIdList);
        PageUtils.startPage();
        List<PileAuthCardVO> pileAuthCardInfoList = pileAuthCardMapper.getPileAuthCardInfoList(dto);
        return pileAuthCardInfoList;
    }

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

    /**
     * 新增充电站鉴权卡(后管用)
     *
     * @param dto 充电站鉴权卡
     * @return 结果
     */
    @Override
    public int addAuthCard(PileAuthCardDTO dto) {
        String logicCard = dto.getLogicCard();
        // 根据卡号查询数据库
        PileAuthCard cardInfo = pileAuthCardMapper.selectSomeStatusCardInfo(null, logicCard);
        if (cardInfo != null) {
            // 不为空说明此卡已存在
            throw new BusinessException(ReturnCodeEnum.CODE_AUTH_CARD_CODE_EXIST);
        }

        // 鉴权卡状态 默认 0-待激活
        String status = Constants.ZERO;
        String memberId = null;

        if (StringUtils.isNotBlank(dto.getPhoneNumber())) {
            // 通过运营商id获取一级运营商id
            String firstLevelMerchantId = pileMerchantInfoService.getFirstLevelMerchantIdByMerchantId(dto.getMerchantId());

            // 通过手机号查询memberId
            MemberBasicInfo memberBasicInfo = memberBasicInfoService.selectInfoByMobileNumber(dto.getPhoneNumber(), firstLevelMerchantId);
            if (memberBasicInfo == null) {
                // 为空则说明未查到该用户的注册信息
                throw new BusinessException(ReturnCodeEnum.CODE_USER_IS_NOT_REGISTER);
            }
            memberId = memberBasicInfo.getMemberId();
            status = Constants.ONE; // 1-正常使用
        }

        String secretKey = RandomStringUtils.randomAlphanumeric(8).toUpperCase(Locale.ROOT); // 生成8位数的字母 + 数字随机数
        PileAuthCard pileAuthCard = PileAuthCard.builder()
                .logicCard(logicCard)
                .memberId(memberId)
                .merchantId(dto.getMerchantId())
                .status(status)
                .secretKey(secretKey)
                .build();
        return pileAuthCardMapper.insertSelective(pileAuthCard);
    }

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

    @Override
    public int updateCardInfo(PileAuthCardDTO dto) {
        // 通过运营商id获取一级运营商id
        String firstLevelMerchantId = pileMerchantInfoService.getFirstLevelMerchantIdByMerchantId(dto.getMerchantId());
        // 通过手机号查询memberId
        MemberBasicInfo memberBasicInfo = memberBasicInfoService.selectInfoByMobileNumber(dto.getPhoneNumber(), firstLevelMerchantId);
        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.updateByPrimaryKeySelective(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);
        return list;
    }

    /**
     * 用户绑定鉴权卡
     *
     * @param dto
     */
    @Override
    public int bindAuthCard(PileAuthCardDTO dto) {
        // 判断当前鉴权卡是否被绑定过
        PileAuthCard pileAuthCardInfo = selectCardInfoByLogicCard(dto.getLogicCard());
        if (pileAuthCardInfo == null){
            // 为空说明没查到此卡信息
            throw new BusinessException(ReturnCodeEnum.CODE_THIS_CARD_HAS_NO_INFO);
        }
        if (StringUtils.isNotBlank(pileAuthCardInfo.getMemberId())) {
            // memberId 不为空，说明此卡已被绑定
            throw new BusinessException(ReturnCodeEnum.CODE_THIS_CARD_HAS_BEEN_BINDING);
        }
        if (!StringUtils.equalsIgnoreCase(pileAuthCardInfo.getSecretKey(), dto.getSecretKey())) {
            // 密钥不一致，不能绑定
            throw new BusinessException(ReturnCodeEnum.CODE_SECRET_KEY_NOT_SAME);
        }
        if (!StringUtils.equals(pileAuthCardInfo.getStatus(), Constants.ZERO)) {
            // 鉴权卡不是待激活状态  0-待激活
            throw new BusinessException(ReturnCodeEnum.CODE_THIS_CARD_STATUS_ANOMALY);
        }
        PileAuthCard authCard = PileAuthCard.builder()
                .id(pileAuthCardInfo.getId())
                .memberId(dto.getMemberId())
                .status(Constants.ONE) // 1-正常使用
                .updateBy(dto.getMemberId())
                .build();
        return updatePileAuthCard(authCard);
    }

    /**
     * 用户解绑鉴权卡
     *
     * @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");
        pileAuthCard.setStatus("0");
        pileAuthCard.setMemberId("");
        String secretKey = RandomStringUtils.randomAlphanumeric(8).toUpperCase(Locale.ROOT); // 生成8位数的字母 + 数字随机数
        pileAuthCard.setSecretKey(secretKey);
        return updatePileAuthCard(pileAuthCard);
    }

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return pileAuthCardMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(PileAuthCard record) {
        return pileAuthCardMapper.insert(record);
    }

    @Override
    public int insertOrUpdate(PileAuthCard record) {
        return pileAuthCardMapper.insertOrUpdate(record);
    }

    @Override
    public int insertOrUpdateSelective(PileAuthCard record) {
        return pileAuthCardMapper.insertOrUpdateSelective(record);
    }

    @Override
    public int insertSelective(PileAuthCard record) {
        return pileAuthCardMapper.insertSelective(record);
    }

    @Override
    public PileAuthCard selectByPrimaryKey(Integer id) {
        return pileAuthCardMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(PileAuthCard record) {
        return pileAuthCardMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(PileAuthCard record) {
        return pileAuthCardMapper.updateByPrimaryKey(record);
    }

    @Override
    public int updateBatch(List<PileAuthCard> list) {
        return pileAuthCardMapper.updateBatch(list);
    }

    @Override
    public int batchInsert(List<PileAuthCard> list) {
        return pileAuthCardMapper.batchInsert(list);
    }
}

