package com.crm.manager.service.impl;

import com.crm.manager.dao.mapper.CustomAllocationRosterMapper;
import com.crm.manager.dao.repository.CustomAllocationRosterRepository;
import com.crm.manager.dao.repository.UserInfoRepository;
import com.crm.manager.service.CustomAllocationRosterRecordService;
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.CustomAllocationRosterCsvDto;
import com.crm.rely.backend.core.dto.custom.allocation.roster.CustomAllocationRosterDto;
import com.crm.rely.backend.core.entity.custom.allocation.roster.CustomAllocationRosterClickByCountrysEntity;
import com.crm.rely.backend.core.entity.custom.allocation.roster.CustomAllocationRosterClickEntity;
import com.crm.rely.backend.core.entity.custom.allocation.roster.CustomAllocationRosterSearchEntity;
import com.crm.rely.backend.core.entity.custom.allocation.roster.CustomAllocationRosterUpdateEntity;
import com.crm.rely.backend.core.pojo.table.CustomAllocationRosterTable;
import com.crm.rely.backend.core.pojo.table.UserInfoTable;
import com.crm.rely.backend.core.pojo.view.CustomAllocationRosterView;
import com.crm.rely.backend.exception.ServiceException;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
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.Date;
import java.util.List;

/**
 * @Author houn
 * @Date 2023/2/20 12:36
 * @PackageName:com.crm.manager.service.impl
 * @ClassName: CustomAllocationRosterServiceImpl
 * @Description: TODO
 */
@Slf4j
@Service
class CustomAllocationRosterServiceImpl implements CustomAllocationRosterService {
    @Autowired
    private CustomAllocationRosterMapper dao;

    @Autowired
    private CustomAllocationRosterRepository repository;

    @Autowired
    private CustomAllocationRosterRecordService customAllocationRosterRecordService;

    @Autowired
    private UserInfoRepository userInfoRepository;

    @Override
    public ResultWithPagerDto<CustomAllocationRosterDto> selectPageList(CustomAllocationRosterSearchEntity
                                                                                searchPageList) throws ServiceException {
        int count = selectCount(searchPageList);
        PageDto pageDto = PageDto.format(searchPageList, count);
        if (count <= 0) {
            return ResultWithPagerDto.success(pageDto);
        }
        List<CustomAllocationRosterDto> dtos = getDto(searchPageList);
        if (dtos == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }
        return ResultWithPagerDto.success(pageDto, dtos);
    }

    @Override
    public List<CustomAllocationRosterCsvDto> selectCsvList(CustomAllocationRosterSearchEntity searchPageList) throws ServiceException {
        List<CustomAllocationRosterView> views = dao.selectCsvList(searchPageList);
        if (views == null || views.size() <= 0) {
            return null;
        }
        List<CustomAllocationRosterCsvDto> dtos = new ArrayList<>(views.size());
        for (CustomAllocationRosterView view : views) {
            CustomAllocationRosterCsvDto dto = new CustomAllocationRosterCsvDto();
            BeanUtils.copyProperties(view, dto);

            dtos.add(dto);
        }
        return dtos;
    }

    @Override
    public int selectCount(CustomAllocationRosterSearchEntity searchCount) {
        return dao.selectCount(searchCount);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(CustomAllocationRosterUpdateEntity entity) throws ServiceException {
        List<CustomAllocationRosterTable> tables = null;

        //如果是销售在分配 啧只能分配现在隶属自己名下的客户
        if (entity.getAllocationId() != null) {
            tables = repository.findAllByIdInAndAllocationAgentId(entity.getIds(), entity.getAllocationId());
        } else {
            tables = repository.findAllByIdIn(entity.getIds());
        }
        if (tables == null) {
            return;
        }
        if (!entity.getStatus().equals(1)) {
            entity.setAllocationAgentId(null);
        }
        Date allocationTime = new Date();
        for (CustomAllocationRosterTable table : tables) {
            table.setAllocationTime(allocationTime);
            //如果穿进来的不为空 则不是管理员 不是管理员就判断当前用户是不是上级给分配的代理 如果不是 则无权限
            if (entity.getAllocationId() != null) {
                if (!entity.getAllocationId().equals(table.getAllocationAgentId())) {
                    throw ServiceException.exception(Constants.NOT_PERMIT);
                }
            }

            //判断是否分配 添加分配次数
            if (entity.getStatus().equals(1) && entity.getAllocationAgentId() != null && !entity.getAllocationAgentId().equals(table.getAllocationAgentId())) {
                if (table.getNumber() == null) {
                    table.setNumber(0);
                }
                table.setNumber(table.getNumber() + 1);
            }

            BeanUtils.copyProperties(entity, table);

            if (!table.getStatus().equals(1)) {
                table.setAllocationTime(null);
            }
        }

        repository.save(tables);

        customAllocationRosterRecordService.add(tables);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void clickAllocationRoster(CustomAllocationRosterClickEntity entity) {
        customAllocationRosterRecordService.clickAllocationRoster(entity);

        //dao.clickAllocationRoster(entity);

        UserInfoTable user = userInfoRepository.findFirstByIbNo(entity.getIbNo());
        List<CustomAllocationRosterTable> tables = dao.findClickAllocationRoster(entity);
        for (CustomAllocationRosterTable table : tables) {
            table.setAllocationAgentId(user == null ? null : user.getId());
            table.setStatus(entity.getStatus());
            table.setNumber(table.getNumber() == null ? 1 : table.getNumber() + 1);
            table.setAllocationTime(new Date());
        }
        repository.save(tables);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void clickAllocationRosterByCountrys(CustomAllocationRosterClickByCountrysEntity entity) {
        customAllocationRosterRecordService.clickAllocationRosterByCountrys(entity);

        //dao.clickAllocationRosterByCountrys(entity);

        if(entity.getCountrys()!=null && entity.getCountrys().size()>0 && !Strings.isNullOrEmpty(entity.getIbNo())){
            UserInfoTable user = userInfoRepository.findFirstByIbNo(entity.getIbNo());
            List<CustomAllocationRosterTable> tables = dao.findClickAllocationRosterByCountrys(entity);
            for (CustomAllocationRosterTable table : tables) {
                table.setAllocationAgentId(user.getId());
                table.setStatus(1);
                table.setNumber(table.getNumber() == null ? 1 : table.getNumber() + 1);
                table.setAllocationTime(new Date());
            }
            repository.save(tables);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateFollowTagById(Long id) throws ServiceException {
        CustomAllocationRosterTable table = repository.findFirstById(id);
        if (table == null) {
            return;
        }
        if (table.getStatus() != null && !table.getStatus().equals(1)) {
            return;
        }
        if (table.getFollowTag() != null) {
            return;
        }
        table.setFollowTag(1);
        table.setFollowTime(new Date());
        repository.save(table);
    }

    /**
     * 添加分配用户
     *
     * @throws ServiceException
     */
    @Scheduled(fixedDelay = 1000 * 60 * 60)
    @Transactional(rollbackFor = Exception.class)
    public synchronized void scheduleAddAllocationTask() throws ServiceException {
        dao.taskAddAllocation("CN");
        dao.taskAddAllocation("EN");
    }

    /**
     * 回收用户
     *
     * @throws ServiceException
     */
    @Scheduled(fixedDelay = 1000 * 60 * 60)
    @Transactional(rollbackFor = Exception.class)
    public synchronized void scheduleUpdateAllocationRecoveryTask() throws ServiceException {
        dao.taskUpdateAllocationRecovery();

//        dao.taskUpdateAllocationRecoveryByCN();
    }

    @Scheduled(fixedDelay = 1000 * 60 * 60)
    @Transactional(rollbackFor = Exception.class)
    public synchronized void scheduleUpdateAllocationAllocationReviseAgentTask() throws ServiceException {
        dao.taskUpdateAllocationReviseAgent();
    }

    private List<CustomAllocationRosterDto> getDto(CustomAllocationRosterSearchEntity search) {
        List<CustomAllocationRosterView> views = dao.selectList(search);
        if (views == null || views.size() <= 0) {
            return null;
        }
        List<CustomAllocationRosterDto> dtos = new ArrayList<>(views.size());
        for (CustomAllocationRosterView view : views) {
            CustomAllocationRosterDto dto = transform(view);
            dtos.add(dto);
        }
        return dtos;
    }

    private CustomAllocationRosterDto transform(CustomAllocationRosterView view) {
        CustomAllocationRosterDto dto = new CustomAllocationRosterDto();
        BeanUtils.copyProperties(view, dto);
        return dto;
    }
}
