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.CustomLoginDemoRepository;
import com.crm.globex.service.CustomLoginDemoService;
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.demo.CustomLoginDemoAddEntity;
import com.crm.rely.backend.model.pojo.table.CustomInfoTable;
import com.crm.rely.backend.model.pojo.table.CustomLoginDemoTable;
import com.crm.rely.backend.service.MqSendService;
import com.crm.rely.backend.util.DateUtil;
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 CustomLoginDemoServiceImpl implements CustomLoginDemoService {
    @Autowired
    private MangerErrorSendEmailComponent toManagerErrorService;
    @Autowired
    private CustomLoginDemoRepository customLoginDemoRepository;

    @Autowired
    private CustomInfoRepository customInfoRepository;

    @Autowired
    private MqSendService mqSendService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(CustomLoginDemoAddEntity entity) throws ServiceException {
        existLogin(entity);
        CustomLoginDemoTable customLoginDemoTable = new CustomLoginDemoTable();
        BeanUtils.copyProperties(entity, customLoginDemoTable);
        customLoginDemoTable.setStatus(StatusConstants.APPLY_PENDING_STATUS);
        customLoginDemoRepository.save(customLoginDemoTable);
    }

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

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

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

        CustomLoginDemoTable customLoginDemoTable =
                customLoginDemoRepository.findFirstByLoginStatus(StatusConstants.MANAGER_PENDING_STATUS);

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

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

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

            if (DateUtil.operationDay(customLoginDemoTable.getAddTime(), 15).getTime() < System.currentTimeMillis()) {
                customLoginDemoTable.setLoginStatus(StatusConstants.MANAGER_COMPLETED_STATUS);
                customLoginDemoRepository.save(customLoginDemoTable);
                return;
            }

            AccountUpdateToManagerEntity accountToManagerEntity = new AccountUpdateToManagerEntity();

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

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

            //设置杠杆状态为调整中
            customLoginDemoTable.setLoginStatus(StatusConstants.MANAGER_PROCESSING_STATUS);
            customLoginDemoRepository.save(customLoginDemoTable);
        }
    }

    @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 {
        CustomLoginDemoTable customLoginDemoTable = customLoginDemoRepository.findFirstByLogin(entity.getLogin());

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


        customLoginDemoRepository.save(customLoginDemoTable);
    }

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