package com.crm.manager.service.impl;

import com.alibaba.fastjson.JSON;
import com.crm.manager.dao.mapper.CustomAllocationRosterScheduledMapper;
import com.crm.manager.dao.repository.CustomAllocationRosterScheduledRepository;
import com.crm.manager.service.CustomAllocationRosterScheduledService;
import com.crm.manager.service.CustomAllocationRosterService;
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.dto.custom.allocation.roster.scheduled.CustomAllocationRosterScheduledDto;
import com.crm.rely.backend.core.dto.custom.allocation.roster.scheduled.CustomAllocationRosterScheduledRuleDto;
import com.crm.rely.backend.core.entity.base.SingleLongEntity;
import com.crm.rely.backend.core.entity.custom.allocation.roster.CustomAllocationRosterClickByCountrysEntity;
import com.crm.rely.backend.core.entity.custom.allocation.roster.scheduled.*;
import com.crm.rely.backend.core.pojo.table.CustomAllocationRosterScheduledTable;
import com.crm.rely.backend.exception.ServiceException;
import com.crm.rely.backend.util.DateUtil;
import com.google.common.base.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class CustomAllocationRosterScheduledServiceImpl implements CustomAllocationRosterScheduledService {

    private static final int ADVANCE_DAY = 0;
    @Autowired
    private CustomAllocationRosterScheduledRepository repository;
    @Autowired
    private CustomAllocationRosterScheduledMapper mapper;
    @Autowired
    private CustomAllocationRosterService customAllocationRosterService;

//    @Scheduled(fixedDelay = 1 * 60 * 1000)
    public void scheduleAddCustomAllocationRoster() throws Exception {
        Date today = new Date();
        Calendar calender = Calendar.getInstance();
        calender.setTime(today);
        //计算出来的默认周 -1 那么周日为0 其他1-6
        int weekday = calender.get(Calendar.DAY_OF_WEEK) - 1;

        //如果是周日 则改为7
        if (weekday == 0) {
            weekday = 7;
        }

        //时间+
        weekday = weekday + ADVANCE_DAY;
        //使用% 用余数方法继续得到周几
        weekday = weekday % 7;
        //如果是周日 则改为7
        if (weekday == 0) {
            weekday = 7;
        }

        Date todayReduce7 = DateUtil.operationDay(today, -7);
        java.sql.Date lastDate = new java.sql.Date(DateUtil.parseDate(todayReduce7).getTime());
        //需要提前两天添加数据
        List<CustomAllocationRosterScheduledTable> scheduledTables1 =
                repository.findAllByWeekdayAndLastTimeIsNull(weekday);
        List<CustomAllocationRosterScheduledTable> scheduledTables2 =
                repository.findAllByWeekdayAndLastTime(weekday, lastDate);

        List<CustomAllocationRosterScheduledTable> scheduledTables = new ArrayList<>();
        if (scheduledTables1 != null && scheduledTables1.size() > 0) {
            scheduledTables.addAll(scheduledTables1);
        }
        if (scheduledTables2 != null && scheduledTables2.size() > 0) {
            scheduledTables.addAll(scheduledTables2);
        }

        //如果得到
        if (scheduledTables.size() > 0) {
            for (CustomAllocationRosterScheduledTable table : scheduledTables) {
                if (Strings.isNullOrEmpty(table.getRules())) {
                    break;
                }

                List<CustomAllocationRosterScheduledRuleEntity> ruleEntities = JSON.parseArray(table.getRules(),
                        CustomAllocationRosterScheduledRuleEntity.class);
                if (ruleEntities == null || table.getRules().isEmpty()) {
                    break;
                }

                table.setLastTime(today);
                ruleEntities.forEach(rule -> {
                    if (rule.getRuleCountrys() == null || rule.getRuleCountrys().isEmpty()) {
                        return;
                    }
                    CustomAllocationRosterClickByCountrysEntity entity =
                            new CustomAllocationRosterClickByCountrysEntity();
                    List<String> countrys = new ArrayList<>(rule.getRuleCountrys().size());
                    for (CustomAllocationRosterScheduledRuleCountryEntity customAllocationRosterScheduledRuleCountryEntity : rule.getRuleCountrys()) {
                        countrys.add(customAllocationRosterScheduledRuleCountryEntity.getCountry());
                    }
                    entity.setCountrys(countrys);
                    entity.setIbNo(rule.getIbNo());
                    entity.setRuleNumber(rule.getRuleNumber());
                    customAllocationRosterService.clickAllocationRosterByCountrys(entity);
                });


            }
            repository.save(scheduledTables);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(CustomAllocationRosterScheduledAddEntity entity) throws ServiceException {
        CustomAllocationRosterScheduledTable table = new CustomAllocationRosterScheduledTable();
        BeanUtils.copyProperties(entity, table);
        table.setRules(JSON.toJSONString(entity.getRules()));
        table.setLastTime(null);
        repository.save(table);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(CustomAllocationRosterScheduledUpdateEntity entity) throws ServiceException {
        CustomAllocationRosterScheduledTable table = repository.findFirstById(entity.getId());
        if (table == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        BeanUtils.copyProperties(entity, table);
        table.setRules(JSON.toJSONString(entity.getRules()));
        table.setLastTime(null);
        repository.save(table);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(CustomAllocationRosterScheduledDeleteEntity entity) throws ServiceException {

        List<CustomAllocationRosterScheduledTable> tables = repository.findAllByIdIn(entity.getIds());
        if (tables == null || tables.size() <= 0) {
            return;
        }
        repository.delete(tables);
    }

    @Override
    public ResultWithPagerDto<CustomAllocationRosterScheduledDto> searchPageList(CustomAllocationRosterScheduledSearchEntity entity) throws ServiceException {
        Integer count = mapper.countList(entity);
        PageDto pageDto = PageDto.format(entity, count);
        if (count == null || count <= 0) {
            return ResultWithPagerDto.success(pageDto);
        }

        List<CustomAllocationRosterScheduledDto> dtos = getCustomAllocationRosterScheduledDto(entity);
        if (dtos == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }
        return ResultWithPagerDto.success(pageDto, dtos);
    }

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

        return dto;
    }

    private List<CustomAllocationRosterScheduledDto> getCustomAllocationRosterScheduledDto(CustomAllocationRosterScheduledSearchEntity entity) throws ServiceException {
        List<CustomAllocationRosterScheduledTable> tables = mapper.pageList(entity);

        if (tables == null || tables.size() <= 0) {

            return null;
        }
        List<CustomAllocationRosterScheduledDto> dtos = new ArrayList<>(tables.size());

        for (CustomAllocationRosterScheduledTable table : tables) {
            CustomAllocationRosterScheduledDto riskRevokeCreditRuleGroupDto = transform(table);
            dtos.add(riskRevokeCreditRuleGroupDto);
        }
        return dtos;
    }

    private CustomAllocationRosterScheduledDto transform(CustomAllocationRosterScheduledTable table) {
        CustomAllocationRosterScheduledDto dto = new CustomAllocationRosterScheduledDto();
        BeanUtils.copyProperties(table, dto);
        dto.setRules(JSON.parseArray(table.getRules(), CustomAllocationRosterScheduledRuleDto.class));
        return dto;
    }
}
