package com.huimv.admin.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huimv.admin.system.entity.Account;
import com.huimv.admin.system.entity.BaseFarmX;
import com.huimv.admin.system.entity.SysAccountMultilevel;
import com.huimv.admin.system.service.IBaseFarmXService;
import com.huimv.admin.system.service.ILoginService;
import com.huimv.admin.system.session.AccessToken;
import com.huimv.common.exception.ExceptionEnum;
import com.huimv.common.exception.MiException;
import com.huimv.common.token.TokenSign;
import com.huimv.common.utils.Result;
import com.huimv.common.utils.ResultCode;
import com.huimv.common.utils.VerifyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping(value = "/my")
public class LoginController {


    @Autowired
    ILoginService iLoginService;

//    @Autowired
//    RedisTemplate redisTemplate;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result login(HttpServletRequest req, @RequestBody Map<String, String> map)  {


        // 对密码加密
//        Result result = iLoginService.login(accountName,         .getMD5Str(password));
        String accountName = map.get("accountName");
        String password = map.get("password");
       /* String code = map.get("code");

        String remoteHost = req.getRemoteHost();
        String redisCode = redisTemplate.opsForValue().get(remoteHost);
        if (redisCode == null) {
            return  new Result(10005,"验证码过期,点击刷新",false);
        }
        if (!redisCode.equals(code.toUpperCase())) {
            return  new Result(10006,"验证码错误,登录失败",false);
        }*/
        // 未对密码加密
        Result result = iLoginService.login(accountName, password);
        if(result.getCode() == 10000){

            Account accountEntity = (Account) result.getData();
            AccessToken accessToken = new AccessToken();
            accessToken.setCreated(new Date());
            accessToken.setAccountName(accountName);
            accessToken.setCode(result.getCode());
            accessToken.setMessage(result.getMessage());
            String token = TokenSign.sign(accountName,accountEntity.getId());
            accessToken.setToken(token);

            accessToken.setId( accountEntity.getId());
//            accessToken.setLoginIp(remoteHost);
            return new Result(ResultCode.SUCCESS,accessToken);
        }
        return  result;
    }

    @RequestMapping("/logout")
    public Result logout(@RequestParam(name = "accountName", required = true) String accountName, @RequestParam(name = "password", required = true) String password) {
        return iLoginService.logout();
    }


    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("/send")
    public void createImg(HttpServletRequest request, HttpServletResponse response)  {
        try {
            //设置响应类型,告诉浏览器输出的内容为图片
            response.setContentType("image/jpeg");
            //设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            VerifyUtil randomValidateCode = new VerifyUtil();
            //输出验证码图片
            String code = randomValidateCode.getRandcode(request, response);
            System.out.println(code);
            //将生成的随机验证码存放到redis中
            String remoteHost = request.getRemoteHost();
            redisTemplate.opsForValue().set(remoteHost,code,300, TimeUnit.SECONDS);
        } catch (Exception e) {
            System.out.println("获取验证码异常:"+e);
            throw new MiException(ExceptionEnum.VERIFCATION_FAID);
        }
    }

    //登录-多牧场
    @PostMapping(value = "/loginMultilevel")
    public Result loginMultilevel(HttpServletRequest req, @RequestBody Map<String, String> map)  {


        String accountName = map.get("accountName");
        String password = map.get("password");
        String code = map.get("code");

        String remoteHost = req.getRemoteHost();
//        String redisCode = redisTemplate.opsForValue().get(remoteHost);
//        if (redisCode == null) {
//            return  new Result(10005,"验证码过期,点击刷新",false);
//        }
//        if (!redisCode.equals(code.toUpperCase())) {
//            return  new Result(10006,"验证码错误,登录失败",false);
//        }
        // 未对密码加密
        Result result = iLoginService.loginMultilevel(accountName, password);
        if(result.getCode() == 10000){

            SysAccountMultilevel accountEntity = (SysAccountMultilevel) result.getData();
            Integer id = accountEntity.getId();

            AccessToken accessToken = new AccessToken();
            accessToken.setCreated(new Date());
            accessToken.setAccountName(accountName);
            accessToken.setCode(result.getCode());
            accessToken.setMessage(result.getMessage());
            String token = TokenSign.sign(accountName,id);
            accessToken.setToken(token);

            accessToken.setId(id);
            accessToken.setLoginIp(remoteHost);
            return new Result(ResultCode.SUCCESS,accessToken);
        }
        return  result;
    }

    //测试-token
    @PostMapping(value = "/getToken")
    public String getToken(HttpServletRequest req)  {
        String token =  TokenSign.sign("superadmin",1);
        return  token;
    }

    @Autowired
    IBaseFarmXService baseFarmXService;

    @PostMapping("/xadd")
    public Result add(@RequestBody BaseFarmX baseFarmX){
        baseFarmXService.save(baseFarmX);
        return new Result(ResultCode.SUCCESS);
    }


    @GetMapping("/xremove")
    public Result remove(@RequestParam(name = "id")Integer id){
        baseFarmXService.removeById(id);
        return new Result(ResultCode.SUCCESS);
    }

    @PostMapping("/xupdate")
    public Result update(@RequestBody BaseFarmX baseFarmX){
        baseFarmXService.updateById(baseFarmX);
        return new Result(ResultCode.SUCCESS);
    }

    @GetMapping("/xlist")
    public Result list(){

        return new Result(ResultCode.SUCCESS,baseFarmXService.list());
    }

    @GetMapping("/xfarmList")
    public Result farmList(@RequestParam(name = "id")Integer id){
        QueryWrapper<BaseFarmX> wrapper = new QueryWrapper<>();
        wrapper.eq("row_status",true);
        if (id != null){
            wrapper.ne("id",id);
        }

        return new Result(ResultCode.SUCCESS,baseFarmXService.list(wrapper));
    }


}
