package com.yutou.bilibili.Controllers;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yutou.bilibili.BiliBili.Services.IBiliBiliLiveService;
import com.yutou.bilibili.Services.ISystemConfigService;
import com.yutou.bilibili.BiliBili.Tools.BiliTools;
import com.yutou.bilibili.Services.IUserService;
import com.yutou.bilibili.Tools.AppTools;
import com.yutou.bilibili.Tools.Config;
import com.yutou.bilibili.Tools.RedisTools;
import com.yutou.bilibili.mybatis.Bili.mybatis.model.BilibiliUpInfo;
import com.yutou.bilibili.mybatis.model.UBiliUp;
import com.yutou.bilibili.mybatis.model.UUser;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

@Controller
public class UserController {
    @Resource
    IUserService service;
    @Resource
    IBiliBiliLiveService biliService;
    @Resource
    ISystemConfigService configService;

    @ResponseBody
    @RequestMapping("/user/reg.do")
    public JSONObject reg(UUser user, HttpServletResponse response) {
        JSONObject json = new JSONObject();
        String isReg = configService.getConfig(Config.USER_REG);
        if (isReg != null) {
            if (isReg.equals("0")) {
                json.put("code", -2);
                json.put("msg", "当前系统禁止注册");
                return json;
            }
        }
        user.setPower("[1,2,3,5,6,7]");
        user.setSubtime(new Date());
        user.setLogintoken(UUID.randomUUID().toString());
        RedisTools.set(user.getLogintoken(),user.getId()+"",30*24*60);
        AppTools.setCookie(response, "login", user.getLogintoken(), -1);
        boolean flag = service.reg(user);
        if (flag) {
            json.put("code", 0);
            json.put("msg", "注册成功");
        } else {
            json.put("code", -1);
            json.put("msg", "该用户已存在或无法注册");
        }
        return json;
    }

    @ResponseBody
    @RequestMapping("/user/login.do")
    public JSONObject login(UUser user, HttpServletResponse response) {
        JSONObject json = new JSONObject();
        json.put("code", 0);
        if (service.login(user.getUser(), user.getPassword())) {
            user = service.getUser(user.getUser());
            //user.setLogintoken(UUID.randomUUID().toString());
            RedisTools.set(user.getLogintoken(),user.getId()+"",30*24*60);
            AppTools.setCookie(response, "login", user.getLogintoken(), -1);
            json.put("msg", "登陆成功");
            json.put("power", user.getPower());
        } else {
            json.put("code", -1);
            json.put("msg", "登陆失败");
        }
        return json;
    }

    @ResponseBody
    @RequestMapping("/user/logout.do")
    public JSONObject logout(HttpServletRequest request, HttpServletResponse response) {
        JSONObject json = new JSONObject();
        String token = AppTools.getLoginToken(request);
        if (StringUtils.isEmpty(token)) {
            json.put("code", -1);
            json.put("msg", "注销失败");
        } else {
            UUser user = service.getUserToToken(token);
            if (user != null) {
                RedisTools.remove(user.getLogintoken());
                user.setLogintoken("");
                service.update(user);
                AppTools.deleteCookie(request, response, "login");
                json.put("code", 0);
                json.put("msg", "注销成功");
            } else {
                json.put("code", -2);
                json.put("msg", "注销失败");
            }
        }
        return json;
    }

    @ResponseBody
    @RequestMapping("/user/set/update.do")
    public JSONObject update(UUser user, HttpServletRequest request) {
        JSONObject json = new JSONObject();
        String token = AppTools.getLoginToken(request);
        if (StringUtils.isEmpty(token)) {
            json.put("code", -1);
            json.put("msg", "未登录");
        } else {
            UUser loginUser = service.getUserToUid(Integer.parseInt(RedisTools.get(token)));
            if (loginUser != null) {
                user.setLogintoken("");
                user.setId(loginUser.getId());
                user.setPower(loginUser.getPower());
                user.setBiliCookie(loginUser.getBiliCookie());
                user.setSubtime(loginUser.getSubtime());
                user.setPassword(AppTools.getMD5 (user.getPassword()));
                service.update(user);
                json.put("code", 0);
                json.put("msg", "修改成功");
            } else {
                json.put("code", -2);
                json.put("msg", "修改失败");
            }
        }
        return json;
    }

    @ResponseBody
    @RequestMapping("/user/up/list.do")
    public JSONObject uplist(HttpServletRequest request) {
        JSONObject json = new JSONObject();
        String token = AppTools.getLoginToken(request);
        if (StringUtils.isEmpty(token)) {
            json.put("code", "-1");
            json.put("msg", "未登录");
        } else {
            json.put("code", 0);
            json.put("msg", "ok");
            json.put("data", service.getUserUp(Integer.parseInt(RedisTools.get(token))));
        }
        return json;
    }

    @ResponseBody
    @RequestMapping("/user/up/set/add.do")
    public JSONObject addUp(HttpServletRequest request, BilibiliUpInfo info) {
        JSONObject json = new JSONObject();
        String token = AppTools.getLoginToken(request);
        if (StringUtils.isEmpty(token)) {
            json.put("code", "-1");
            json.put("msg", "未登录");
        } else {
            int roomid = 0;
            if (!info.getUrl().startsWith("http")) {
                info.setUrl("https://live.bilibili.com/" + info.getUrl());
            }
            BilibiliUpInfo tmp = biliService.queryUpToUrl(info.getUrl());
            if (tmp == null) {
                info = BiliTools.checkout(info);
                if (info != null) {
                    roomid = info.getRoomid();
                    info.setEnable(0);
                    biliService.addUpInfo(info);
                }
            } else {
                roomid = tmp.getRoomid();
            }
            if (roomid == 0) {
                json.put("code", -1);
                json.put("msg", "添加失败");
                return json;
            }
            UBiliUp up = new UBiliUp();
            up.setUid(Integer.parseInt(RedisTools.get(token)));
            up.setRoomid(roomid);
            json.put("code", 0);
            json.put("msg", service.addUp(up) ? "添加成功" : "添加失败");
        }
        return json;
    }

    @ResponseBody
    @RequestMapping("/user/get/test.do")
    public JSONObject testUser(HttpServletRequest request) {
        JSONObject json = new JSONObject();
        String token = AppTools.getLoginToken(request);
        if (StringUtils.isEmpty(token)) {
            json.put("code", -1);
            json.put("msg", "未登录");
        } else {
            UUser user = service.getUserToUid(Integer.parseInt(RedisTools.get(token)));;
            if (user == null) {
                json.put("code", -2);
                json.put("msg", "未登录");
                return json;
            }
            JSONArray powers = JSONArray.parseArray(user.getPower());
            JSONObject ujson = (JSONObject) JSON.toJSON(user);
            ujson.remove("logintoken");
            ujson.remove("biliCookie");
            ujson.remove("password");
            ujson.remove("subtime");
            ujson.put("power", powers);
            json.put("code", 0);
            json.put("data", ujson);
        }
        return json;
    }

}
