package com.sqx.modules.sys.controller;

import com.sqx.common.utils.Result;
import com.sqx.common.validator.ValidatorUtils;
import com.sqx.common.validator.group.AddGroup;
import com.sqx.modules.app.dao.MsgDao;
import com.sqx.modules.app.entity.Msg;
import com.sqx.modules.sys.entity.SysUserEntity;
import com.sqx.modules.sys.form.SysLoginForm;
import com.sqx.modules.sys.service.SysCaptchaService;
import com.sqx.modules.sys.service.SysUserService;
import com.sqx.modules.sys.service.SysUserTokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;

/**
 * 登录相关
 */
@RestController
@Api(value = "登录相关", tags = {"登录相关"})
public class SysLoginController extends AbstractController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserTokenService sysUserTokenService;
    @Autowired
    private SysCaptchaService sysCaptchaService;
    @Autowired
    private MsgDao msgDao;

    /**
     * 验证码
     */
    @GetMapping("captcha.jpg")
    public void captcha(HttpServletResponse response, String uuid) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //获取图片验证码
        BufferedImage image = sysCaptchaService.getCaptcha(uuid);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }


    @PostMapping("/sys/registered")
    @ApiOperation("代理注册")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "msg", value = "验证码", dataTypeClass = String.class, paramType = "param"),
    })
    public Result registered(@RequestBody SysUserEntity user, String msg) {
        if(StringUtils.isBlank(user.getMobile())){
            return Result.error("注册失败,请输入手机号");
        }
        if(StringUtils.isBlank(msg)){
            return Result.error("注册失败,请输入验证码");
        }
        Msg msg1 = msgDao.findByPhoneAndCode(user.getMobile(), msg);
        if (msg1 == null) {
            return Result.error("验证码不正确！");
        }
        user.setIsChannel(1);
        user.setQdRate(new BigDecimal("0.01"));
        user.setStatus(1);
        user.setRoleIdList(Collections.singletonList(4L));
        ValidatorUtils.validateEntity(user, AddGroup.class);
        sysUserService.saveUser(user);
        return Result.success();
    }


    /**
     * 登录
     */
    @PostMapping("/sys/login")
    public Map<String, Object> login(@RequestBody SysLoginForm form) throws IOException {
        boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
        if (!captcha) {
            return Result.error("验证码不正确");
        }

        //用户信息
        SysUserEntity user = sysUserService.queryByUserName(form.getUsername());

        //账号不存在、密码错误
        if (user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
            return Result.error("账号或密码不正确");
        }

        //账号锁定
        if (user.getStatus() == 0) {
            return Result.error("账号已被锁定,请联系管理员");
        }

        //判断角色类型
        if (form.getAdminType() == 1 && user.getIsChannel() != null && user.getIsChannel() == 1) {
            return Result.error("代理账号请登录代理端！");
        } else if (form.getAdminType() == 2 && user.getIsChannel() == null) {
            return Result.error("管理员请登录管理端！");
        }

        //生成token，并保存到数据库
        Result r = sysUserTokenService.createToken(user.getUserId());
        return r;
    }


    /**
     * 退出
     */
    @PostMapping("/sys/logout")
    public Result logout() {
        sysUserTokenService.logout(getUserId());
        return Result.success();
    }

}
