package com.crm.manager.controller;

import com.crm.manager.service.AccountTypeService;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.dto.account.type.AccountTypeListDto;
import com.crm.rely.backend.core.dto.base.BaseResultDto;
import com.crm.rely.backend.core.entity.account.type.AccountTypeUpdateEntity;
import com.crm.rely.backend.core.entity.custom.info.InfoEntity;
import com.crm.rely.backend.core.entity.system.config.SendUpdateEmailCodeEntity;
import com.crm.rely.backend.service.EmailService;
import com.crm.rely.backend.util.GetIpAndMac;
import com.crm.rely.backend.util.GoogleAuthenticatorUtil;
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.Date;
import java.util.List;

/**
 * Created by max on 2020/8/18.
 */
@RestController
@RequestMapping("/config/account/type")
public class AccountTypeController {

    @Autowired
    private AccountTypeService accountTypeService;
    @Autowired
    private EmailService emailService;

    @PostMapping("/list")
    public BaseResultDto<List<AccountTypeListDto>> getList() throws Exception {
        return BaseResultDto.success(accountTypeService.getList());
    }

    @PostMapping("/update")
    public BaseResultDto<Object> update(@RequestBody @Validated AccountTypeUpdateEntity entity, InfoEntity infoEntity) throws Exception {

//        String emailCode = entity.getEmailCode();
        if (!GoogleAuthenticatorUtil.verifyCode(infoEntity.getSecretKey(), entity.getGaCode())) {
            return BaseResultDto.error(Constants.GOOGLE_CAPTCHA_ERROR);
        }
//        String email = infoEntity.getIbInfo().getEmail();
//        emailService.validateCode(email, emailCode);

        return accountTypeService.updateList(entity.getData());
    }

    @PostMapping("/update/send/code")
    public BaseResultDto updateChannelSendEmailCode(InfoEntity infoEntity) throws Exception {
        return sendEmailCode(infoEntity);
    }


    public BaseResultDto sendEmailCode(InfoEntity infoEntity) throws Exception {
        if (infoEntity == null || infoEntity.getIbInfo() == null) {
            return BaseResultDto.error(Constants.SYSTEM_ERROR);
        }
        SendUpdateEmailCodeEntity emailCodeEntity = new SendUpdateEmailCodeEntity();

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

        accountTypeService.sendEmailCode(emailCodeEntity);
        return BaseResultDto.success(Constants.SEND_SUCCESS);
    }

}
