package com.ruoyi.common.auth.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.auth.entity.OauthClientDetails;
import com.ruoyi.common.auth.mapper.OauthClientDetailsMapper;
import com.ruoyi.common.auth.service.OauthClientDetailsService;
import com.ruoyi.common.core.domain.StringConstant;
import com.ruoyi.common.core.exception.ServiceException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dromara.common.encrypt.utils.Desensitization;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Yuuki
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class OauthClientDetailsServiceImpl extends ServiceImpl<OauthClientDetailsMapper, OauthClientDetails> implements OauthClientDetailsService {

    private final PasswordEncoder passwordEncoder;
    private final RedisClientDetailsService redisClientDetailsService;

    @Override
    public List<OauthClientDetails> findOauthClientDetails(OauthClientDetails oauthClientDetails) {
        LambdaQueryWrapper<OauthClientDetails> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(oauthClientDetails.getClientId())) {
            queryWrapper.eq(OauthClientDetails::getClientId, oauthClientDetails.getClientId());
        }
        List<OauthClientDetails> result = this.baseMapper.selectList(queryWrapper);


        List<OauthClientDetails> records = new ArrayList<>();
        result.forEach(o -> {
            o.setOriginSecret(null);
            o.setClientSecret(null);
            records.add(o);
        });
        //遍历result对电话和身份证进行脱敏
        for (OauthClientDetails o : result) {
            if(o.getAdditionalInformation() != null && o.getAdditionalInformation().length() > 0) {
                //截取原始身份证号码和电话
                String idCard = o.getAdditionalInformation().substring(o.getAdditionalInformation().indexOf("身份证号:") + 5, o.getAdditionalInformation().indexOf("身份证号") + 5 + 18);
                String phone = o.getAdditionalInformation().substring(o.getAdditionalInformation().indexOf("电话：:") + 3, o.getAdditionalInformation().indexOf("电话") + 3 + 11);
                String s = o.getAdditionalInformation().replace(idCard, Desensitization.idCardDesensitization(idCard)).replace(phone, Desensitization.mobilePhoneDesensitization(phone));
                o.setAdditionalInformation(s);
            }
        }


        return result;
    }

    @Override
    public OauthClientDetails findById(String clientId) {
        OauthClientDetails clientDetails = this.baseMapper.selectById(clientId);
        if (clientDetails == null) {
            return clientDetails;
        }
        //遍历result对电话和身份证进行脱敏
        if (clientDetails.getAdditionalInformation() != null && clientDetails.getAdditionalInformation().length() > 0) {
            String information = clientDetails.getAdditionalInformation();
            //截取原始身份证号码和电话
            String idCard = information.substring(information.indexOf("身份证号:") + 5, information.indexOf("身份证号") + 5 + 18);
            String phone = information.substring(information.indexOf("电话：:") + 3, information.indexOf("电话") + 3 + 11);
            String s = information.replace(idCard, Desensitization.idCardDesensitization(idCard)).replace(phone, Desensitization.mobilePhoneDesensitization(phone));
            clientDetails.setAdditionalInformation(s);
        }
        if (clientDetails != null) {
            //id不为空才能进行修改
            clientDetails.setId("defaultId");
        }
        return clientDetails;
    }
    @Override
    public OauthClientDetails findByIdToCheck(String clientId) {
        return this.baseMapper.selectById(clientId);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createOauthClientDetails(OauthClientDetails oauthClientDetails) throws ServiceException {
        OauthClientDetails byId = this.findByIdToCheck(oauthClientDetails.getClientId());
        if (byId != null) {
            throw new ServiceException("该Client已存在");
        }
        oauthClientDetails.setOriginSecret(oauthClientDetails.getClientSecret());
        oauthClientDetails.setClientSecret(passwordEncoder.encode(oauthClientDetails.getClientSecret()));


        boolean saved = this.save(oauthClientDetails);
        if (saved) {
            log.info("缓存Client -> {}", ObjectUtil.cloneIfPossible(oauthClientDetails));
            this.redisClientDetailsService.loadClientByClientId(oauthClientDetails.getClientId());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOauthClientDetails(OauthClientDetails oauthClientDetails) {
        String clientId = oauthClientDetails.getClientId();

        LambdaQueryWrapper<OauthClientDetails> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OauthClientDetails::getClientId, oauthClientDetails.getClientId());


        oauthClientDetails.setClientId(null);
        oauthClientDetails.setClientSecret(null);


        boolean updated = this.update(oauthClientDetails, queryWrapper);
        if (updated) {
            log.info("更新Client -> {}", ObjectUtil.cloneIfPossible(oauthClientDetails));
            this.redisClientDetailsService.removeRedisCache(clientId);
            this.redisClientDetailsService.loadClientByClientId(clientId);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteOauthClientDetails(String clientIds) {
        Object[] clientIdArray = StringUtils.splitByWholeSeparatorPreserveAllTokens(clientIds, StringConstant.COMMA);
        LambdaQueryWrapper<OauthClientDetails> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(OauthClientDetails::getClientId, clientIdArray);
        boolean removed = this.remove(queryWrapper);
        if (removed) {
            log.info("删除ClientId为({})的Client", ObjectUtil.cloneIfPossible(clientIds));
            Arrays.stream(clientIdArray).forEach(c -> this.redisClientDetailsService.removeRedisCache(String.valueOf(c)));

        }
    }

    @Override
    public OauthClientDetails findByIdToAuth(String clientId) {
        OauthClientDetails clientDetails = this.baseMapper.selectByIdToAuto(clientId);
        if (clientDetails == null) {
            return clientDetails;
        }
        //遍历result对电话和身份证进行脱敏
        if (clientDetails.getAdditionalInformation() != null && clientDetails.getAdditionalInformation().length() > 0) {
            String information = clientDetails.getAdditionalInformation();
            //截取原始身份证号码和电话
            String idCard = information.substring(information.indexOf("身份证号:") + 5, information.indexOf("身份证号") + 5 + 18);
            String phone = information.substring(information.indexOf("电话：:") + 3, information.indexOf("电话") + 3 + 11);
            String s = information.replace(idCard, Desensitization.idCardDesensitization(idCard)).replace(phone, Desensitization.mobilePhoneDesensitization(phone));
            clientDetails.setAdditionalInformation(s);
        }
        if (clientDetails != null) {
            //id不为空才能进行修改
            clientDetails.setId("defaultId");
        }
        return clientDetails;
    }
}
