package com.huimv.beeboxs.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huimv.beeboxs.common.exception.ExceptionEnum;
import com.huimv.beeboxs.common.exception.MiException;
import com.huimv.beeboxs.common.token.TokenSign;
import com.huimv.beeboxs.common.utils.Result;
import com.huimv.beeboxs.common.utils.ResultCode;
import com.huimv.beeboxs.common.utils.VerifyUtil;
import com.huimv.beeboxs.entity.HiveBaseBeehive;
import com.huimv.beeboxs.entity.HiveBaseStation;
import com.huimv.beeboxs.entity.SysAccountMultilevel;
import com.huimv.beeboxs.entity.vo.HiveBaseStationVo;
import com.huimv.beeboxs.service.IBaseHiveFarmService;
import com.huimv.beeboxs.service.IHiveBaseBeehiveService;
import com.huimv.beeboxs.service.IHiveBaseStationService;
import com.huimv.beeboxs.service.ILoginService;
import com.huimv.beeboxs.session.AccessToken;
import org.apache.commons.lang.StringUtils;
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.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

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


    @Autowired
    ILoginService iLoginService;



    @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());
            accessToken.setFarmId(accountEntity.getFarmIds());
            String token = TokenSign.sign(accountName,id,accountEntity.getFarmIds());
            accessToken.setToken(token);

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

    //测试-token
//    @PostMapping(value = "/getToken")
//    public String getToken(HttpServletRequest req)  {
//        String token =  TokenSign.sign("superbeeboxs",1,null);
//        return  token;
//    }
    @Autowired
    private IHiveBaseStationService baseStationService;

    @Autowired
    private IBaseHiveFarmService baseHiveFarmService;

    @Autowired
    private IHiveBaseBeehiveService baseBeehiveService;

    @Autowired
    private IBaseHiveFarmService farmService;

    @GetMapping("/updateStation")
    public Result updateStation(@RequestParam(name ="id") String id,
                                @RequestParam(name ="farmIds") Integer farmIds){

        HiveBaseStation auh = baseStationService.getOne(new QueryWrapper<HiveBaseStation>().eq("ap_uid_hex", id));
        if (ObjectUtil.isEmpty(auh)){
            return new Result(10001,"该基站未启用，请联系管理员",false);
        }
        Integer farmId = auh.getFarmId();
        if (ObjectUtil.isNotEmpty(farmId) && farmId >0 ){
            return new Result(10001,"该基站已绑定牧场",false);
        }

        String farmName = baseHiveFarmService.getById(farmIds).getFarmName();
        auh.setFarmId(farmIds);
        auh.setFarmName(farmName);
        auh.setBindingDate(new Date());
        baseStationService.updateById(auh);
        return new Result(10000,"绑定成功",true);
    }

    @GetMapping("/updateBeehive")
    public Result update(@RequestParam(name ="id") String id,
                         @RequestParam(name ="apUidHex") String apUidHex,
                         @RequestParam(name ="type") Integer type){

        HiveBaseBeehive uh = baseBeehiveService.getOne(new QueryWrapper<HiveBaseBeehive>().eq("uid_hex", id));

        if (type == 1){
            if (ObjectUtil.isEmpty(uh)){
                return new Result(10001,"蜂场环境传感器未启用，请联系管理员",false);
            }
            String farmId = uh.getApUidHex();
            if (StringUtils.isNotEmpty(farmId) ){
                return new Result(10001,"蜂场环境传感器已绑定基站",false);
            }
        }
        HiveBaseStation hex = baseStationService.getOne(new QueryWrapper<HiveBaseStation>().eq("ap_uid_hex", apUidHex));


        if (type == 2){
            if (ObjectUtil.isEmpty(uh)){
                return new Result(10001,"蜂箱智能终端未启用，请联系管理员",false);
            }
            String farmId = uh.getApUidHex();
            if (StringUtils.isNotEmpty(farmId) ){
                return new Result(10001,"蜂箱智能终端已绑定基站",false);
            }
        }
        uh.setType(type);

        uh.setBindingDate(new Date());

        uh.setFarmId(hex.getFarmId());
        uh.setApUidHex(apUidHex);
        uh.setApName(hex.getApName());
        baseBeehiveService.updateById(uh);
        if (type == 1){
            return new Result(10000,"蜂场环境传感器绑定成功",true);
        }else {
            return new Result(10000,"蜂箱智能终端绑定成功",true);
        }

    }


    @GetMapping("/getFarm")
    public Result getFarm(){

        return  new Result(ResultCode.SUCCESS,farmService.list());
    }
    @GetMapping("/listAllStation")
    public Result listAll(@RequestParam(name ="current") Integer current,
                          @RequestParam(name ="pageSize") Integer pageSize,
                          @RequestParam(name ="farmId") Integer farmId){
        Map map = new HashMap();
        map.put("current",current);
        map.put("pageSize",pageSize);
        map.put("farmId",farmId);

        return baseStationService.listAll(map);
    }
}
