package com.crm.manager.controller;

import com.alibaba.fastjson.JSON;
import com.crm.manager.service.SysConfigService;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.constant.GlobalConfigConstants;
import com.crm.rely.backend.core.constant.PrefixEnum;
import com.crm.rely.backend.core.dto.base.BaseResultDto;
import com.crm.rely.backend.core.dto.base.ResultWithPagerDto;
import com.crm.rely.backend.core.dto.system.config.SysConfigSearchDto;
import com.crm.rely.backend.core.entity.system.config.*;
import com.crm.rely.backend.model.entity.user.info.UserInfoEntity;
import com.crm.rely.backend.core.exception.ServiceException;
import com.crm.rely.backend.model.constant.ConfigConstants;
import com.crm.rely.backend.model.dto.sys.notice.SysConfigNoticeEmailDto;
import com.crm.rely.backend.model.entity.sys.config.SysConfigFinanceEntity;
import com.crm.rely.backend.model.entity.sys.notice.SysConfigNoticeEmailByEmailCodeEntity;
import com.crm.rely.backend.util.GetIpAndMac;
import com.crm.rely.backend.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 配置
 *
 * @author houn
 */
@RestController
@RequestMapping("/config")
public class SysConfigController {

    @Autowired
    private SysConfigService sysConfigService;

    @PostMapping("/refresh")
    public BaseResultDto refresh() throws Exception {

        sysConfigService.refresh();
        return BaseResultDto.success();
    }

    @PostMapping("/cancel")
    public BaseResultDto cancel() throws Exception {

        sysConfigService.cancel();
        return BaseResultDto.success();
    }

    /**
     * 添加配置
     *
     * @param entity
     * @return
     * @throws Exception
     */
    @PostMapping("/add")
    public BaseResultDto add(@RequestBody @Validated SysConfigAddEntity entity) throws Exception {

        entity.setPwd(MD5Util.getMD5(entity.getPwd()));

        sysConfigService.add(entity);
        return BaseResultDto.success();
    }

    /**
     * 删除配置
     *
     * @param entity
     * @return
     * @throws Exception
     */
    @PostMapping("/delete")
    public BaseResultDto delete(@RequestBody @Validated SysConfigDeleteEntity entity, UserInfoEntity infoEntity) throws Exception {
        if (!PrefixEnum.PREFIX_SYSTEM.equals(infoEntity.getPrefix())) {
            return BaseResultDto.error(Constants.SYSTEM_ERROR);
        }
        sysConfigService.delete(entity);
        return BaseResultDto.success();
    }

    /**
     * 修改配置
     *
     * @param entity
     * @return
     * @throws Exception
     */
    @PostMapping("/update")
    public BaseResultDto update(@RequestBody @Validated SysConfigUpdateEntity entity, UserInfoEntity infoEntity) throws Exception {
        entity.setEmail(infoEntity.getEmail());
        sysConfigService.update(entity);

        return BaseResultDto.success();
    }

    @PostMapping("/update/send/code")
    public BaseResultDto updateManagerSendEmailCode(UserInfoEntity infoEntity) throws Exception {

        return updateSendEmailCode(infoEntity);
    }

    /**
     * 列表查询
     *
     * @param entity
     * @param infoEntity
     * @return
     * @throws Exception
     */
    @PostMapping("/search/list")
    public BaseResultDto list(@RequestBody @Validated SysConfigSearchEntity entity, UserInfoEntity infoEntity) throws Exception {


        ResultWithPagerDto<SysConfigSearchDto> result = sysConfigService.searchPageList(entity);

        return result;
    }

    /**
     * 单个查询
     *
     * @param entity
     * @return
     * @throws Exception
     */
    @PostMapping("/search/single")
    public BaseResultDto single(@RequestBody @Validated SysConfigSingleEntity entity) throws Exception {

        SysConfigSearchDto result = sysConfigService.searchSingle(entity);

        return BaseResultDto.success(result);
    }

    /**
     * 查看全局邮件配置
     *
     * @return
     * @throws Exception
     */
    @PostMapping("/email/search")
    public BaseResultDto searchGlobal() throws Exception {

        SysConfigSearchDto dto = sysConfigService.searchSingleByCode(GlobalConfigConstants.EMAIL_CONFIG_CONFIGURE);
        return BaseResultDto.success(dto);
    }

    /**
     * 发送修改配置邮件code(当前人员邮箱)
     *
     * @param infoEntity 登录人信息
     * @return
     * @throws Exception
     */
    private BaseResultDto updateSendEmailCode(UserInfoEntity infoEntity) throws Exception {
        if (infoEntity == null || infoEntity == null) {
            return BaseResultDto.error(Constants.SYSTEM_ERROR);
        }
        SendUpdateEmailCodeEntity emailCodeEntity = new SendUpdateEmailCodeEntity();

        emailCodeEntity.setEmail(infoEntity.getEmail());
        emailCodeEntity.setTime(new Date());
        emailCodeEntity.setUser(infoEntity.getId());
        emailCodeEntity.setIp(GetIpAndMac.getIp());

        sysConfigService.sendUpdateEmailCode(emailCodeEntity);
        return BaseResultDto.success(Constants.SEND_SUCCESS);
    }

    @PostMapping("/notice/email/search")
    public BaseResultDto searchGlobalNoticeEmail() throws Exception {
        List<String> codes = new ArrayList<>(6);

        codes.add(ConfigConstants.CUSTOM_SUBMIT_VERIFICATION_MANAGER_EMAIL);
        codes.add(ConfigConstants.FIRM_OFFER_COMPLETE_MANAGER_EMAIL);
        codes.add(ConfigConstants.ASSET_MANAGEMENT_COMPLETE_MANAGER_EMAIL);
        codes.add(ConfigConstants.FINANCE_DEPOSIT_MANAGER_EMAIL);
        codes.add(ConfigConstants.FINANCE_WITHDRAW_MANAGER_EMAIL);
        codes.add(ConfigConstants.FINANCE_TRAIN_MANAGER_EMAIL);

        List<SysConfigSearchDto> dtos = sysConfigService.searchSingleByCodes(codes);
        SysConfigNoticeEmailDto sysConfigNoticeEmailDto = new SysConfigNoticeEmailDto();
        for (SysConfigSearchDto sysConfigSearchDto : dtos) {
            switch (sysConfigSearchDto.getCode()) {
                case ConfigConstants.CUSTOM_SUBMIT_VERIFICATION_MANAGER_EMAIL:
                    sysConfigNoticeEmailDto.setCustomSubmitEmailNotice(sysConfigSearchDto.getValue());
                    break;
                case ConfigConstants.FIRM_OFFER_COMPLETE_MANAGER_EMAIL:
                    sysConfigNoticeEmailDto.setFirmOfferEmailNotice(sysConfigSearchDto.getValue());
                    break;
                case ConfigConstants.ASSET_MANAGEMENT_COMPLETE_MANAGER_EMAIL:
                    sysConfigNoticeEmailDto.setAssetManagementEmailNotice(sysConfigSearchDto.getValue());
                    break;
                case ConfigConstants.FINANCE_DEPOSIT_MANAGER_EMAIL:
                    sysConfigNoticeEmailDto.setDepositEmailNotice(sysConfigSearchDto.getValue());
                    break;
                case ConfigConstants.FINANCE_WITHDRAW_MANAGER_EMAIL:
                    sysConfigNoticeEmailDto.setWithdrawEmailNotice(sysConfigSearchDto.getValue());
                    break;
                case ConfigConstants.FINANCE_TRAIN_MANAGER_EMAIL:
                    sysConfigNoticeEmailDto.setTrainEmailNotice(sysConfigSearchDto.getValue());
                    break;
                default:
                    break;
            }
        }
        return BaseResultDto.success(sysConfigNoticeEmailDto);
    }

    @PostMapping("/notice/email/update")
    public BaseResultDto updateGlobalNoticeEmail(@RequestBody  SysConfigNoticeEmailByEmailCodeEntity sysConfigNoticeEmailByEmailCodeEntity) throws Exception {

        SysConfigUpdateEntitys entitys = new SysConfigUpdateEntitys();
        entitys.setEmail(sysConfigNoticeEmailByEmailCodeEntity.getEmail());
        entitys.setEmailCode(sysConfigNoticeEmailByEmailCodeEntity.getEmailCode());
        List<BaseSysConfigUpdateEntity> updateData = new ArrayList<>(6);

        BaseSysConfigUpdateEntity sysConfigMaxUpdateEntityRegister = new BaseSysConfigUpdateEntity();
        sysConfigMaxUpdateEntityRegister.setCode(ConfigConstants.CUSTOM_SUBMIT_VERIFICATION_MANAGER_EMAIL);
        sysConfigMaxUpdateEntityRegister.setValue(sysConfigNoticeEmailByEmailCodeEntity.getCustomSubmitEmailNotice());
        updateData.add(sysConfigMaxUpdateEntityRegister);

        BaseSysConfigUpdateEntity sysConfigMaxUpdateEntityLeverage = new BaseSysConfigUpdateEntity();
        sysConfigMaxUpdateEntityLeverage.setCode(ConfigConstants.FIRM_OFFER_COMPLETE_MANAGER_EMAIL);
        sysConfigMaxUpdateEntityLeverage.setValue(sysConfigNoticeEmailByEmailCodeEntity.getFirmOfferEmailNotice());
        updateData.add(sysConfigMaxUpdateEntityLeverage);

        BaseSysConfigUpdateEntity sysConfigMaxUpdateEntityApply = new BaseSysConfigUpdateEntity();
        sysConfigMaxUpdateEntityApply.setCode(ConfigConstants.ASSET_MANAGEMENT_COMPLETE_MANAGER_EMAIL);
        sysConfigMaxUpdateEntityApply.setValue(sysConfigNoticeEmailByEmailCodeEntity.getAssetManagementEmailNotice());
        updateData.add(sysConfigMaxUpdateEntityApply);

        BaseSysConfigUpdateEntity sysConfigMaxUpdateEntityDeposit = new BaseSysConfigUpdateEntity();
        sysConfigMaxUpdateEntityDeposit.setCode(ConfigConstants.FINANCE_DEPOSIT_MANAGER_EMAIL);
        sysConfigMaxUpdateEntityDeposit.setValue(sysConfigNoticeEmailByEmailCodeEntity.getDepositEmailNotice());
        updateData.add(sysConfigMaxUpdateEntityDeposit);

        BaseSysConfigUpdateEntity sysConfigMaxUpdateEntityWithdraw = new BaseSysConfigUpdateEntity();
        sysConfigMaxUpdateEntityWithdraw.setCode(ConfigConstants.FINANCE_WITHDRAW_MANAGER_EMAIL);
        sysConfigMaxUpdateEntityWithdraw.setValue(sysConfigNoticeEmailByEmailCodeEntity.getWithdrawEmailNotice());
        updateData.add(sysConfigMaxUpdateEntityWithdraw);

        BaseSysConfigUpdateEntity sysConfigMaxUpdateEntityTransfer = new BaseSysConfigUpdateEntity();
        sysConfigMaxUpdateEntityTransfer.setCode(ConfigConstants.FINANCE_TRAIN_MANAGER_EMAIL);
        sysConfigMaxUpdateEntityTransfer.setValue(sysConfigNoticeEmailByEmailCodeEntity.getTrainEmailNotice());
        updateData.add(sysConfigMaxUpdateEntityTransfer);

        entitys.setUpdateData(updateData);
        sysConfigService.updates(entitys);
        return BaseResultDto.success();
    }

    @PostMapping("/rate/search")
    public BaseResultDto searchGlobalRate() throws Exception {

        SysConfigSearchDto dto = sysConfigService.searchSingleByCode(ConfigConstants.FINANCE_CONFIGURE);
        SysConfigFinanceEntity financeEntity = JSON.parseObject(dto.getValue(), SysConfigFinanceEntity.class);
        if (financeEntity == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }
        return BaseResultDto.success(financeEntity);
    }

    @PostMapping("/rate/update")
    public BaseResultDto updateGlobalRate(@RequestBody SysConfigFinanceEntity sysConfigFinanceEntity) throws Exception {

        SysConfigUpdateEntity baseSysConfigUpdateEntity = new SysConfigUpdateEntity();
        baseSysConfigUpdateEntity.setCode(ConfigConstants.FINANCE_CONFIGURE);
        baseSysConfigUpdateEntity.setValue(JSON.toJSONString(sysConfigFinanceEntity));
        sysConfigService.update(baseSysConfigUpdateEntity);
        return BaseResultDto.success();
    }
}
