package com.crm.custom.service.impl;

import com.crm.custom.dao.mapper.CustomLoginDemoMapper;
import com.crm.custom.dao.repository.CustomLoginDemoRepository;
import com.crm.custom.service.*;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.constant.StatusConstants;
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.exception.ServiceException;
import com.crm.rely.backend.model.constant.CustomConstants;
import com.crm.rely.backend.model.dto.custom.login.CustomLoginConditionDto;
import com.crm.rely.backend.model.dto.custom.login.CustomLoginDemoDto;
import com.crm.rely.backend.model.entity.custom.info.CustomInfoUpdateAgentEntity;
import com.crm.rely.backend.model.entity.custom.login.CustomLoginCheckByLoginEntity;
import com.crm.rely.backend.model.entity.custom.login.demo.CustomLoginDemoApproveEntity;
import com.crm.rely.backend.model.entity.custom.login.demo.CustomLoginDemoSearchListEntity;
import com.crm.rely.backend.model.entity.custom.login.demo.CustomLoginDemoUpdateCheckByLoginEntity;
import com.crm.rely.backend.model.pojo.table.CustomLoginDemoTable;
import com.crm.rely.backend.model.pojo.view.CustomLoginDemoView;
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.ArrayList;
import java.util.List;

@Service
public class CustomLoginDemoServiceImpl implements CustomLoginDemoService {

    @Autowired
    private CustomLoginDemoRepository repository;

    @Autowired
    private CustomLoginDemoMapper mapper;

    @Autowired
    private FinanceTrainFeignService financeTrainFeignService;

    @Autowired
    private CustomLoginService customLoginService;

    @Autowired
    private WebVideoFeignService webVideoFeignService;

    @Autowired
    private CustomInfoService customInfoService;

    /**
     * 是否有在的账号或者成功的账号
     *
     * @param customId
     * @return
     * @throws ServiceException
     */
    @Override
    public boolean existDemoStatus(Long customId) throws ServiceException {
        List<Integer> sts = new ArrayList<>(3);
        sts.add(StatusConstants.APPLY_PENDING_STATUS);
        sts.add(StatusConstants.APPLY_STATUS);
        sts.add(StatusConstants.PASSED_STATUS);
        return repository.existsByCustomIdAndStatusIn(customId, sts);
    }

    @Override
    public boolean existDemoStatus(Long customId, Integer status) throws ServiceException {

        return repository.existsByCustomIdAndStatus(customId, status);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Long login, Integer valid) throws ServiceException {
        CustomLoginDemoTable table = repository.findFirstByLogin(login);
        if (table != null) {
            table.setValid(valid);
            table.setLoginStatus(StatusConstants.MANAGER_PENDING_STATUS);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void applyCheck(CustomLoginDemoUpdateCheckByLoginEntity entity) throws ServiceException {
        CustomLoginDemoTable table = repository.findFirstByLoginAndCustomId(entity.getLogin(), entity.getCustomId());
        if (table == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        //如果是申请考核
        if (StatusConstants.APPLY_STATUS.equals(entity.getStatus())) {
            //判断状态是否为初始状态
            if (!StatusConstants.APPLY_PENDING_STATUS.equals(table.getStatus())) {
                throw ServiceException.exception(Constants.NOT_PERMIT);
            }
        }
        //如果放弃考核
        else if (StatusConstants.APPLY_ABANDON_STATUS.equals(entity.getStatus())) {
            //判断状态是否为申请中
            if (!StatusConstants.APPLY_STATUS.equals(table.getStatus())) {
                throw ServiceException.exception(Constants.NOT_PERMIT);
            }
        }
        table.setLoginStatus(StatusConstants.MANAGER_PENDING_STATUS);
        table.setValid(0);
        table.setStatus(entity.getStatus());
        repository.save(table);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CustomLoginDemoTable approve(CustomLoginDemoApproveEntity entity) throws ServiceException {
        CustomLoginDemoTable table = repository.findFirstById(entity.getId());
        if (table == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        if (!StatusConstants.APPLY_STATUS.equals(table.getStatus())) {
            throw ServiceException.exception(Constants.NOT_PERMIT);
        }
        BeanUtils.copyProperties(entity, table);
        repository.save(table);

        return table;
    }

    @Override
    public CustomLoginConditionDto conditionDemo(CustomLoginCheckByLoginEntity entity) throws Exception {

        BaseResultDto<Boolean> resultDto = financeTrainFeignService.validateLogin(entity);
        CustomLoginConditionDto dto = new CustomLoginConditionDto();
        dto.setTrainCondition((resultDto != null && resultDto.getData()) ? 1 : 0);

        boolean exist = customLoginService.existByCustomIdAndEquity(entity.getCustomId(), CustomConstants.CUSTOM_LOGIN_CONDITION);
        dto.setCustomLoginCondition(exist ? 1 : 0);
        dto.setLogin(entity.getLogin());
        return dto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void studyDemo(CustomLoginCheckByLoginEntity entity) throws Exception {
        CustomLoginDemoTable table = repository.getFirstByLogin(entity.getLogin());
        if (table == null) {
            throw ServiceException.exception(Constants.FAIL);
        }
        //账号只有是拒绝的账号才能进行重新学习
        if (StatusConstants.REJECTED_STATUS.equals(table.getStatus()) || StatusConstants.APPLY_ABANDON_STATUS.equals(table.getStatus())) {
            CustomLoginConditionDto customLoginDemoConditionDto = conditionDemo(entity);
            //这个账号条件都满足 则吧账号关闭 设置为不可操作状态
            if (customLoginDemoConditionDto != null && customLoginDemoConditionDto.getCustomLoginCondition() == 1 && customLoginDemoConditionDto.getTrainCondition() == 1) {
                table.setStatus(StatusConstants.NOT_OPERATION_STATUS);
                table.setValid(0);
                table.setLoginStatus(StatusConstants.MANAGER_PENDING_STATUS);
                repository.save(table);

                List<Integer> sts = new ArrayList<>();
                sts.add(StatusConstants.PASSED_STATUS);
                sts.add(StatusConstants.APPLY_STATUS);
                sts.add(StatusConstants.APPLY_PENDING_STATUS);
                List<CustomLoginDemoTable> tables =
                        repository.findAllByCustomIdAndStatusInAndLoginNot(table.getCustomId(), sts, entity.getLogin());
                if (tables != null && tables.size() > 0) {
                    for (CustomLoginDemoTable customLoginDemoTable : tables) {
                        customLoginDemoTable.setValid(0);
                        customLoginDemoTable.setStatus(StatusConstants.NOT_OPERATION_STATUS);
                        table.setLoginStatus(StatusConstants.MANAGER_PENDING_STATUS);
                    }
                    repository.save(tables);
                }

                customInfoService.updatePosition(table.getCustomId(), CustomConstants.POSITION1);
                BaseResultDto baseResultDto = webVideoFeignService.delete();
                if (baseResultDto == null) {
                    throw ServiceException.exception(Constants.SYSTEM_ERROR);
                }
                if (baseResultDto.getCode() != 200) {
                    throw ServiceException.exception(baseResultDto.getMsg());
                }
            } else {
                throw ServiceException.exception(Constants.NOT_PERMIT);
            }
        } else {
            throw ServiceException.exception(Constants.NOT_PERMIT);
        }
    }

    @Override
    public ResultWithPagerDto<CustomLoginDemoDto> searchPageList(CustomLoginDemoSearchListEntity entity) throws ServiceException {
        Integer count = mapper.countList(entity);
        PageDto pageDto = PageDto.format(entity, count);
        if (count == null || count <= 0) {
            return ResultWithPagerDto.success(pageDto);
        }
        List<CustomLoginDemoDto> dtos = getDtos(entity);
        if (dtos == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }

        return ResultWithPagerDto.success(pageDto, dtos);
    }

    @Override
    public CustomLoginDemoTable getByLogin(Long login) throws ServiceException {
        CustomLoginDemoTable table = repository.getFirstByLogin(login);
        if (table == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }
        return table;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAgentId(CustomInfoUpdateAgentEntity entity) throws ServiceException {
        List<CustomLoginDemoTable> tables = repository.findAllByCustomId(entity.getId());
        if (tables != null && tables.size() > 0) {
            for (CustomLoginDemoTable table : tables) {
                table.setAgentId(entity.getAgentId());
                table.setModifyIp(entity.getModifyIp());
                table.setModifyTime(entity.getModifyTime());
                table.setModifyUser(entity.getModifyUser());
            }
            repository.save(tables);
        }
    }


    private List<CustomLoginDemoDto> getDtos(CustomLoginDemoSearchListEntity entity) throws ServiceException {
        List<CustomLoginDemoView> views = mapper.pageList(entity);

        if (views == null || views.size() <= 0) {
            return null;
        }
        List<CustomLoginDemoDto> dtos = new ArrayList<>(views.size());
        for (CustomLoginDemoView view : views) {
            CustomLoginDemoDto dto = transform(view);
            if (dto.getEquity() != null) {
                dto.setEquity(dto.getEquity().setScale(2, BigDecimal.ROUND_HALF_UP));
            }
            if (dto.getBalance() != null) {
                dto.setBalance(dto.getBalance().setScale(2,BigDecimal.ROUND_HALF_UP));
            }
            if (dto.getCredit() != null) {
                dto.setCredit(dto.getCredit().setScale(2,BigDecimal.ROUND_HALF_UP));
            }
            if (dto.getFloating() != null) {
                dto.setFloating(dto.getFloating().setScale(2,BigDecimal.ROUND_HALF_UP));
            }
            dtos.add(dto);
        }

        return dtos;
    }

    private CustomLoginDemoDto transform(CustomLoginDemoView table) {
        CustomLoginDemoDto dto = new CustomLoginDemoDto();
        BeanUtils.copyProperties(table, dto);

        return dto;
    }
}
