package com.crm.globex.service.impl;

import com.alibaba.fastjson.JSON;
import com.crm.globex.configuration.MangerErrorSendEmailComponent;
import com.crm.globex.dao.repository.CustomInfoRepository;
import com.crm.globex.dao.repository.CustomLoginFirmOfferRepository;
import com.crm.globex.service.CustomLoginFirmOfferService;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.constant.StatusConstants;
import com.crm.rely.backend.core.entity.manager.AccountUpdateToManagerEntity;
import com.crm.rely.backend.core.entity.manager.callback.AccountUpdateCallbackEntity;
import com.crm.rely.backend.core.exception.ServiceException;
import com.crm.rely.backend.model.entity.custom.login.firm.offer.CustomLoginFirmOfferAddEntity;
import com.crm.rely.backend.model.pojo.table.CustomInfoTable;
import com.crm.rely.backend.model.pojo.table.CustomLoginFirmOfferTable;
import com.crm.rely.backend.service.MqSendService;
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.Date;

/**
 * @description:
 * @author: houn
 * @create: 2020-07-31 23:03
 **/
@Service
public class CustomLoginFirmOfferServiceImpl implements CustomLoginFirmOfferService {
    @Autowired
    private MangerErrorSendEmailComponent toManagerErrorService;
    @Autowired
    private CustomLoginFirmOfferRepository customLoginFirmOfferRepository;

    @Autowired
    private CustomInfoRepository customInfoRepository;

    @Autowired
    private MqSendService mqSendService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(CustomLoginFirmOfferAddEntity entity) throws ServiceException {
        existLogin(entity);
        CustomLoginFirmOfferTable customLoginFirmOfferTable = new CustomLoginFirmOfferTable();
        BeanUtils.copyProperties(entity, customLoginFirmOfferTable);
        customLoginFirmOfferTable.setStatus(StatusConstants.APPLY_PENDING_STATUS);
        customLoginFirmOfferRepository.save(customLoginFirmOfferTable);
    }

    //
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public void update(CustomLoginFirmOfferUpdateLeverageByLoginEntity entity) throws ServiceException {
//
//        CustomLoginFirmOfferTable customLoginFirmOfferTable = customLoginFirmOfferRepository.findFirstByLogin(entity.getLogin());
//
//        if (customLoginFirmOfferTable == null) {
//            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
//        }
//        if (entity.getGroup() != null && !entity.getGroup().equals(customLoginFirmOfferTable.getGroupCode())) {
//            entity.setId(customLoginFirmOfferTable.getId());
//            BeanUtils.copyProperties(entity, customLoginFirmOfferTable);
//            customLoginFirmOfferRepository.save(customLoginFirmOfferTable);
//        }
//    }
//
    @Override
    public CustomLoginFirmOfferTable getByCustomIdAndLogin(Long customId, Long login) throws ServiceException {
        return customLoginFirmOfferRepository.getFirstByCustomIdAndLogin(customId, login);
    }

    @Override
    public boolean existByCustomIdAndLogin(Long customId, Long login) throws ServiceException {
        return customLoginFirmOfferRepository.existsByCustomIdAndLogin(customId, login);
    }

    /**
     * 定时器 开始自动调整Login
     *
     * @throws ServiceException
     */
    @Transactional(rollbackFor = Exception.class)
    public void scheduleAutomaticLogin() throws ServiceException {

        CustomLoginFirmOfferTable customLoginFirmOfferTable =
                customLoginFirmOfferRepository.findFirstByLoginStatus(StatusConstants.MANAGER_PENDING_STATUS);

        if (customLoginFirmOfferTable == null) {
            //拉取过期账号
            customLoginFirmOfferTable =
                    customLoginFirmOfferRepository.findFirstByLoginStatusAndValidAndExpirationTimeLessThanAndExpirationTimeIsNotNull(StatusConstants.MANAGER_COMPLETED_STATUS, 1, new Date());
            //设置
            if (customLoginFirmOfferTable != null) {
                customLoginFirmOfferTable.setValid(0);
            }
        }
        if (customLoginFirmOfferTable != null) {

            CustomInfoTable customInfoTable = customInfoRepository.getFirstById(customLoginFirmOfferTable.getCustomId());

            //如果找不到客户 直接显示系统异常
            if (customInfoTable == null) {
                customLoginFirmOfferTable.setLoginStatus(StatusConstants.MANAGER_COMPLETED_STATUS);
                customLoginFirmOfferRepository.save(customLoginFirmOfferTable);
                return;
            }

            AccountUpdateToManagerEntity accountToManagerEntity = new AccountUpdateToManagerEntity();

            accountToManagerEntity.setName(customLoginFirmOfferTable.getName());
            accountToManagerEntity.setLogin(customLoginFirmOfferTable.getLogin());
            accountToManagerEntity.setLeverage(customLoginFirmOfferTable.getLeverage());
            accountToManagerEntity.setGroup(customLoginFirmOfferTable.getGroupCode());
            accountToManagerEntity.setValid(customLoginFirmOfferTable.getValid());
            accountToManagerEntity.setRouteType(Constants.FIRM_OFFER_USER_RECORD_UPDATE);

            mqSendService.send(Constants.MT4_USER_RECORD_UPDATE, JSON.toJSONString(accountToManagerEntity));

            customLoginFirmOfferTable.setLoginStatus(StatusConstants.MANAGER_PROCESSING_STATUS);
            customLoginFirmOfferRepository.save(customLoginFirmOfferTable);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void callbackAutomaticAccount(AccountUpdateCallbackEntity callbackEntity) throws ServiceException {

        if (callbackEntity != null && callbackEntity.getCode() == Constants.SUCCESS_CODE && callbackEntity.getData() != null) {
            callbackEntity.getData().setStatus(StatusConstants.MANAGER_COMPLETED_STATUS);
        } else {
            callbackEntity.getData().setStatus(StatusConstants.MANAGER_PENDING_STATUS);

            System.out.println("修改交易账户manager异常,callback data:" + callbackEntity);
        }
        callbackAutomaticAccountUpdate(callbackEntity.getCode(), callbackEntity.getData());
    }

    /**
     * 开始回调创建订单 manager成功失败
     *
     * @param entity
     * @throws ServiceException
     */
    @Transactional(rollbackFor = Exception.class)
    public void callbackAutomaticAccountUpdate(Integer code, AccountUpdateToManagerEntity entity) throws ServiceException {
        CustomLoginFirmOfferTable customLoginFirmOfferTable = customLoginFirmOfferRepository.findFirstByLogin(entity.getLogin());

        if (customLoginFirmOfferTable == null) {
            return;
        }
        if (StatusConstants.MANAGER_COMPLETED_STATUS.equals(entity.getStatus())) {
            customLoginFirmOfferTable.setLoginStatus(entity.getStatus());
        } else {
            customLoginFirmOfferTable.setLoginStatus(StatusConstants.MANAGER_PENDING_STATUS);
            toManagerErrorService.addErrorInfo(code, Constants.DEMO_USER_RECORD_UPDATE, entity.getSerial(), entity);
        }


        customLoginFirmOfferRepository.save(customLoginFirmOfferTable);
    }

    private void existLogin(CustomLoginFirmOfferAddEntity entity) throws ServiceException {
        boolean bl = customLoginFirmOfferRepository.existsByLogin(entity.getLogin());
        if (bl) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }
    }
}
