package com.crm.custom.service.impl;

import com.crm.custom.dao.mapper.GoldenQuestionCustomMapper;
import com.crm.custom.dao.mapper.GoldenRewardQuestionMapper;
import com.crm.custom.dao.repository.*;
import com.crm.custom.service.GoldenRewardQuestionService;
import com.crm.custom.service.SysConfigService;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.dto.base.PageDto;
import com.crm.rely.backend.core.dto.base.ResultWithPagerDto;
import com.crm.rely.backend.core.entity.base.SingleLongEntity;
import com.crm.rely.backend.core.exception.ServiceException;
import com.crm.rely.backend.core.pojo.table.SysConfigTable;
import com.crm.rely.backend.model.constant.ConfigConstants;
import com.crm.rely.backend.model.dto.golden.question.GoldenRewardQuestionDto;
import com.crm.rely.backend.model.dto.golden.question.GoldenRewardQuestionListDto;
import com.crm.rely.backend.model.entity.golden.question.*;
import com.crm.rely.backend.model.pojo.table.*;
import com.crm.rely.backend.util.DateUtil;
import com.google.common.base.Strings;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Log4j
@Service
public class GoldenRewardQuestionServiceImpl implements GoldenRewardQuestionService {

    @Autowired
    private GoldenRewardQuestionRepository repository;
    @Autowired
    private GoldenRewardQuestionMapper mapper;
    @Autowired
    private CustomInfoRepository customInfoRepository;
    @Autowired
    private GoldenQuestionCustomMapper goldenQuestionCustomMapper;
    @Autowired
    private GoldenQuestionCustomRepository goldenQuestionCustomRepository;
    @Autowired
    private GoldenCustomRewardRecordRepository goldenCustomRewardRecordRepository;
    @Autowired
    private GoldenCustomBalanceRecordRepository customBalanceRecordRepository;
    @Autowired
    private SysConfigService sysConfigService;

    @Override
    public GoldenRewardQuestionDto getQuestion(Long customId) throws Exception {
        GoldenRewardQuestionDto dto = new GoldenRewardQuestionDto();
        dto.setType(0);

        GoldenCustomRewardRecordTable record = goldenCustomRewardRecordRepository.findFirstByCustomId(customId);
        if (record != null && record.getStatus() == 1) {
            Date startDate = DateUtil.getThisWeekMonday(new Date());
            Date endDate = DateUtil.addDate(startDate,7);
            Integer count = goldenQuestionCustomMapper.getCountQuestionByDate(customId,startDate,endDate);
            if (count == null || count <= 0) {
                GoldenRewardQuestionTable table =  mapper.getRandQuestion();
                if (table != null) {
                    dto.setQuestionId(table.getId());
                    dto.setQuestion(table.getQuestion());
                    dto.setType(1);
                }
            }
        }

        return dto;
    }

    @Override
    public void customAddQuestion(GoldenQuestionCustomAddEntity entity) throws Exception {
        Date startDate = DateUtil.getThisWeekMonday(new Date());
        Date endDate = DateUtil.addDate(startDate,7);
        Integer count = goldenQuestionCustomMapper.getCountQuestionByDate(entity.getCustomId(),startDate,endDate);
        if (count != null && count > 0) {
            throw ServiceException.exception("reward_question_already_exist");
        }

        GoldenRewardQuestionTable questionTable = repository.getFirstById(entity.getQuestionId());
        if (questionTable == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }

        GoldenQuestionCustomTable table = new GoldenQuestionCustomTable();
        BeanUtils.copyProperties(entity, table);
        table.setQuestion(questionTable.getQuestion());
        table.setAnswer(questionTable.getAnswer());
        table.setCustomRight(questionTable.getAnswer() == table.getCustomAnswer() ? 1 : 0 );
        goldenQuestionCustomRepository.save(table);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(GoldenRewardQuestionAddEntity entity) throws ServiceException {
        GoldenRewardQuestionTable table = new GoldenRewardQuestionTable();
        BeanUtils.copyProperties(entity, table);
        repository.save(table);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(GoldenRewardQuestionDeleteEntitys entity) throws ServiceException {
        List<GoldenRewardQuestionTable> tables = repository.findAllByIdIn(entity.getIds());
        if (tables == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        repository.delete(tables);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(GoldenRewardQuestionUpdateEntity entity) throws ServiceException {
        GoldenRewardQuestionTable table = repository.findFirstById(entity.getId());
        if (table == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        BeanUtils.copyProperties(entity, table);
        repository.save(table);
    }

    @Override
    public ResultWithPagerDto<GoldenRewardQuestionListDto> searchPageList(GoldenRewardQuestionSearchEntity entity) throws ServiceException {
        Integer count = mapper.countList(entity);
        PageDto pageDto = PageDto.format(entity, count);
        if (count == null || count <= 0) {
            return ResultWithPagerDto.success(pageDto);
        }
        List<GoldenRewardQuestionTable> tables = mapper.pageList(entity);
        if (tables == null || tables.size() <= 0) {
            throw new ServiceException(Constants.SYSTEM_ERROR);
        }
        List<GoldenRewardQuestionListDto> dtos = new ArrayList<>(tables.size());

        for (GoldenRewardQuestionTable table : tables) {
            GoldenRewardQuestionListDto dto = transformSearchListDto(table);
            dtos.add(dto);
        }

        return ResultWithPagerDto.success(pageDto, dtos);
    }

    @Override
    public GoldenRewardQuestionListDto searchSingle(SingleLongEntity entity) throws ServiceException {
        GoldenRewardQuestionTable table = repository.getFirstById(entity.getId());
        if (table == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }

        return transformSearchListDto(table);
    }

    private GoldenRewardQuestionListDto transformSearchListDto(GoldenRewardQuestionTable table) {
        GoldenRewardQuestionListDto dto = new GoldenRewardQuestionListDto();
        BeanUtils.copyProperties(table, dto);
        return dto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void rewardQuestionTask() throws Exception {
        SysConfigTable sysConfigTable =
                sysConfigService.getByCode(ConfigConstants.CUSTOM_REWARD_QUESTION_AMOUNT);
        BigDecimal giveAmount = (sysConfigTable == null || sysConfigTable.getValue() == null)
                ? BigDecimal.ZERO : new BigDecimal(sysConfigTable.getValue());

        List<GoldenCustomRewardRecordTable> list = goldenCustomRewardRecordRepository.findByStatus(1);
        for (GoldenCustomRewardRecordTable table : list){
            Date endDate = DateUtil.addDate(table.getStartDate(),180);
            if(DateUtil.formatDate(new Date()).compareTo(DateUtil.formatDate(endDate)) >= 0){
                Integer count = goldenQuestionCustomMapper.getCountQuestionByDate(table.getCustomId(),table.getStartDate(),endDate);
                count = count == null ? 0 : count;

                Integer num = DateUtil.weekBetween(table.getStartDate(),endDate);
                if( count >= num ){
                    table.setStatus(2);
                    table.setGrantStatus(2);

                    CustomInfoTable custom = customInfoRepository.findFirstById(table.getCustomId());
                    BigDecimal balance = custom.getBalance() == null ? BigDecimal.ZERO : custom.getBalance();
                    custom.setBalance(balance.add(giveAmount));
                    customInfoRepository.save(custom);

                    GoldenCustomBalanceRecordTable record = new GoldenCustomBalanceRecordTable();
                    record.setCustomId(custom.getId());
                    record.setCId(custom.getCId());
                    record.setAmount(giveAmount);
                    record.setType(2);
                    record.setAddTime(new Date());
                    customBalanceRecordRepository.save(record);

                }else{
                    table.setStatus(3);
                }
                table.setModifyTime(new Date());

                goldenCustomRewardRecordRepository.save(table);
            }
        }

    }

    @JmsListener(destination = ConfigConstants.CUSTOM_REWARD_RECORD)
    @Transactional(rollbackFor = Exception.class)
    public void addCustomRewardRecord(String content) throws ServiceException {
        log.info(String.format("CUSTOM_REWARD_RECORD,content-customId:%s", content));

        if (Strings.isNullOrEmpty(content)) {
            log.error("CUSTOM_REWARD_RECORD,content is null");
            return;
        }

        GoldenCustomRewardRecordTable recodeTable = goldenCustomRewardRecordRepository.findFirstByCustomId(Long.valueOf(content));
        if(recodeTable == null){
            GoldenCustomRewardRecordTable table = new GoldenCustomRewardRecordTable();
            table.setCustomId(Long.valueOf(content));
            table.setStartDate(new Date());
            table.setStatus(1);
            table.setGrantStatus(1);
            table.setAddTime(new Date());
            goldenCustomRewardRecordRepository.save(table);
        }

    }

}
