package com.crm.ucard.service.impl;

import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.dto.base.BaseResultDto;
import com.crm.rely.backend.core.dto.base.PageDto;
import com.crm.rely.backend.core.dto.base.ResultWithPagerDto;
import com.crm.rely.backend.core.dto.ucard.CardIdTypeConfigDto;
import com.crm.rely.backend.core.entity.base.BaseDeleteEntities;
import com.crm.rely.backend.core.entity.ucard.CardIdTypeConfigAddEntity;
import com.crm.rely.backend.core.entity.ucard.CardIdTypeConfigPageEntity;
import com.crm.rely.backend.core.entity.ucard.CardIdTypeConfigUpdateEntity;
import com.crm.rely.backend.core.entity.ucard.CardTypeConfigUpdateEntity;
import com.crm.rely.backend.core.pojo.table.ucard.CardIdTypeConfigTable;
import com.crm.rely.backend.core.pojo.table.ucard.CardTypeConfigTable;
import com.crm.rely.backend.core.pojo.table.ucard.CardTypeTable;
import com.crm.rely.backend.exception.ServiceException;
import com.crm.ucard.dao.mapper.CardIdTypeConfigMapper;
import com.crm.ucard.dao.repository.CardIdTypeConfigRepository;
import com.crm.ucard.dao.repository.CardTypeConfigRepository;
import com.crm.ucard.dao.repository.CardTypeRepository;
import com.crm.ucard.service.UcardTypeConfigService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Slf4j
@Service
public class UcardTypeConfigServiceImpl implements UcardTypeConfigService {


    @Autowired
    private CardTypeRepository cardTypeRepository;
    @Autowired
    private CardTypeConfigRepository cardTypeConfigRepository;
    @Autowired
    private CardIdTypeConfigMapper cardIdTypeConfigMapper;
    @Autowired
    private CardIdTypeConfigRepository cardIdTypeConfigRepository;


    /**
     * 修改卡类型配置
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResultDto updateCardTypeConfig(CardTypeConfigUpdateEntity entity) throws ServiceException {
        CardTypeTable typeTable = cardTypeRepository.findByCardTypeId(entity.getCardTypeId());
        if (typeTable == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        if (entity.getCardFee() != null) {
            if (entity.getCardFee().compareTo(BigDecimal.ZERO) < 0) {
                throw ServiceException.exception("卡片费用不能小于0");
            }
            validateDecimalPlaces(entity.getCardFee(), "cardFee", 2);
        }
        if (entity.getOriginalCardFee() != null) {
            if (entity.getOriginalCardFee().compareTo(BigDecimal.ZERO) < 0) {
                throw ServiceException.exception("原卡片费用不能小于0");
            }
            validateDecimalPlaces(entity.getOriginalCardFee(), "originalCardFee", 2);
        }
        if (entity.getRechargeMinQuota() != null) {
            // 校验充值最小额度配置
            if (entity.getRechargeMinQuota().compareTo(typeTable.getRechargeMinQuota()) < 0) {
                throw ServiceException.exception("充值最小额度不能小于三方充值的最小额度");
            }
            if (entity.getRechargeMinQuota().compareTo(typeTable.getRechargeMaxQuota()) > 0) {
                throw ServiceException.exception("充值最小额度不能大于三方充值的最大额度");
            }
            validateDecimalPlaces(entity.getRechargeMinQuota(), "rechargeMinQuota", 2);
        }
        if (entity.getRechargeMaxQuota() != null) {
            // 校验充值最大额度配置
            if (entity.getRechargeMaxQuota().compareTo(typeTable.getRechargeMaxQuota()) > 0) {
                throw ServiceException.exception("充值最大额度不能大于三方充值的最大额度");
            }
            if (entity.getRechargeMaxQuota().compareTo(typeTable.getRechargeMinQuota()) < 0) {
                throw ServiceException.exception("充值最大额度不能小于三方充值的最小额度");
            }
            validateDecimalPlaces(entity.getRechargeMinQuota(), "rechargeMinQuota", 2);
        }
        if (entity.getRechargeMaxQuota() != null && entity.getRechargeMinQuota() != null) {
            if (entity.getRechargeMaxQuota().compareTo(entity.getRechargeMinQuota()) < 0) {
                throw ServiceException.exception("充值最大额度不能小于充值最小额度");
            }
        }
        CardTypeConfigTable table = cardTypeConfigRepository.findByCardTypeId(entity.getCardTypeId());
        if (table == null) {
            table = new CardTypeConfigTable();
            table.setAddTime(new Date());
        } else {
            table.setModifyTime(new Date());
        }
        BeanUtils.copyProperties(entity, table);
        table.setIsContact(true);
        cardTypeConfigRepository.save(table);
        return BaseResultDto.success();
    }

    /**
     * 证件类型配置列表
     */
    @Override
    public ResultWithPagerDto<CardIdTypeConfigDto> getCardIdTypeConfigList(CardIdTypeConfigPageEntity entity) throws ServiceException {
        try {
            // 获取总数
            Integer count = cardIdTypeConfigMapper.countList(entity);
            PageDto pageDto = PageDto.format(entity, count);
            if (count == null || count <= 0) {
                return ResultWithPagerDto.success(pageDto);
            }
            List<CardIdTypeConfigDto> dtos = cardIdTypeConfigMapper.pageList(entity);
            return ResultWithPagerDto.success(pageDto, dtos);
        } catch (Exception e) {
            log.error("获取证件类型配置列表失败", e);
            throw new ServiceException("获取证件类型配置列表失败");
        }
    }

    /**
     * 批量更新证件类型配置
     */
    @Override
    public BaseResultDto batchAddCardIdTypeConfig(List<CardIdTypeConfigAddEntity> entitys) throws ServiceException {
        cardIdTypeConfigMapper.batchSave(entitys);
        return BaseResultDto.success();
    }

    /**
     * 更新证件类型配置
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResultDto updateCardIdTypeConfig(CardIdTypeConfigUpdateEntity entity) throws ServiceException {
        CardIdTypeConfigTable table = cardIdTypeConfigRepository.findFirstById(entity.getId());
        if (table == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        BeanUtils.copyProperties(entity, table);
        cardIdTypeConfigRepository.save(table);
        return BaseResultDto.success();
    }

    /**
     * 批量删除证件类型配置
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResultDto deleteCardIdTypeConfig(BaseDeleteEntities entity) throws ServiceException {
        List<CardIdTypeConfigTable> tables = Lists.newArrayList();
        for (Long id : entity.getIds()) {
            CardIdTypeConfigTable table = new CardIdTypeConfigTable();
            table.setId(id);
            tables.add(table);
        }
        cardIdTypeConfigRepository.deleteInBatch(tables);
        return BaseResultDto.success();
    }

    /**
     * 验证金额小数位数不能超过10位
     *
     * @param amount    待验证的金额
     * @param fieldName 字段名称（用于错误提示）
     * @throws ServiceException 当小数位数超过10位时抛出异常
     */
    private void validateDecimalPlaces(BigDecimal amount, String fieldName, int maxDecimalPlaces) throws ServiceException {
        if (amount != null) {
            String amountStr = amount.stripTrailingZeros().toPlainString();
            int decimalIndex = amountStr.indexOf(".");
            if (decimalIndex != -1) {
                int decimalPlaces = amountStr.length() - decimalIndex - 1;
                if (decimalPlaces > maxDecimalPlaces) {
                    throw new ServiceException(fieldName + "小数位数不能超过" + maxDecimalPlaces + "位");
                }
            }
        }
    }




}
