package com.crm.manager.service.impl;

import com.crm.manager.dao.repository.AccountTypeLeverageRepository;
import com.crm.manager.dao.repository.AccountTypePointRepository;
import com.crm.manager.dao.repository.AccountTypeRepository;
import com.crm.manager.service.AccountTypeService;
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.type.AccountTypeListDto;
import com.crm.rely.backend.core.dto.base.BaseResultDto;
import com.crm.rely.backend.core.entity.account.type.AccountTypeListUpdateEntity;
import com.crm.rely.backend.core.entity.system.config.SendUpdateEmailCodeEntity;
import com.crm.rely.backend.core.entity.system.email.SysEmailSendEntity;
import com.crm.rely.backend.core.pojo.table.AccountTypeLeverageTable;
import com.crm.rely.backend.core.pojo.table.AccountTypePointTable;
import com.crm.rely.backend.core.pojo.table.AccountTypeTable;
import com.crm.rely.backend.exception.ServiceException;
import com.crm.rely.backend.service.EmailService;
import com.crm.rely.backend.util.DateUtil;
import com.crm.rely.backend.util.GetRandom;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by max on 2020/8/18.
 */
@Service
public class AccountTypeServiceImpl implements AccountTypeService {


    @Autowired
    private AccountTypeRepository accountTypeRepository;
    @Autowired
    private AccountTypeLeverageRepository accountTypeLeverageRepository;
    @Autowired
    private AccountTypePointRepository accountTypePointRepository;

    @Autowired
    private EmailService emailService;

    @Override
    public List<AccountTypeListDto> getList() throws Exception {

        /*
            账户类型
         */
        List<AccountTypeTable> accountTypeTables = accountTypeRepository.findAll();
        if (CollectionUtils.isEmpty(accountTypeTables)) {
            return null;
        }
        /*
            杠杆比例
         */
        List<AccountTypeLeverageTable> leverageTables = accountTypeLeverageRepository.findAll();
        /*
            外佣
         */
        List<AccountTypePointTable> pointTables = accountTypePointRepository.findAll();


        List<AccountTypeListDto> dtos = Lists.newArrayList();
        accountTypeTables.forEach((item) -> {
            AccountTypeListDto dto = new AccountTypeListDto();
            BeanUtils.copyProperties(item, dto);
            dto.setLeverages(Lists.newArrayList());
            leverageTables.forEach((leverage) -> {
                if (leverage.getType() == item.getId()) {
                    dto.getLeverages().add(leverage.getLeverage());
                }
            });
            dto.setPoints(Lists.newArrayList());
            pointTables.forEach((point) -> {
                if (point.getType() == item.getId()) {
                    dto.getPoints().add(point.getPoint());
                }
            });
            dtos.add(dto);
        });

        return dtos;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResultDto<Object> updateList(List<AccountTypeListUpdateEntity> entities) throws Exception {

        /*
            解析请求
         */
        List<AccountTypeTable> typeTables = Lists.newArrayList();
        List<AccountTypeLeverageTable> leverageTables = Lists.newArrayList();
        List<AccountTypePointTable> pointTables = Lists.newArrayList();

        List<AccountTypePointTable> typePointTables = accountTypePointRepository.findAll();

        entities.forEach((entity -> {
            if (entity.getDefaultLoginValid() != null && entity.getDefaultLoginValid().equals(1)) {
                entity.setQuotaAmount(BigDecimal.ZERO);
            }
            AccountTypeTable typeTable = new AccountTypeTable();
            BeanUtils.copyProperties(entity, typeTable);
            entity.getLeverages().forEach((leverage) -> {
                AccountTypeLeverageTable leverageTable = new AccountTypeLeverageTable();
                leverageTable.setLeverage(leverage);
                leverageTable.setType(entity.getId());
                leverageTables.add(leverageTable);
            });
            entity.getPoints().forEach((point) -> {
                AccountTypePointTable pointTable = new AccountTypePointTable();
                pointTable.setPoint(point);
                pointTable.setType(entity.getId());

                for (AccountTypePointTable typePointTable : typePointTables) {
                    if (pointTable.getType().equals(typePointTable.getType()) && pointTable.getPoint().equals(typePointTable.getPoint())) {
                        pointTable.setForMam(typePointTable.getForMam());
                        break;
                    }
                }

                pointTables.add(pointTable);
            });

            typeTables.add(typeTable);
        }));

        if (!CollectionUtils.isEmpty(typeTables)) {
            accountTypeRepository.save(typeTables);
        }

        if (!CollectionUtils.isEmpty(leverageTables)) {
            accountTypeLeverageRepository.deleteAll();
            accountTypeLeverageRepository.save(leverageTables);
        }

        if (!CollectionUtils.isEmpty(pointTables)) {
            accountTypePointRepository.deleteAll();
            accountTypePointRepository.save(pointTables);
        }

        return BaseResultDto.success();
    }

    @Override
    public void sendEmailCode(SendUpdateEmailCodeEntity entity) throws ServiceException {

        //构建实体
        SysEmailSendEntity sysEmailSendEntity = createSendEmailCodeEntity(entity);

        //发送收据
        emailService.sendCode(sysEmailSendEntity, sysEmailSendEntity.getMap().get(MapConstants.CODE));
    }

    private SysEmailSendEntity createSendEmailCodeEntity(SendUpdateEmailCodeEntity entity) {
        SysEmailSendEntity sysEmailSendEntity = new SysEmailSendEntity();

        Map<String, String> map = new HashMap<>(2);
        String code = GetRandom.getRandom(6);
        map.put(MapConstants.CODE, code);
        Date time = DateUtil.operationMinute(new Date(), Constants.EMAIL_VALIDATECODE_TIME);
        map.put(MapConstants.EXPIRE_TIME, DateUtil.formatTime(time));
        map.put(MapConstants.DATE_TIME, DateUtil.formatTime());

        sysEmailSendEntity.setAddIp(entity.getIp());
        sysEmailSendEntity.setAddTime(entity.getTime());

        sysEmailSendEntity.setUsers(entity.getEmail());
        sysEmailSendEntity.setEmailSendEnum(EmailSendEnum.UPDATE_CONFIG_EMAIL_CODE);

        sysEmailSendEntity.setTemplateName(SystemEmailCodeConstants.CONFIG_UPDATE_EMAIL_CODE_SEND);

        sysEmailSendEntity.setMap(map);

        return sysEmailSendEntity;
    }
}
