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.CardNumberDto;
import com.crm.rely.backend.core.entity.base.BaseDeleteEntities;
import com.crm.rely.backend.core.entity.ucard.CardNumberAddEntity;
import com.crm.rely.backend.core.entity.ucard.CardNumberPageEntity;
import com.crm.rely.backend.core.entity.ucard.CardNumberUpdateEntity;
import com.crm.rely.backend.core.entity.ucard.CardNumberVerifyEntity;
import com.crm.rely.backend.core.pojo.table.ucard.CardApplyTable;
import com.crm.rely.backend.core.pojo.table.ucard.UcardCardNumberTable;
import com.crm.rely.backend.exception.ServiceException;
import com.crm.rely.backend.util.ListSplitUtil;
import com.crm.ucard.dao.mapper.CardApplyMapper;
import com.crm.ucard.dao.mapper.UcardCardNumberMapper;
import com.crm.ucard.dao.repository.UcardCardNumberRepository;
import com.crm.ucard.service.UcardNumberService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UcardNumberServiceImpl implements UcardNumberService {

    @Autowired
    private CardApplyMapper cardApplyMapper;
    @Autowired
    private UcardCardNumberRepository cardNumberRepository;
    @Autowired
    private UcardCardNumberMapper cardNumberMapper;


    /**
     * 根据卡号修改状态
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveCardNumberStatus(String cardNumber, Integer status) throws ServiceException {
        UcardCardNumberTable cardNumberTable = cardNumberRepository.findByCardNumber(cardNumber);
        if (cardNumberTable == null) {
            cardNumberTable = new UcardCardNumberTable();
            cardNumberTable.setCardNumber(cardNumber);
        }
        cardNumberTable.setStatus(status);
        cardNumberRepository.save(cardNumberTable);
    }

    /**
     * 校验实体卡卡号是否使用过
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResultDto cardNumberVerify(CardNumberVerifyEntity entity) throws ServiceException {
        CardApplyTable table = cardApplyMapper.cardNumberVerify(entity.getCardNumber().trim());
        if (table != null) {
            saveCardNumberStatus(table.getCardNumber(), 3);
            return BaseResultDto.error("该实体卡卡号已被使用。");
        }
        saveCardNumberStatus(entity.getCardNumber(), 2);
        return BaseResultDto.success();
    }

    /**
     * 导入卡号
     */
    @Override
    public BaseResultDto cardNumberImport(List<CardNumberAddEntity> entityList) throws ServiceException {
        if (CollectionUtils.isEmpty(entityList)) {
            return BaseResultDto.success();
        }
        // 查询数据库中所有的卡号
        List<UcardCardNumberTable> tables = cardNumberRepository.findAll();
        // 查询使用过的卡号
        List<String> numberList = cardApplyMapper.queryAllUsedCardNumber();
        List<UcardCardNumberTable> tableList = Lists.newArrayList();
        // 过滤数据库中的卡号
        if (CollectionUtils.isNotEmpty(tables)) {
            List<String> cardNumbers =
                    tables.stream().map(UcardCardNumberTable::getCardNumber).collect(Collectors.toList());
            entityList =
                    entityList.stream().filter(entity -> !cardNumbers.contains(entity.getCardNumber())).collect(Collectors.toList());
        }
        // 过滤使用过的卡号
        if (CollectionUtils.isNotEmpty(numberList)) {
            entityList =
                    entityList.stream().filter(entity -> !numberList.contains(entity.getCardNumber())).collect(Collectors.toList());
        }

        entityList.forEach(entity -> {
            UcardCardNumberTable table = new UcardCardNumberTable();
            table.setCardNumber(entity.getCardNumber());
            table.setStatus(1);
            tableList.add(table);
        });
        if (CollectionUtils.isNotEmpty(tableList)) {
            List<List<UcardCardNumberTable>> lists = ListSplitUtil.split(tableList);
            for (List<UcardCardNumberTable> list : lists) {
                cardNumberMapper.batchSave(list);
            }
        }
        return BaseResultDto.success();
    }

    /**
     * 卡号列表
     */
    @Override
    public ResultWithPagerDto<CardNumberDto> queryCardNumberList(CardNumberPageEntity entity) throws ServiceException {
        try {
            // 获取总数
            Integer count = cardNumberMapper.countList(entity);
            PageDto pageDto = PageDto.format(entity, count);
            if (count == null || count <= 0) {
                return ResultWithPagerDto.success(pageDto);
            }
            List<CardNumberDto> dtos = cardNumberMapper.pageList(entity);
            return ResultWithPagerDto.success(pageDto, dtos);
        } catch (Exception e) {
            log.error("获取卡号列表失败", e);
            throw new ServiceException("获取卡号列表失败");
        }
    }

    /**
     * 卡号下拉列表
     */
    @Override
    public BaseResultDto<CardNumberDto> queryCardNumberDropdown(CardNumberPageEntity entity) throws ServiceException {
        entity.setPage(null);
        List<CardNumberDto> dtos = cardNumberMapper.pageList(entity);
        return BaseResultDto.success(dtos);
    }

    /**
     * 修改卡号状态
     */
    @Override
    public BaseResultDto saveCardNumberStatus(CardNumberUpdateEntity entity) throws ServiceException {
        UcardCardNumberTable table = cardNumberRepository.findOne(entity.getId());
        if (table == null) {
            BaseResultDto.error(Constants.INFO_NOT_FOUND);
        }
        table.setStatus(entity.getStatus());
        cardNumberRepository.save(table);
        return BaseResultDto.success();
    }

    /**
     * 删除实体卡卡号
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResultDto deleteCardNumber(BaseDeleteEntities entity) {
        List<UcardCardNumberTable> tables = Lists.newArrayList();
        for (Long id : entity.getIds()) {
            UcardCardNumberTable table = new UcardCardNumberTable();
            table.setId(id);
            tables.add(table);
        }
        cardNumberRepository.deleteInBatch(tables);
        return BaseResultDto.success();
    }


}
