package com.crm.manager.service.impl;

import com.crm.manager.dao.mapper.AccountLeverageChangeMapper;
import com.crm.manager.dao.repository.AccountLeverageChangeRepository;
import com.crm.manager.dao.repository.CustomInfoRepository;
import com.crm.manager.service.AccountLeverageChangeService;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.constant.EmailSendEnum;
import com.crm.rely.backend.core.constant.MapConstants;
import com.crm.rely.backend.core.constant.SystemEmailCodeConstants;
import com.crm.rely.backend.core.dto.account.leverage.AccountLeverageSearchListDto;
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.account.leverage.AccountLeverageChangeApproveEntity;
import com.crm.rely.backend.core.entity.account.leverage.AccountLeverageChangeDeleteEntity;
import com.crm.rely.backend.core.entity.account.leverage.AccountLeverageChangeSearchEntity;
import com.crm.rely.backend.core.entity.system.email.SysEmailSendEntity;
import com.crm.rely.backend.core.entity.web.notice.record.WebNoticeRecordAndEmailMqEntity;
import com.crm.rely.backend.core.pojo.table.AccountLeverageChangeTable;
import com.crm.rely.backend.core.pojo.table.CustomInfoTable;
import com.crm.rely.backend.core.pojo.view.AccountLeverageChangeView;
import com.crm.rely.backend.exception.ServiceException;
import com.crm.rely.backend.service.EmailService;
import com.crm.rely.backend.service.MqSendService;
import com.crm.rely.backend.util.CountryUtil;
import com.crm.rely.backend.util.CustomInfoUtil;
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @description:
 * @author: houn
 * @create: 2020-07-07 14:45
 **/
@Service
public class AccountLeverageChangeServiceImpl implements AccountLeverageChangeService {


    @Autowired
    private AccountLeverageChangeRepository accountLeverageChangeRepository;

    @Autowired
    private AccountLeverageChangeMapper accountLeverageChangeMapper;

    @Autowired
    private CustomInfoRepository customInfoRepository;

    @Autowired
    private EmailService emailService;

    @Autowired
    private MqSendService mqSendService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void approve(AccountLeverageChangeApproveEntity entity) throws ServiceException {
        AccountLeverageChangeTable table = accountLeverageChangeRepository.findFirstById(entity.getId());
        if (table == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        if (!Constants.APPLY_STATUS.equals(table.getStatus())) {
            throw ServiceException.exception(Constants.CANNOT_APPROVE);
        }

        BeanUtils.copyProperties(entity, table);

        accountLeverageChangeRepository.save(table);
        if (Constants.PASSED_STATUS.equals(table.getStatus()) && Constants.MANAGER_COMPLETED_STATUS.equals(table.getLeverageStatus())) {
            SysEmailSendEntity sysEmailSendEntity = createAccountLeverageUpdateCompleteSysEmailEntity(table);
            emailService.sendEmail(sysEmailSendEntity);

            WebNoticeRecordAndEmailMqEntity mqEntity = new WebNoticeRecordAndEmailMqEntity(sysEmailSendEntity,
                    table.getCId());
            mqSendService.send(Constants.WEB_NOTICE_PUT_RECORD, mqEntity);
        }
    }

    private SysEmailSendEntity createAccountLeverageUpdateCompleteSysEmailEntity(AccountLeverageChangeTable table) throws ServiceException {

        CustomInfoTable customInfoTable = customInfoRepository.getFirstByCId(table.getCId());
        if (customInfoTable == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }
        SysEmailSendEntity sysEmailSendEntity = new SysEmailSendEntity();
        Map<String, String> map = new HashMap<>(3);

        String name = CustomInfoUtil.getName(customInfoTable);

        map.put(MapConstants.NAME, name);
        map.put(MapConstants.LOGIN, String.valueOf(table.getLogin()));
        map.put(MapConstants.PLATFORM, table.getPlatform());
        map.put(MapConstants.C_ID, String.valueOf(customInfoTable.getCId()));
        map.put(MapConstants.LEVERAGE, String.valueOf(table.getNewLeverage()));
        map.put(MapConstants.LEVERAGE_OLD, String.valueOf(table.getOldLeverage()));
        map.put(MapConstants.DATE_TIME, DateUtil.formatTime());

        sysEmailSendEntity.setAddIp("127.0.0.1");
        sysEmailSendEntity.setAddTime(new Date());

        sysEmailSendEntity.setUsers(customInfoTable.getEmail());
        sysEmailSendEntity.setEmailSendEnum(EmailSendEnum.ACCOUNT_UPDATE_LEVERAGE_COMPLETE);
        String templateName;
        String lang = customInfoTable.getLang();

        if (Strings.isNullOrEmpty(lang)) {
            lang = customInfoTable.getCountry();
        }
        if (CountryUtil.isCN(customInfoTable.getCountry())) {
            templateName = SystemEmailCodeConstants.ACCOUNT_LEVERAGE_UPDATE_COMPLETE_SEND_CN;
        } else {
            templateName = SystemEmailCodeConstants.ACCOUNT_LEVERAGE_UPDATE_COMPLETE_SEND_EN;
        }
        sysEmailSendEntity.setTemplateName(templateName);

        sysEmailSendEntity.setMap(map);

        return sysEmailSendEntity;
    }
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public void approve(AccountLeverageChangeApproveManagerEntity entity) throws ServiceException {
//        AccountLeverageChangeTable accountLeverageChangeTable = accountLeverageChangeRepository.findFirstById(entity.getId());
//        if (accountLeverageChangeTable == null) {
//            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
//        }
//        if (!Constants.PASSED_STATUS.equals(accountLeverageChangeTable.getStatus()) || !Constants.MANAGER_PROCESSING_STATUS.equals(accountLeverageChangeTable.getLeverageStatus())) {
//            throw ServiceException.exception(Constants.CANNOT_APPROVE);
//        }
//
//        BeanUtils.copyProperties(entity, accountLeverageChangeTable);
//
//        accountLeverageChangeRepository.save(accountLeverageChangeTable);
//    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(AccountLeverageChangeDeleteEntity entity) throws ServiceException {
        List<AccountLeverageChangeTable> accountLeverageChangeTables = accountLeverageChangeRepository.findAllByIdIn(entity.getIds());
        if (accountLeverageChangeTables == null || accountLeverageChangeTables.size() <= 0) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }

        accountLeverageChangeRepository.delete(accountLeverageChangeTables);
    }

    @Override
    public ResultWithPagerDto<AccountLeverageSearchListDto> searchList(AccountLeverageChangeSearchEntity entity) throws ServiceException {
        Integer count = accountLeverageChangeMapper.countList(entity);
        PageDto pageDto = PageDto.format(entity, count);
        if (count == null || count <= 0) {
            return ResultWithPagerDto.success(pageDto);
        }
        List<AccountLeverageChangeView> accountLeverageChangeViews = accountLeverageChangeMapper.pageList(entity);

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

            throw new ServiceException(Constants.SYSTEM_ERROR);
        }
        List<AccountLeverageSearchListDto> accountLeverageDtos = new ArrayList<>(accountLeverageChangeViews.size());

        for (AccountLeverageChangeView accountLeverageChangeView : accountLeverageChangeViews) {
            AccountLeverageSearchListDto transform = transform(accountLeverageChangeView);
            accountLeverageDtos.add(transform);
        }

        return ResultWithPagerDto.success(pageDto, accountLeverageDtos);
    }

    @Override
    public AccountLeverageSearchListDto searchSingle(Long id) throws ServiceException {
        AccountLeverageChangeView one = accountLeverageChangeMapper.getOne(id);
        if (one == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        return transform(one);
    }

    private AccountLeverageSearchListDto transform(AccountLeverageChangeView accountLeverageChangeView) {
        AccountLeverageSearchListDto accountLeverageDto = new AccountLeverageSearchListDto();
        BeanUtils.copyProperties(accountLeverageChangeView, accountLeverageDto);
        return accountLeverageDto;
    }
}
