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.CustomLoginRepository;
import com.crm.globex.service.CustomLoginService;
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.CustomLoginAddEntity;
import com.crm.rely.backend.model.pojo.table.CustomInfoTable;
import com.crm.rely.backend.model.pojo.table.CustomLoginTable;
import com.crm.rely.backend.model.util.CustomInfoUtil;
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;

/**
 * @description:
 * @author: houn
 * @create: 2020-07-31 23:03
 **/
@Service
public class CustomLoginServiceImpl implements CustomLoginService {
    @Autowired
    private MangerErrorSendEmailComponent toManagerErrorService;
    @Autowired
    private CustomLoginRepository customLoginRepository;

    @Autowired
    private CustomInfoRepository customInfoRepository;

    @Autowired
    private MqSendService mqSendService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(CustomLoginAddEntity entity) throws ServiceException {
        existLogin(entity);
        CustomLoginTable customLoginTable = new CustomLoginTable();
        BeanUtils.copyProperties(entity, customLoginTable);
        customLoginTable.setStatus(StatusConstants.APPLY_PENDING_STATUS);
        customLoginRepository.save(customLoginTable);
    }

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

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

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

        CustomLoginTable customLoginTable =
                customLoginRepository.findFirstByLoginStatus(StatusConstants.MANAGER_PENDING_STATUS);

        if (customLoginTable != null) {

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

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


            AccountUpdateToManagerEntity accountToManagerEntity = new AccountUpdateToManagerEntity();

            accountToManagerEntity.setName(CustomInfoUtil.getName(customInfoTable));
            accountToManagerEntity.setLogin(customLoginTable.getLogin());
            accountToManagerEntity.setAgent(0L);
            accountToManagerEntity.setEmail(customInfoTable.getEmail());
            accountToManagerEntity.setPhone(customInfoTable.getPhone());
            accountToManagerEntity.setCountry(customInfoTable.getCountryEnName());
            accountToManagerEntity.setId(customInfoTable.getIdentity());
            accountToManagerEntity.setLeverage(customLoginTable.getLeverage());
            accountToManagerEntity.setGroup(customLoginTable.getGroupCode());
            accountToManagerEntity.setCity(customInfoTable.getCity());
            accountToManagerEntity.setTown(customInfoTable.getState());
            accountToManagerEntity.setPostalCode(customInfoTable.getZipCode());
            accountToManagerEntity.setAddressLine(customInfoTable.getAddressLine());
            accountToManagerEntity.setGroup(customLoginTable.getGroupCode());
            accountToManagerEntity.setValid(customLoginTable.getValid());
            accountToManagerEntity.setRouteType(Constants.USER_RECORD_UPDATE);

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

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

    @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 {
        CustomLoginTable customLoginTable = customLoginRepository.findFirstByLogin(entity.getLogin());

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


        customLoginRepository.save(customLoginTable);
    }

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