package com.crm.globex.service.impl;

import com.alibaba.fastjson.JSON;
import com.crm.globex.dao.repository.AccountApplyPasswordResetRepository;
import com.crm.globex.dao.repository.CustomInfoRepository;
import com.crm.globex.service.AccountApplyPasswordResetService;
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.AccountPasswordToManagerEntity;
import com.crm.rely.backend.core.entity.manager.callback.AccountPasswordCallbackEntity;
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.model.constant.EmailTemplateConstants;
import com.crm.rely.backend.model.pojo.table.AccountApplyPasswordResetTable;
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.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: houn
 * @create: 2020-07-24 11:06
 **/
@Service
public class AccountApplyPasswordResetServiceImpl implements AccountApplyPasswordResetService {

    @Autowired
    private AccountApplyPasswordResetRepository accountApplyPasswordResetRepository;

    @Autowired
    private MqSendService mqSendService;

    @Autowired
    private EmailService emailService;

    @Autowired
    private CustomInfoRepository customInfoRepository;

    /**
     * 定时器
     *
     * @throws ServiceException
     */
    @Transactional(rollbackFor = Exception.class)
    public void scheduleAutomaticDealRest() throws ServiceException {
        //操作类型为自动 状态为处理中 审核状态为成功的订单
        AccountApplyPasswordResetTable accountApplyPasswordResetTable =
                accountApplyPasswordResetRepository.findFirstByPasswordStatus(StatusConstants.MANAGER_PENDING_STATUS);

        if (accountApplyPasswordResetTable != null) {
            accountApplyPasswordResetTable.setPassword(GetRandom.getRandomPasswordString());

            AccountPasswordToManagerEntity accountPasswordToManagerEntity = new AccountPasswordToManagerEntity();
            accountPasswordToManagerEntity.setSerial(accountApplyPasswordResetTable.getSerial());
            accountPasswordToManagerEntity.setLogin(accountApplyPasswordResetTable.getLogin());
            accountPasswordToManagerEntity.setNewPass(accountApplyPasswordResetTable.getPassword());
            accountPasswordToManagerEntity.setType(Constants.MANAGER_PASSWORD_TYPE_MASTER_REST);
            accountPasswordToManagerEntity.setRouteType(Constants.USER_RECORD_MASTER_PASSWORD_REST_UPDATE);

            if (accountApplyPasswordResetTable.getLoginType().equals(1)) {
                mqSendService.send(Constants.MT4_DEMO_USER_RECORD_PASSWORD_UPDATE,
                        JSON.toJSONString(accountPasswordToManagerEntity));
            } else {
                mqSendService.send(Constants.MT4_USER_RECORD_PASSWORD_UPDATE, JSON.toJSONString(accountPasswordToManagerEntity));
            }


            //设置状态为调整中
            accountApplyPasswordResetTable.setPasswordStatus(StatusConstants.MANAGER_PROCESSING_STATUS);
            accountApplyPasswordResetRepository.save(accountApplyPasswordResetTable);
        }
    }

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

    /**
     * 开始回调 manager成功失败
     *
     * @param entity
     * @throws ServiceException
     */
    @Transactional(rollbackFor = Exception.class)
    public void callbackAutomaticDealRest(Integer code, AccountPasswordToManagerEntity entity) throws ServiceException {
        AccountApplyPasswordResetTable table = accountApplyPasswordResetRepository.findFirstBySerial(entity.getSerial());

        if (table == null) {
            return;
        }

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

            table.setPasswordStatus(StatusConstants.MANAGER_COMPLETED_STATUS);

            sendCustomEmail(table);
        } else {
            table.setPasswordStatus(StatusConstants.MANAGER_PENDING_STATUS);
        }
        accountApplyPasswordResetRepository.save(table);
    }


    private void sendCustomEmail(AccountApplyPasswordResetTable 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.C_ID, String.valueOf(table.getCId()));
        map.put(MapConstants.DATE_TIME, DateUtil.formatTime(new Date()));
        map.put(MapConstants.MASTER_PASSWORD, table.getPassword());
        String loginType = null;
        switch (table.getLoginType()) {
            case 1:
                loginType = "模拟账户";
                break;
            case 2:
                loginType = "实盘账户";
                break;
            case 3:
                loginType = "资管账户";
                break;
            case 4:
                loginType = "真实账户";
                break;
        }
        map.put(MapConstants.LOGIN_TYPE, loginType);

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

        sysEmailSendEntity.setTemplateName(EmailTemplateConstants.CUSTOM_DEAL_REST_PASSWORD_COMPLETE);

        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();
        }
    }
}
