package com.crm.globex.service.impl;

import com.alibaba.fastjson.JSON;
import com.crm.globex.configuration.MangerErrorSendEmailComponent;
import com.crm.globex.dao.repository.AccountApplyAssetManagementRepository;
import com.crm.globex.dao.repository.CustomInfoRepository;
import com.crm.globex.service.AccountApplyAssetManagementService;
import com.crm.globex.service.CustomLoginAssetManagementService;
import com.crm.globex.service.SysConfigService;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.constant.MapConstants;
import com.crm.rely.backend.core.constant.StatusConstants;
import com.crm.rely.backend.core.entity.manager.AccountToManagerEntity;
import com.crm.rely.backend.core.entity.manager.FinanceBalanceToManagerEntity;
import com.crm.rely.backend.core.entity.manager.callback.AccountCallbackEntity;
import com.crm.rely.backend.core.entity.manager.callback.FinanceCallbackEntity;
import com.crm.rely.backend.core.entity.system.email.SysEmailSendEntity;
import com.crm.rely.backend.core.entity.web.notice.record.WebNoticeRecordAndEmailMqEntity;
import com.crm.rely.backend.core.exception.ServiceException;
import com.crm.rely.backend.core.pojo.table.SysConfigTable;
import com.crm.rely.backend.model.constant.ConfigConstants;
import com.crm.rely.backend.model.constant.EmailTemplateConstants;
import com.crm.rely.backend.model.entity.custom.login.asset.management.CustomLoginAssetManagementAddEntity;
import com.crm.rely.backend.model.entity.sys.config.SysMt4AssetManagementConfigureEntity;
import com.crm.rely.backend.model.pojo.table.AccountApplyAssetManagementTable;
import com.crm.rely.backend.model.pojo.table.CustomInfoTable;
import com.crm.rely.backend.service.EmailService;
import com.crm.rely.backend.service.MqSendService;
import com.crm.rely.backend.util.DateUtil;
import com.crm.rely.backend.util.GetRandom;
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.*;

/**
 * @description:
 * @author: houn
 * @create: 2020-07-31 23:06
 **/
@Service
public class AccountApplyAssetManagementServiceImpl implements AccountApplyAssetManagementService {
    @Autowired
    private MangerErrorSendEmailComponent toManagerErrorService;
    @Autowired
    private AccountApplyAssetManagementRepository accountApplyAssetManagementRepository;

    @Autowired
    private CustomLoginAssetManagementService customLoginAssetManagementService;

    @Autowired
    private CustomInfoRepository customInfoRepository;

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private MqSendService mqSendService;

    @Autowired
    private EmailService emailService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void scheduleUpdateAccountOperationType() throws ServiceException {

        AccountApplyAssetManagementTable accountApplyAssetManagementTable =
                accountApplyAssetManagementRepository.findFirstByStatus(StatusConstants.APPLY_STATUS);
        if (accountApplyAssetManagementTable != null) {
            List<String> codes = new ArrayList<>(2);
            codes.add(ConfigConstants.AUTOMATIC_LOGON_LOGIN_MT4_ASSET_MANAGEMENT_NEXT);
            codes.add(ConfigConstants.AUTOMATIC_LOGON_LOGIN_MT4_ASSET_MANAGEMENT_CONFIGURE);
            List<SysConfigTable> sysConfigTables = sysConfigService.getByCodes(codes);


            SysMt4AssetManagementConfigureEntity configureEntity = null;
            SysConfigTable nextLogin = null;
            for (SysConfigTable sysConfigTable : sysConfigTables) {
                if (ConfigConstants.AUTOMATIC_LOGON_LOGIN_MT4_ASSET_MANAGEMENT_CONFIGURE.equals(sysConfigTable.getCode())) {
                    configureEntity =
                            JSON.parseObject(sysConfigTable.getValue(), SysMt4AssetManagementConfigureEntity.class);
                }
                if (ConfigConstants.AUTOMATIC_LOGON_LOGIN_MT4_ASSET_MANAGEMENT_NEXT.equals(sysConfigTable.getCode())) {
                    nextLogin = sysConfigTable;
                }
            }
            if (nextLogin == null || configureEntity == null) {
                //todo  通知管理员 系统出现问题
                accountApplyAssetManagementTable.setApproveUser(-1L);
                accountApplyAssetManagementTable.setApproveTime(new Date());
                accountApplyAssetManagementTable.setApproveDesc("103");
                accountApplyAssetManagementTable.setStatus(StatusConstants.REJECTED_STATUS);
                accountApplyAssetManagementRepository.save(accountApplyAssetManagementTable);
                return;
            }


            long login = 0;
            try {
                login = Long.parseLong(nextLogin.getValue());
            } catch (Exception e) {
                e.printStackTrace();
            }
            //设置当前账号
            accountApplyAssetManagementTable.setLogin(login);
            //设置下一个账号保存
            login++;
            nextLogin.setValue(String.valueOf(login));
            String name = "ZG" + DateUtil.format("MMddHHmmss");
            accountApplyAssetManagementTable.setName(name);
            accountApplyAssetManagementTable.setGroupCode(configureEntity.getGroupCode());

            accountApplyAssetManagementTable.setLeverage(configureEntity.getLeverage());
            accountApplyAssetManagementTable.setCurrency(configureEntity.getCurrency());
            //设置状态为代修改中
            accountApplyAssetManagementTable.setAccountStatus(StatusConstants.MANAGER_PENDING_STATUS);
            accountApplyAssetManagementTable.setBalanceStatus(StatusConstants.MANAGER_PENDING_STATUS);
            //修改审核人  添加为系统审核
            accountApplyAssetManagementTable.setApproveUser(-1L);
            accountApplyAssetManagementTable.setApproveTime(new Date());
            accountApplyAssetManagementTable.setApproveDesc("100");
            accountApplyAssetManagementTable.setStatus(StatusConstants.PASSED_STATUS);

            accountApplyAssetManagementTable.setMasterPassword(GetRandom.getRandomPasswordString());
            accountApplyAssetManagementTable.setInvestorPassword(GetRandom.getRandomPasswordString());

            accountApplyAssetManagementRepository.save(accountApplyAssetManagementTable);
            sysConfigService.save(nextLogin);
        }

    }

    /**
     * 定时器 开始自动创建账户
     *
     * @throws ServiceException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void scheduleAutomaticAccount() throws ServiceException {
        //操作类型为自动 状态为正在待处理 审核状态为成功的订单
        AccountApplyAssetManagementTable accountApplyAssetManagementTable =
                accountApplyAssetManagementRepository.findFirstByAccountStatusAndBalanceStatusAndStatus(StatusConstants.MANAGER_PENDING_STATUS,
                        StatusConstants.MANAGER_PENDING_STATUS,
                        StatusConstants.PASSED_STATUS);

        if (accountApplyAssetManagementTable != null) {

            CustomInfoTable customInfoTable =
                    customInfoRepository.getFirstById(accountApplyAssetManagementTable.getCustomId());
            //如果找不到客户 直接显示系统异常
            if (customInfoTable == null) {
                accountApplyAssetManagementTable.setApproveUser(-1L);
                accountApplyAssetManagementTable.setApproveTime(new Date());
                accountApplyAssetManagementTable.setApproveDesc("103");
                accountApplyAssetManagementTable.setLogin(null);
                accountApplyAssetManagementTable.setGroupCode(null);
                accountApplyAssetManagementTable.setStatus(StatusConstants.REJECTED_STATUS);
                accountApplyAssetManagementRepository.save(accountApplyAssetManagementTable);
                return;
            }
            AccountToManagerEntity accountToManagerEntity = new AccountToManagerEntity();

            accountToManagerEntity.setSerial(accountApplyAssetManagementTable.getSerial());
            accountToManagerEntity.setName(accountApplyAssetManagementTable.getName());
            accountToManagerEntity.setLeverage(accountApplyAssetManagementTable.getLeverage());
            accountToManagerEntity.setLogin(accountApplyAssetManagementTable.getLogin());
            accountToManagerEntity.setGroup(accountApplyAssetManagementTable.getGroupCode());
            accountToManagerEntity.setMasterPass(accountApplyAssetManagementTable.getMasterPassword());
            accountToManagerEntity.setInvestorPass(accountApplyAssetManagementTable.getInvestorPassword());
            accountToManagerEntity.setLeadSource(accountApplyAssetManagementTable.getSerial());
            accountToManagerEntity.setRouteType(Constants.ASSET_MANAGEMENT_USER_RECORD_CREATE);
            accountToManagerEntity.setValid(1);

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

            accountApplyAssetManagementTable.setAccountStatus(StatusConstants.MANAGER_PROCESSING_STATUS);
            accountApplyAssetManagementRepository.save(accountApplyAssetManagementTable);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void callbackAutomaticAccount(AccountCallbackEntity 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);
        }
        callbackAutomaticAccount(callbackEntity.getCode(), callbackEntity.getData());
    }

    /**
     * 开始回调创建订单 manager成功失败
     *
     * @param entity
     * @throws ServiceException
     */
    @Transactional(rollbackFor = Exception.class)
    public void callbackAutomaticAccount(Integer code, AccountToManagerEntity entity) throws ServiceException {
        AccountApplyAssetManagementTable table =
                accountApplyAssetManagementRepository.findFirstBySerial(entity.getSerial());

        if (table == null) {
            return;
        }
        table.setAccountStatus(entity.getStatus());
        if (StatusConstants.MANAGER_COMPLETED_STATUS.equals(entity.getStatus())) {

            CustomLoginAssetManagementAddEntity customLoginAddEntity = new CustomLoginAssetManagementAddEntity();
            BeanUtils.copyProperties(table, customLoginAddEntity);
            customLoginAddEntity.setName(entity.getName());
            customLoginAddEntity.setLoginStatus(StatusConstants.MANAGER_COMPLETED_STATUS);
            customLoginAddEntity.setAddIp(table.getAddIp());
            customLoginAddEntity.setAddTime(new Date());
            customLoginAddEntity.setAddUser(table.getAddUser());
            customLoginAssetManagementService.add(customLoginAddEntity);

            sendCustomEmail(table);

        } else {
            table = setStatus(table, code);
            toManagerErrorService.addErrorInfo(code, Constants.DEMO_USER_RECORD_CREATE, entity.getSerial(), entity);
        }

        accountApplyAssetManagementRepository.save(table);
    }


    /**
     * 定时器 开始自动入金
     *
     * @throws ServiceException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void scheduleAutomaticAccountBalance() throws ServiceException {
        //操作类型为自动 状态为正在待处理 审核状态为成功的订单
        AccountApplyAssetManagementTable accountApplyAssetManagementTable =
                accountApplyAssetManagementRepository.findFirstByAccountStatusAndBalanceStatusAndStatus(StatusConstants.MANAGER_COMPLETED_STATUS,
                        StatusConstants.MANAGER_PENDING_STATUS,
                        StatusConstants.PASSED_STATUS);

        if (accountApplyAssetManagementTable != null) {

            FinanceBalanceToManagerEntity financeBalanceToManagerEntity = new FinanceBalanceToManagerEntity();
            financeBalanceToManagerEntity.setAmount(accountApplyAssetManagementTable.getBalance());
            financeBalanceToManagerEntity.setComment(accountApplyAssetManagementTable.getSerial());
            financeBalanceToManagerEntity.setSerial(accountApplyAssetManagementTable.getSerial());
            financeBalanceToManagerEntity.setType(1);
            financeBalanceToManagerEntity.setLogin(accountApplyAssetManagementTable.getLogin());
            financeBalanceToManagerEntity.setRouteType(Constants.ASSET_MANAGEMENT_TRADE_TRANS_INFO);

            mqSendService.send(Constants.MT4_TRADE_TRANS_INFO, JSON.toJSONString(financeBalanceToManagerEntity));

            accountApplyAssetManagementTable.setBalanceStatus(StatusConstants.MANAGER_PROCESSING_STATUS);
            accountApplyAssetManagementRepository.save(accountApplyAssetManagementTable);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void callbackAutomaticAccountBalance(FinanceCallbackEntity 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);
        }
        callbackAutomaticAccountBalance(callbackEntity.getCode(), callbackEntity.getData());
    }

    /**
     * 开始回调创建订单 manager成功失败
     *
     * @param entity
     * @throws ServiceException
     */
    @Transactional(rollbackFor = Exception.class)
    public void callbackAutomaticAccountBalance(Integer code, FinanceBalanceToManagerEntity entity) throws ServiceException {
        AccountApplyAssetManagementTable accountApplyAssetManagementTable =
                accountApplyAssetManagementRepository.findFirstBySerial(entity.getSerial());

        if (accountApplyAssetManagementTable == null) {
            return;
        }
        accountApplyAssetManagementTable.setBalanceStatus(entity.getStatus());

        if (!StatusConstants.MANAGER_COMPLETED_STATUS.equals(entity.getStatus())) {
            toManagerErrorService.addErrorInfo(code, Constants.DEMO_TRADE_TRANS_INFO, entity.getSerial(), entity);
        }

        accountApplyAssetManagementRepository.save(accountApplyAssetManagementTable);
    }

    private AccountApplyAssetManagementTable setStatus(AccountApplyAssetManagementTable accountApplyAssetManagementTable, Integer code) throws ServiceException {
        if (code == null) {
            code = 0;
        }
        accountApplyAssetManagementTable = setMT4Status(accountApplyAssetManagementTable, code);


        return accountApplyAssetManagementTable;
    }


    private AccountApplyAssetManagementTable setMT4Status(AccountApplyAssetManagementTable accountApplyAssetManagementTable, Integer code) throws ServiceException {
        if (code == null) {
            code = 0;
        }

        switch (code.intValue()) {
            case -2:
                accountApplyAssetManagementTable.setAccountStatus(StatusConstants.MANAGER_PENDING_STATUS);
                SysConfigTable sysConfigTable = getLoginConfig();
                if (sysConfigTable == null) {
                    //todo  通知管理员 系统出现问题
                    throw ServiceException.exception(Constants.SYSTEM_ERROR);
                }
                long login = getLogin(sysConfigTable);
                //设置当前账号
                accountApplyAssetManagementTable.setLogin(login);
                //设置下一个账号保存
                login++;
                sysConfigTable.setValue(String.valueOf(login));
                sysConfigService.save(sysConfigTable);
                break;
//            case -65:
//                accountApplyAssetManagementTable.setAccountStatus(null);
//                accountApplyAssetManagementTable.setStatus(StatusConstants.REJECTED_STATUS);
//                accountApplyAssetManagementTable.setApproveDesc("101");
//                break;
            default:
                break;
        }
        return accountApplyAssetManagementTable;
    }

    private SysConfigTable getLoginConfig() throws ServiceException {
        SysConfigTable sysConfigTable = null;
        sysConfigTable = sysConfigService.getByCode(ConfigConstants.AUTOMATIC_LOGON_LOGIN_MT4_ASSET_MANAGEMENT_NEXT);


        return sysConfigTable;
    }


    private long getLogin(SysConfigTable sysConfigTable) throws ServiceException {
        if (sysConfigTable == null) {
            //todo 通知管理员
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }
        long login = 0;
        try {
            login = Long.parseLong(sysConfigTable.getValue());
        } catch (Exception e) {
            e.printStackTrace();
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }
        return login;
    }

    private void sendCustomEmail(AccountApplyAssetManagementTable table) throws ServiceException {

        CustomInfoTable customInfoTable = customInfoRepository.getFirstById(table.getCustomId());
        if (customInfoTable == null) {
            throw new ServiceException(Constants.USER_NOT_EXIST_ERROR);
        }
        //构建map 用于后面邮件模版替换
        Map<String, String> map = new HashMap<>(10);

        map.put(MapConstants.LOGIN, String.valueOf(table.getLogin()));
        map.put(MapConstants.MASTER_PASSWORD, table.getMasterPassword());
        map.put(MapConstants.INVESTOR_PASSWORD, table.getInvestorPassword());
        map.put(MapConstants.C_ID, String.valueOf(table.getCId()));
        map.put(MapConstants.DATE_TIME, DateUtil.formatTime(new Date()));
        map.put(MapConstants.LOGIN_TYPE, "资管账户");

        SysEmailSendEntity sysEmailSendEntity = new SysEmailSendEntity();
        sysEmailSendEntity.setSubject("CWG DEPOSIT");
        sysEmailSendEntity.setMap(map);

        sysEmailSendEntity.setTemplateName(EmailTemplateConstants.ACCOUNT_ASSET_MANAGEMENT_CREATE_COMPLETE_SEND);

        sysEmailSendEntity.setUsers(customInfoTable.getEmail());
        try {
            emailService.sendEmail(sysEmailSendEntity);
            WebNoticeRecordAndEmailMqEntity mqEntity = new WebNoticeRecordAndEmailMqEntity(sysEmailSendEntity,
                    table.getCId(), table.getCustomId());
            mqSendService.send(Constants.WEB_NOTICE_PUT_RECORD, mqEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
