package com.crm.custom.service.impl;

import com.crm.custom.dao.mapper.CustomLoginFirmOfferMapper;
import com.crm.custom.dao.repository.CustomLoginDemoRepository;
import com.crm.custom.dao.repository.CustomLoginFirmOfferRepository;
import com.crm.custom.service.*;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.constant.MapConstants;
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.entity.system.email.SysEmailSendEntity;
import com.crm.rely.backend.core.pojo.table.SysConfigTable;
import com.crm.rely.backend.core.exception.ServiceException;
import com.crm.rely.backend.model.constant.ConfigConstants;
import com.crm.rely.backend.model.constant.CustomConstants;
import com.crm.rely.backend.model.constant.EmailTemplateConstants;
import com.crm.rely.backend.model.dto.custom.login.CustomLoginConditionDto;
import com.crm.rely.backend.model.dto.custom.login.CustomLoginFirmOfferDto;
import com.crm.rely.backend.model.dto.custom.login.CustomLoginFirmOfferRollDto;
import com.crm.rely.backend.model.entity.account.apply.asset.management.AccountApplyAssetManagementAddEntity;
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.firm.offer.CustomLoginFirmOfferApproveEntity;
import com.crm.rely.backend.model.entity.custom.login.firm.offer.CustomLoginFirmOfferSearchListEntity;
import com.crm.rely.backend.model.entity.custom.login.firm.offer.CustomLoginFirmOfferUpdateCheckByLoginEntity;
import com.crm.rely.backend.model.pojo.table.CustomLoginDemoTable;
import com.crm.rely.backend.model.pojo.table.CustomLoginFirmOfferTable;
import com.crm.rely.backend.model.pojo.view.CustomLoginFirmOfferRollView;
import com.crm.rely.backend.model.pojo.view.CustomLoginFirmOfferView;
import com.crm.rely.backend.service.EmailService;
import com.crm.rely.backend.util.DateUtil;
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.*;

@Service
public class CustomLoginFirmOfferServiceImpl implements CustomLoginFirmOfferService {

    @Autowired
    private CustomLoginFirmOfferRepository repository;

    @Autowired
    private CustomLoginFirmOfferMapper mapper;

    @Autowired
    private AccountApplyAssetManagementService accountApplyAssetManagementService;

    @Autowired
    private AccountApplyFirmOfferService accountApplyFirmOfferService;

    @Autowired
    private CustomLoginService customLoginService;
    @Autowired
    private FinanceTrainFeignService financeTrainFeignService;

    @Autowired
    private WebVideoFeignService webVideoFeignService;

    @Autowired
    private EmailService emailService;

    @Autowired
    private SysConfigService sysConfigService;


    @Autowired
    private CustomInfoService customInfoService;

    @Autowired
    private CustomLoginDemoRepository customLoginDemoRepository;

    /**
     * 是否有在的账号或者成功的账号
     *
     * @param customId
     * @return
     * @throws ServiceException
     */
    @Override
    public boolean existFirmOfferStatus(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
    @Transactional(rollbackFor = Exception.class)
    public void update(Long login, Integer valid) throws ServiceException {
        CustomLoginFirmOfferTable table = repository.findFirstByLogin(login);
        if (table != null) {
            table.setValid(valid);
            table.setLoginStatus(StatusConstants.MANAGER_PENDING_STATUS);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void applyCheck(CustomLoginFirmOfferUpdateCheckByLoginEntity entity) throws ServiceException {
        CustomLoginFirmOfferTable 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);
        sendManager(table);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CustomLoginFirmOfferTable approve(CustomLoginFirmOfferApproveEntity entity) throws ServiceException {
        CustomLoginFirmOfferTable 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);

        //如果审核通过 注册资管账户
        if (StatusConstants.PASSED_STATUS.equals(table.getStatus())) {

            AccountApplyAssetManagementAddEntity accountApplyAssetManagementAddEntity =
                    new AccountApplyAssetManagementAddEntity();
            accountApplyAssetManagementAddEntity.setCustomId(table.getCustomId());
            accountApplyAssetManagementAddEntity.setAgentId(table.getAgentId());
            accountApplyAssetManagementAddEntity.setCId(table.getCId());
            accountApplyAssetManagementAddEntity.setBalance(entity.getBalance());

            accountApplyAssetManagementService.addAccountApply(accountApplyAssetManagementAddEntity);
        }


        return table;
    }

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

        return ResultWithPagerDto.success(pageDto, dtos);
    }

    @Override
    public CustomLoginConditionDto conditionFirmOffer(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 studyFirmOffer(CustomLoginCheckByLoginEntity entity) throws Exception {
        CustomLoginFirmOfferTable 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 = conditionFirmOffer(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<CustomLoginDemoTable> tables =
                        customLoginDemoRepository.findAllByCustomIdAndStatus(table.getCustomId(),
                                StatusConstants.PASSED_STATUS);
                if (tables != null && tables.size() > 0) {
                    for (CustomLoginDemoTable customLoginDemoTable : tables) {
                        customLoginDemoTable.setStatus(StatusConstants.NOT_OPERATION_STATUS);
                    }
                    customLoginDemoRepository.save(tables);
                }

//
//                AccountApplyFirmOfferAddEntity accountApplyFirmOfferAddEntity = new AccountApplyFirmOfferAddEntity();
//                accountApplyFirmOfferAddEntity.setCustomId(customLoginFirmOfferTable.getCustomId());
//                accountApplyFirmOfferAddEntity.setAgentId(customLoginFirmOfferTable.getAgentId());
//                accountApplyFirmOfferAddEntity.setCId(customLoginFirmOfferTable.getCId());
//                accountApplyFirmOfferService.addAccountApply(accountApplyFirmOfferAddEntity);
                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 CustomLoginFirmOfferTable getByLogin(Long login) throws ServiceException {
        CustomLoginFirmOfferTable 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<CustomLoginFirmOfferTable> tables = repository.findAllByCustomId(entity.getId());
        if (tables != null && tables.size() > 0) {
            for (CustomLoginFirmOfferTable table : tables) {
                table.setAgentId(entity.getAgentId());
                table.setModifyIp(entity.getModifyIp());
                table.setModifyTime(entity.getModifyTime());
                table.setModifyUser(entity.getModifyUser());
            }
            repository.save(tables);
        }
    }

    @Override
    public List<CustomLoginFirmOfferRollDto> rollList() throws ServiceException {
        List<CustomLoginFirmOfferRollView> views = mapper.rollList();

        if (views == null || views.size() <= 0) {
            return null;
        }
        List<CustomLoginFirmOfferRollDto> dtos = new ArrayList<>(views.size());
        for (CustomLoginFirmOfferRollView view : views) {
            CustomLoginFirmOfferRollDto dto = new CustomLoginFirmOfferRollDto();
            BeanUtils.copyProperties(view, dto);
            dtos.add(dto);
        }

        return dtos;
    }

    private void sendManager(CustomLoginFirmOfferTable table) throws ServiceException {
        if (!StatusConstants.APPLY_STATUS.equals(table.getStatus())) {
            return;
        }
        SysConfigTable sysConfigTable = sysConfigService.getByCode(ConfigConstants.FIRM_OFFER_COMPLETE_MANAGER_EMAIL);
        if (sysConfigTable == null) {
            throw new ServiceException(Constants.SYSTEM_ERROR);
        }
        String users = sysConfigTable.getValue();

        if (users == null) {
            throw new ServiceException(Constants.SYSTEM_ERROR);
        }
        //构建map 用于后面邮件模版替换
        Map<String, String> map = new HashMap<>(10);

        map.put(MapConstants.LOGIN, table.getLogin() + "");
        map.put(MapConstants.APPLY_TIME, DateUtil.formatTime(new Date()));
        map.put(MapConstants.DATE_TIME, DateUtil.formatTime(new Date()));
        map.put(MapConstants.LOGIN_TYPE, "实盘");

        SysEmailSendEntity sysEmailSendEntity = new SysEmailSendEntity();
        sysEmailSendEntity.setSubject("CWG DEPOSIT");
        sysEmailSendEntity.setMap(map);
        sysEmailSendEntity.setTemplateName(EmailTemplateConstants.CHECK_COMPLETE_EMAIL);
        sysEmailSendEntity.setUsers(users);
        try {
            emailService.sendEmail(sysEmailSendEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private List<CustomLoginFirmOfferDto> getDtos(CustomLoginFirmOfferSearchListEntity entity) throws ServiceException {
        List<CustomLoginFirmOfferView> views = mapper.pageList(entity);

        if (views == null || views.size() <= 0) {
            return null;
        }
        List<CustomLoginFirmOfferDto> dtos = new ArrayList<>(views.size());
        for (CustomLoginFirmOfferView view : views) {
            CustomLoginFirmOfferDto 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 CustomLoginFirmOfferDto transform(CustomLoginFirmOfferView table) {
        CustomLoginFirmOfferDto dto = new CustomLoginFirmOfferDto();
        BeanUtils.copyProperties(table, dto);

        return dto;
    }
}
