package com.crm.manager.service.cooperate;

import com.crm.manager.dao.mapper.TwCooperateDailyMapper;
import com.crm.manager.dto.export.TwCooperateExportDto;
import com.crm.manager.service.TwCooperateDailyService;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.dto.base.BaseReportResultDto;
import com.crm.rely.backend.core.dto.base.BaseResultWithPagerDto;
import com.crm.rely.backend.core.dto.base.PageDto;
import com.crm.rely.backend.core.dto.cooperate.tw.TwCooperateDto;
import com.crm.rely.backend.core.dto.cooperate.tw.TwCooperateSumDto;
import com.crm.rely.backend.core.entity.cooperate.tw.TwCooperateListEntity;
import com.crm.rely.backend.core.entity.cooperate.tw.TwCooperateUpdateEntity;
import com.crm.rely.backend.core.pojo.table.TwCooperateDailyTable;
import com.crm.rely.backend.core.pojo.view.TwCooperateDailyView;
import com.crm.rely.backend.exception.ServiceException;
import com.crm.rely.backend.util.FloatFormat;
import com.crm.rely.backend.util.FormatPage;
import org.apache.commons.compress.utils.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class TwCooperateDailyServiceImpl implements TwCooperateDailyService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private TwCooperateDailyMapper twCooperateDailyMapper;

    @Override
    public BaseReportResultDto<List<TwCooperateDto>, TwCooperateSumDto> twSearchList(TwCooperateListEntity entity) throws ServiceException {

        try {
            Integer count = twCooperateDailyMapper.countSearch(entity);
            if (count == null || count == 0) {
                return new BaseReportResultDto<>(Constants.SUCCESS_CODE, "");
            }
            PageDto pageDto = FormatPage.format(entity.getPage(), count);

            List<TwCooperateDto> dtos = Optional.ofNullable(twCooperateDailyMapper.listSearch(entity)).orElse(Lists.newArrayList()).stream().map(this::convertViewToDto).collect(Collectors.toList());


            TwCooperateDailyView sumView = twCooperateDailyMapper.sumSearch(entity);
            TwCooperateSumDto sumDto = new TwCooperateSumDto();
            BeanUtils.copyProperties(sumView, sumDto);

            return new BaseReportResultDto<>(dtos, sumDto, pageDto);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceException(e.getMessage());
        }
    }

    @Override
    public TwCooperateDto twSearchSingle(Long id) throws ServiceException {
        try {
            TwCooperateDailyView view = twCooperateDailyMapper.getViewById(id);
            if (view != null) {
                return convertViewToDto(view);
            } else {
                return null;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceException(e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateById(TwCooperateUpdateEntity entity) throws ServiceException {
        try {
            //获取源数据
            TwCooperateDailyTable table = twCooperateDailyMapper.getOne(entity.getId());
            if (table == null) {
                throw new ServiceException(Constants.INFO_NOT_FOUND);
            }
            BeanUtils.copyProperties(entity, table);
            calculateValue(table);

            twCooperateDailyMapper.updateById(table);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceException(e.getMessage());
        }
    }

    @Override
    public List<TwCooperateExportDto> getExportDto(TwCooperateListEntity entity) throws ServiceException {
        try {
            entity.setPage(null);
            return Optional.ofNullable(twCooperateDailyMapper.listSearch(entity)).orElse(Lists.newArrayList()).stream().map(this::convertViewToExportDto).collect(Collectors.toList());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceException(e.getMessage());
        }
    }

    private void calculateValue(TwCooperateDailyTable table) {
        table.setSettlementPl((nz(table.getTotalProfit()) - nz(table.getNegativeProfit())) * -1);
        table.setSumRebate(nz(table.getRebate()) + nz(table.getCommission()) + nz(table.getHidden()));
        table.setDba(nz(table.getWithdrawalFee()) + nz(table.getDepositFee()) + nz(table.getPtc()) + nz(table.getDepositComment()) + nz(table.getSumRebate()));
        table.setAssBase(table.getSettlementPl() - table.getDba());
        table.setFinalProfit(table.getAssRatio() * table.getAssBase());
    }

    private TwCooperateDto convertViewToDto(TwCooperateDailyView view) {
        try {
            TwCooperateDto dto = new TwCooperateDto();
            BeanUtils.copyProperties(view, dto);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (dto.getSummaryType() == 1) {
                dto.setSummaryDate(sdf.format(view.getSummaryDate()));
            } else if (dto.getSummaryType() == 2) {
                dto.setSummaryDate(sdf.format(view.getStartDate()) + "~" + sdf.format(view.getEndDate()));
            }

            return dto;
        } catch (BeansException e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }

    private TwCooperateExportDto convertViewToExportDto(TwCooperateDailyView view) {
        try {
            TwCooperateExportDto dto = new TwCooperateExportDto();
            BeanUtils.copyProperties(view, dto);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            dto.setAssRatio(FloatFormat.formatToPercent(view.getAssBase() * 100F));
            if (view.getSummaryType() == 1) {
                dto.setSummaryDate(sdf.format(view.getSummaryDate()));
                dto.setSummaryType("日");
            } else if (view.getSummaryType() == 2) {
                dto.setSummaryDate(sdf.format(view.getStartDate()) + "~" + sdf.format(view.getEndDate()));
                dto.setSummaryType("周");
            }

            return dto;
        } catch (BeansException e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }

    private float nz(Float value) {
        return Optional.ofNullable(value).orElse(0f);
    }


}
