package com.bonus.hn.bearing.capacity.backstage.manager.controller;

import cn.hutool.core.codec.Base64;
import com.bonus.hn.bearing.capacity.backstage.manager.entity.ImgResult;
import com.bonus.hn.bearing.capacity.backstage.manager.service.UserService;
import com.bonus.hn.bearing.capacity.backstage.manager.utils.AjaxRes;
import com.bonus.hn.bearing.capacity.backstage.manager.utils.GlobalConst;
import com.bonus.hn.bearing.capacity.backstage.manager.utils.VerifyCodeUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
 * @author bonus
 */
@RestController
@RequestMapping("/getCode")
public class VCodeController {

    /**
     * 登录验证码过期时间：单位 分钟
     */
    @Value("${loginCode.expiration}")
    private Long expiration;

    @Value("${loginCode.prefix}")
    private String prefix;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserService userService;
    /**
     * 获取验证码
     */
    @GetMapping("/vCode")
    @ResponseBody
    public ImgResult getCode() throws IOException {
        // 生成随机字串
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        String uuid = UUID.randomUUID().toString();
        // 存入redis
        redisTemplate.opsForValue().set(prefix + uuid,verifyCode, expiration, TimeUnit.MINUTES);
        // 生成图片
        int w = 111, h = 36;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(w, h, stream, verifyCode);
        try {
            return new ImgResult(Base64.encode(stream.toByteArray()),uuid);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            stream.close();
        }
    }

    @RequestMapping(value = "addLoginLog", method = RequestMethod.POST)
    @ApiOperation(value = "个人信息-登录日志")
    public AjaxRes addLoginLog() {
        AjaxRes ar = new AjaxRes();
        int cb = userService.addLoginLog();
        ar.setFailMsg(GlobalConst.DATA_FAIL);
        if(cb>0){
            ar.setFailMsg(GlobalConst.INIT_SUCCEED);
        }
        return  ar;
    }


    @RequestMapping(value = "updateLonLat", method = RequestMethod.POST)
    @ApiOperation(value = "更新大地坐标->百度经纬")
    public String  updateLonLat(String proId,String meridian) {
        int cb = userService.updateLonLat(proId,meridian);
        if(cb>0){
            return "success";
        }
        return "error";
    }
}
