package com.crm.manager.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.crm.manager.dao.mapper.CustomLoginCompletionMapper;
import com.crm.manager.dao.mapper.CustomLoginDao;
import com.crm.manager.dao.repository.CustomLoginCompletionRepository;
import com.crm.manager.service.CustomLoginCompletionService;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.constant.PayConstant;
import com.crm.rely.backend.core.dto.base.PageDto;
import com.crm.rely.backend.core.dto.base.ResultWithPagerDto;
import com.crm.rely.backend.core.dto.custom.login.completion.CustomLoginCompletionListDto;
import com.crm.rely.backend.core.entity.base.SingleLongEntity;
import com.crm.rely.backend.core.entity.custom.login.completion.CustomLoginCompletionAddEntity;
import com.crm.rely.backend.core.entity.custom.login.completion.CustomLoginCompletionDeleteEntitys;
import com.crm.rely.backend.core.entity.custom.login.completion.CustomLoginCompletionSearchEntity;
import com.crm.rely.backend.core.entity.custom.login.completion.CustomLoginCompletionUpdateEntity;
import com.crm.rely.backend.core.entity.finance.balance.FinanceBalanceAddEntity;
import com.crm.rely.backend.core.pojo.table.CustomLoginCompletionTable;
import com.crm.rely.backend.core.pojo.table.FinanceBalanceTable;
import com.crm.rely.backend.core.pojo.view.AccountBalanceView;
import com.crm.rely.backend.exception.ServiceException;
import com.crm.rely.backend.service.MqSendService;
import com.crm.rely.backend.util.GetRandom;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Slf4j
@Service
public class CustomLoginCompletionServiceImpl implements CustomLoginCompletionService {

    @Autowired
    private CustomLoginCompletionRepository repository;
    @Autowired
    private CustomLoginCompletionMapper mapper;
    @Autowired
    private MqSendService mqSendService;
    @Autowired
    private CustomLoginDao customLoginDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(CustomLoginCompletionAddEntity entity) throws ServiceException {
        CustomLoginCompletionTable table = new CustomLoginCompletionTable();
        BeanUtils.copyProperties(entity, table);
        repository.save(table);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(CustomLoginCompletionDeleteEntitys entity) throws ServiceException {
        List<CustomLoginCompletionTable> tables = repository.findAllByIdIn(entity.getIds());
        if (tables == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        repository.delete(tables);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(CustomLoginCompletionUpdateEntity entity) throws ServiceException {
        CustomLoginCompletionTable table = repository.findFirstById(entity.getId());
        if (table == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        BeanUtils.copyProperties(entity, table);
        repository.save(table);
    }

    @Override
    public ResultWithPagerDto<CustomLoginCompletionListDto> searchPageList(CustomLoginCompletionSearchEntity entity) throws ServiceException {
        Integer count = mapper.countList(entity);
        PageDto pageDto = PageDto.format(entity, count);
        if (count == null || count <= 0) {
            return ResultWithPagerDto.success(pageDto);
        }
        List<CustomLoginCompletionTable> tables = mapper.pageList(entity);
        if (tables == null || tables.size() <= 0) {
            throw new ServiceException(Constants.SYSTEM_ERROR);
        }
        List<CustomLoginCompletionListDto> dots = new ArrayList<>(tables.size());

        for (CustomLoginCompletionTable table : tables) {
            CustomLoginCompletionListDto dto = transformSearchListDto(table);
            dots.add(dto);
        }

        return ResultWithPagerDto.success(pageDto, dots);
    }

    @Override
    public CustomLoginCompletionListDto searchSingle(SingleLongEntity entity) throws ServiceException {
        CustomLoginCompletionTable table = repository.getFirstById(entity.getId());
        if (table == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }

        return transformSearchListDto(table);
    }

    @Override
    public void adds(List<CustomLoginCompletionAddEntity> addEntities) throws ServiceException {
        Map<String, Long> map = new HashMap<>();

        List<CustomLoginCompletionTable> tables = new ArrayList<>();
        for (CustomLoginCompletionAddEntity entity : addEntities) {
            map.put(entity.getLogin() + "-" + entity.getPlatform(), entity.getLogin());

        }
        for (String key : map.keySet()) {
            CustomLoginCompletionTable table = new CustomLoginCompletionTable();
            table.setLogin(map.get(key));
            table.setPlatform(key.split("-")[1]);
            table.setStatus(1);
            table.setAddTime(new Date());
            tables.add(table);
        }

        repository.save(tables);

        mqSendService.send(Constants.CUSTOM_LOGIN_COMPLETION, tables);
    }

    @JmsListener(destination = Constants.CUSTOM_LOGIN_COMPLETION)
    @Transactional(rollbackFor = Exception.class)
    public void customLoginCompletion(String content) throws Exception {
        log.info(String.format("CUSTOM_LOGIN_COMPLETION,content:%s", content));
        List<CustomLoginCompletionTable> entitys = JSON.parseArray(content, CustomLoginCompletionTable.class);

        if (entitys == null) {
            log.error("CUSTOM_LOGIN_COMPLETION, entitys is null");
            return;
        }

        for (CustomLoginCompletionTable table : entitys) {
            CustomLoginCompletionTable completionTable =
                    repository.findFirstByLoginAndPlatformAndStatus(table.getLogin(), table.getPlatform(), 1);

            AccountBalanceView amountView = customLoginDao.getCustomLoginByLoginAndPlatform(table.getLogin(),
                    table.getPlatform());
            if (amountView == null) {
                completionTable.setStatus(3);
                completionTable.setBalance(BigDecimal.ZERO);
                completionTable.setAmount(BigDecimal.ZERO);
                repository.save(completionTable);
                continue;
            }

            completionTable.setSerial(GetRandom.getOrderNo(PayConstant.COMPLETE_HEAD));
            completionTable.setStatus(2);
            completionTable.setBalance(new BigDecimal(amountView.getBalance()));
            completionTable.setAmount(new BigDecimal(0).subtract(new BigDecimal(amountView.getBalance())));
            repository.save(completionTable);

            FinanceBalanceAddEntity financeBalanceAddEntity = new FinanceBalanceAddEntity();
            financeBalanceAddEntity.setAmount(completionTable.getAmount());
            financeBalanceAddEntity.setSerial(completionTable.getSerial());
            financeBalanceAddEntity.setLogin(completionTable.getLogin());
            financeBalanceAddEntity.setCallbackMq(Constants.CUSTOM_LOGIN_COMPLETION_CALLBACK);
            mqSendService.send(Constants.FINANCE_BALANCE_INFO, JSONObject.toJSONString(financeBalanceAddEntity));
        }
    }


    @JmsListener(destination = Constants.CUSTOM_LOGIN_COMPLETION_CALLBACK)
    @Transactional(rollbackFor = Exception.class)
    public void customLoginCompletionCallback(String content) throws Exception {
        log.info(String.format("CUSTOM_LOGIN_COMPLETION_CALLBACK,content:%s", content));
        FinanceBalanceTable entity = JSON.parseObject(content, FinanceBalanceTable.class);

        if (entity == null || StringUtils.isEmpty(entity.getSerial()) || entity.getTradeStatus() == null) {
            log.error("CUSTOM_LOGIN_COMPLETION_CALLBACK,entity is null");
            return;
        }
        CustomLoginCompletionTable completionTable = repository.findFirstBySerial(entity.getSerial());
        if (completionTable == null) {
            log.error("CUSTOM_LOGIN_COMPLETION_CALLBACK,table is null");
            return;
        }
        if (2 == completionTable.getStatus() && 2 == entity.getTradeStatus()) {
            completionTable.setStatus(3);
            repository.save(completionTable);
        }
    }

    private CustomLoginCompletionListDto transformSearchListDto(CustomLoginCompletionTable table) {
        CustomLoginCompletionListDto dto = new CustomLoginCompletionListDto();
        BeanUtils.copyProperties(table, dto);
        return dto;
    }

}
