package com.crm.globex.service.impl;

import com.alibaba.fastjson.JSON;
import com.crm.globex.configuration.MangerErrorSendEmailComponent;
import com.crm.globex.dao.mapper.MTMapper;
import com.crm.globex.dao.repository.AccountApplyRepository;
import com.crm.globex.dao.repository.CustomInfoRepository;
import com.crm.globex.service.AccountApplyService;
import com.crm.globex.service.CustomLoginService;
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.callback.AccountCallbackEntity;
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.CustomLoginAddEntity;
import com.crm.rely.backend.model.entity.sys.config.SysMt4ConfigureEntity;
import com.crm.rely.backend.model.pojo.table.AccountApplyTable;
import com.crm.rely.backend.model.pojo.table.CustomInfoTable;
import com.crm.rely.backend.model.pojo.view.AccountInfoView;
import com.crm.rely.backend.model.util.CustomInfoUtil;
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 com.google.common.base.Strings;
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 AccountApplyServiceImpl implements AccountApplyService {
    @Autowired
    private MangerErrorSendEmailComponent toManagerErrorService;
    @Autowired
    private AccountApplyRepository accountApplyRepository;

    @Autowired
    private CustomLoginService customLoginService;

    @Autowired
    private CustomInfoRepository customInfoRepository;

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private MqSendService mqSendService;

    @Autowired
    private EmailService emailService;

    @Autowired
    private MTMapper mtMapper;

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

        AccountApplyTable accountApplyTable =
                accountApplyRepository.findFirstByStatus(StatusConstants.APPLY_STATUS);
        if (accountApplyTable != null) {

            List<String> codes = new ArrayList<>(2);
            codes.add(ConfigConstants.AUTOMATIC_LOGON_LOGIN_MT4_REAL_NEXT);
            codes.add(ConfigConstants.AUTOMATIC_LOGON_LOGIN_MT4_REAL_CONFIGURE);

            List<SysConfigTable> sysConfigTables = sysConfigService.getByCodes(codes);
            SysMt4ConfigureEntity sysMt4ConfigureEntity = null;
            SysConfigTable nextLogin = null;
            for (SysConfigTable sysConfigTable : sysConfigTables) {
                if (ConfigConstants.AUTOMATIC_LOGON_LOGIN_MT4_REAL_CONFIGURE.equals(sysConfigTable.getCode())) {
                    sysMt4ConfigureEntity =
                            JSON.parseObject(sysConfigTable.getValue(), SysMt4ConfigureEntity.class);
                }
                if (ConfigConstants.AUTOMATIC_LOGON_LOGIN_MT4_REAL_NEXT.equals(sysConfigTable.getCode())) {
                    nextLogin = sysConfigTable;
                }
            }
            if (nextLogin == null || sysMt4ConfigureEntity == null) {
                //todo  通知管理员 系统出现问题
                accountApplyTable.setApproveUser(-1L);
                accountApplyTable.setApproveTime(new Date());
                accountApplyTable.setApproveDesc("103");
                accountApplyTable.setStatus(StatusConstants.REJECTED_STATUS);
                accountApplyRepository.save(accountApplyTable);
                return;
            }

            long login = 0;
            try {
                login = Long.parseLong(nextLogin.getValue());
            } catch (Exception e) {
                e.printStackTrace();
            }
            //设置当前账号
            accountApplyTable.setLogin(login);
            //设置下一个账号保存
            login++;
            nextLogin.setValue(String.valueOf(login));
            accountApplyTable.setGroupCode(sysMt4ConfigureEntity.getGroupCode());
            accountApplyTable.setLeverage(sysMt4ConfigureEntity.getLeverage());
            accountApplyTable.setCurrency(sysMt4ConfigureEntity.getCurrency());
            //设置状态为代修改中
            accountApplyTable.setAccountStatus(StatusConstants.MANAGER_PENDING_STATUS);
            //修改审核人  添加为系统审核
            accountApplyTable.setApproveUser(-1L);
            accountApplyTable.setApproveTime(new Date());
            accountApplyTable.setApproveDesc("100");
            accountApplyTable.setStatus(StatusConstants.PASSED_STATUS);

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

            accountApplyRepository.save(accountApplyTable);
            sysConfigService.save(nextLogin);
        }

    }

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

        if (accountApplyTable != null) {

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

            AccountToManagerEntity accountToManagerEntity = new AccountToManagerEntity();

            accountToManagerEntity.setSerial(accountApplyTable.getSerial());
            accountToManagerEntity.setName(CustomInfoUtil.getName(customInfoTable));
            accountToManagerEntity.setLogin(accountApplyTable.getLogin());
            accountToManagerEntity.setAgent(0L);
            accountToManagerEntity.setEmail(customInfoTable.getEmail());
            accountToManagerEntity.setPhone(customInfoTable.getPhone());
            accountToManagerEntity.setCountry(customInfoTable.getCountryEnName());
            accountToManagerEntity.setId(customInfoTable.getIdentity());
            accountToManagerEntity.setLeverage(accountApplyTable.getLeverage());
            accountToManagerEntity.setGroup(accountApplyTable.getGroupCode());
            accountToManagerEntity.setMasterPass(accountApplyTable.getMasterPassword());
            accountToManagerEntity.setInvestorPass(accountApplyTable.getInvestorPassword());
            accountToManagerEntity.setComment("--");
            accountToManagerEntity.setLeadSource(accountApplyTable.getSerial());
            accountToManagerEntity.setCity(customInfoTable.getCity());
            accountToManagerEntity.setTown(customInfoTable.getState());
            accountToManagerEntity.setPostalCode(customInfoTable.getZipCode());
            accountToManagerEntity.setAddressLine(customInfoTable.getAddressLine());
            accountToManagerEntity.setRouteType(Constants.USER_RECORD_CREATE);
            accountToManagerEntity.setValid(1);

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

            accountApplyTable.setAccountStatus(StatusConstants.MANAGER_PROCESSING_STATUS);
            accountApplyRepository.save(accountApplyTable);
        }
    }

    @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 {
        AccountApplyTable table = accountApplyRepository.findFirstBySerial(entity.getSerial());

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

        if (!StatusConstants.MANAGER_COMPLETED_STATUS.equals(entity.getStatus())) {

            table = setStatus(table, code);
        }

        if (StatusConstants.MANAGER_COMPLETED_STATUS.equals(table.getAccountStatus())) {

            CustomLoginAddEntity customLoginAddEntity = new CustomLoginAddEntity();
            BeanUtils.copyProperties(table, customLoginAddEntity);
            customLoginAddEntity.setValid(entity.getValid());
            customLoginAddEntity.setLoginStatus(StatusConstants.MANAGER_COMPLETED_STATUS);
            customLoginAddEntity.setAddIp(table.getAddIp());
            customLoginAddEntity.setAddTime(new Date());
            customLoginAddEntity.setAddUser(table.getAddUser());
            customLoginService.add(customLoginAddEntity);

            //发送邮件
            sendCustomEmail(table);
        }

        accountApplyRepository.save(table);
    }


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


        return accountApplyTable;
    }

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

        switch (code.intValue()) {
            case -2:

                AccountInfoView account = mtMapper.getLogin(accountApplyTable.getLogin(), Constants.MT4);
                if (account == null) {
                    accountApplyTable.setAccountStatus(StatusConstants.MANAGER_PENDING_STATUS);
                } else if (!Strings.isNullOrEmpty(account.getComment()) && account.getComment().equals(accountApplyTable.getComment())) {
                    accountApplyTable.setAccountStatus(StatusConstants.MANAGER_COMPLETED_STATUS);
                } else {
                    accountApplyTable.setAccountStatus(StatusConstants.MANAGER_PENDING_STATUS);
                    SysConfigTable sysConfigTable = getLoginConfig();
                    if (sysConfigTable == null) {
                        //todo  通知管理员 系统出现问题
                        throw ServiceException.exception(Constants.SYSTEM_ERROR);
                    }

                    long login = getLogin(sysConfigTable);
                    //设置当前账号
                    accountApplyTable.setLogin(login);
                    //设置下一个账号保存
                    login++;
                    sysConfigTable.setValue(String.valueOf(login));
                    sysConfigService.save(sysConfigTable);
                }

                break;
//            case -65:
//                accountApplyTable.setAccountStatus(null);
//                accountApplyTable.setStatus(StatusConstants.REJECTED_STATUS);
//                accountApplyTable.setApproveDesc("101");
//                break;
            default:
                break;
        }
        return accountApplyTable;
    }

    private SysConfigTable getLoginConfig() throws ServiceException {
        SysConfigTable sysConfigTable = null;
        sysConfigTable = sysConfigService.getByCode(ConfigConstants.AUTOMATIC_LOGON_LOGIN_MT4_REAL_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(AccountApplyTable 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_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();
        }
    }
}
