package com.crm.ucard.controller;

import com.alibaba.fastjson.JSON;
import com.crm.login.rely.backend.controller.BaseLoginController;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.constant.EmailSendEnum;
import com.crm.rely.backend.core.constant.PrefixEnum;
import com.crm.rely.backend.core.dto.base.BaseResultDto;
import com.crm.rely.backend.core.dto.custom.CustomInfoDto;
import com.crm.rely.backend.core.dto.custom.InfoDto;
import com.crm.rely.backend.core.dto.ib.info.IbInfoDto;
import com.crm.rely.backend.core.entity.custom.info.*;
import com.crm.rely.backend.exception.ServiceException;
import com.crm.rely.backend.service.EmailService;
import com.crm.rely.backend.service.SysCountryService;
import com.crm.rely.backend.util.DateUtil;
import com.crm.rely.backend.util.GetIpAndMac;
import com.crm.rely.backend.util.MD5Util;
import com.crm.ucard.service.CustomInfoService;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.BeanUtils;
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 org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Locale;

/**
 * @program: crm-backend
 * @description:
 * @author: houn
 * @create: 2019-07-25 15:57
 */
@Log4j
@RestController
@RequestMapping("/custom")
public class CustomController extends BaseLoginController {

    @Autowired
    private SysCountryService sysCountryService;

    @Autowired
    private CustomInfoService  customInfoService;

    @Autowired
    private EmailService emailService;

    /**
     * 退出登录
     *
     * @param httpServletRequest
     * @throws Exception
     */
    @Override
    @PostMapping("/logout")
    public BaseResultDto logout(HttpServletRequest httpServletRequest) throws Exception {

        return super.logout(httpServletRequest);
    }

    /**
     * 登录信息
     *
     * @param entity
     * @return
     * @throws Exception
     */
    @PostMapping("/login")
    public BaseResultDto login(@RequestBody @Validated CustomInfoLoginEntity entity, HttpServletRequest request,
                               HttpServletResponse response, HttpSession session) throws Exception {
        entity.setLoginName(entity.getLoginName().toLowerCase());

        log.info(String.format("login request,username:%s,ip:%s,CLIENT_IP:%s,time:%s",
                entity.getLoginName(), GetIpAndMac.getIp(request), GetIpAndMac.getClientIp(request),
                DateUtil.formatTime()));

        //密码处理为
        entity.setPassword(MD5Util.getMD5(entity.getPassword()));

        /**
         * 处理登录时间 登录ip 登录地区
         */
        entity.setIp(GetIpAndMac.getIp(request));
        String returnStr = sysCountryService.getAdderByIp(entity.getIp());

        entity.setAddress(returnStr);
        entity.setTime(new Date());

        InfoEntity infoEntity = customInfoService.login(entity);

        infoEntity.setPrefix(PrefixEnum.PREFIX_CUSTOM);

        String accessToken = super.login(infoEntity, entity.getSource());
        setLocaleResolver(infoEntity.getCustomInfo().getLang(), request, response);

        return BaseResultDto.success(Constants.LOGIN_SUCCESS, accessToken);
    }

    /**
     * 获取登录信息
     *
     * @param entity
     * @return
     * @throws Exception
     */
    @PostMapping("/info")
    public BaseResultDto info(InfoEntity entity) {

        InfoDto infoDto = new InfoDto();

        BeanUtils.copyProperties(entity, infoDto);

        if (entity.getCustomInfo() != null) {
            CustomInfoDto customInfoDto = new CustomInfoDto();
            BeanUtils.copyProperties(entity.getCustomInfo(), customInfoDto);
            infoDto.setCustomInfo(customInfoDto);
        } else {
            infoDto.setCustomInfo(null);
        }

        if (entity.getIbInfo() != null) {
            IbInfoDto ibInfoDto = new IbInfoDto();
            BeanUtils.copyProperties(entity.getIbInfo(), ibInfoDto);
            infoDto.setIbInfo(ibInfoDto);
        } else {
            infoDto.setIbInfo(null);
        }

//        setLocaleResolver(entity.getCustomInfo().getLang(), request, response);

        return BaseResultDto.success(infoDto);
    }

    /**
     * 登录修改密码
     *
     * @param entity
     * @param req
     * @param infoEntity
     * @return
     */
    @PostMapping("/update/login/password")
    public BaseResultDto updatePassword(@RequestBody @Validated CustomUpdateLoginPasswordEntity entity,
                                        HttpServletRequest req, InfoEntity infoEntity) throws Exception {

        entity.setId(infoEntity.getCustomInfo().getId());
        if (entity.getNewPassword().equals(entity.getOldPassword())) {
            return BaseResultDto.error(Constants.PASSWORD_NEW_AND_OLD_IDENTICAL_ERROR);
        }

        entity.setModifyIp(GetIpAndMac.getIp(req));
        entity.setModifyTime(new Date());
        entity.setModifyUser(infoEntity.getId());
        entity.setNewPassword(MD5Util.getMD5(entity.getNewPassword()));
        entity.setOldPassword(MD5Util.getMD5(entity.getOldPassword()));

        customInfoService.updatePassword(entity);
        return BaseResultDto.success(Constants.UPDATE_SUCCESS);
    }

    private void setLocaleResolver(String lang, HttpServletRequest request, HttpServletResponse response) {
        LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
        try {
            if ("cn".equals(lang)) {

                localeResolver.setLocale(request, response, new Locale("zh", "CN"));
            } else {
                localeResolver.setLocale(request, response, new Locale("en", "US"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 未登录修改密码发送邮件
     *
     * @param entity
     * @param req
     * @return
     */
    @PostMapping("/update/password/send/email")
    public BaseResultDto updatePasswordSendEmail(@RequestBody @Validated CustomUpdatePasswordSendEmailEntity entity,
                                                 HttpServletRequest req) throws Exception {
        String ip = GetIpAndMac.getIp(req);
        emailService.validate(ip, EmailSendEnum.FORGET_PASSWORD.getCode(), ip);

        entity.setIp(ip);
        entity.setTime(new Date());
        customInfoService.updatePasswordSendEmail(entity);

        return BaseResultDto.success(Constants.SEND_SUCCESS);
    }

    /**
     * 未登录根据邮件修改密码
     *
     * @param entity
     * @param req
     * @return
     */
    @PostMapping("/update/email/password")
    public BaseResultDto updatePassword(@RequestBody @Validated CustomUpdateEmailPasswordEntity entity,
                                        HttpServletRequest req) throws Exception {

        log.info(String.format("updatePassword:%s",JSON.toJSONString(entity)));
        entity.setModifyIp(GetIpAndMac.getIp(req));
        entity.setModifyTime(new Date());
        entity.setPassword(MD5Util.getMD5(entity.getPassword()));

        customInfoService.updatePassword(entity);

        return BaseResultDto.success(Constants.SUCCESS);
    }

    @RequestMapping("/get/balance")
    public BaseResultDto balance(InfoEntity infoEntity) throws ServiceException {

        BigDecimal balance = customInfoService.getBalance(infoEntity.getCustomInfo().getId());

        return BaseResultDto.success(balance);
    }

}
