package com.YuyeTech.HeartRate.game.controller;

import com.YuyeTech.HeartRate.constant.CookieConstant;
import com.YuyeTech.HeartRate.constant.RedisConstant;
import com.YuyeTech.HeartRate.dataobject.AdminInfo;
import com.YuyeTech.HeartRate.enums.RedisType;
import com.YuyeTech.HeartRate.game.userinfo.projo.UserInfo;
import com.YuyeTech.HeartRate.enums.ResultEnum;
import com.YuyeTech.HeartRate.form.AdminForm;
import com.YuyeTech.HeartRate.service.AdminInfoService;
import com.YuyeTech.HeartRate.game.userinfo.service.MainInfoService;
import com.YuyeTech.HeartRate.game.userinfo.service.UserInfoService;
import com.YuyeTech.HeartRate.utils.AliyunOSSUtil;
import com.YuyeTech.HeartRate.utils.CookieUtil;
import com.YuyeTech.HeartRate.utils.RedisSettingMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * @author:slambb
 * @date:2020/6/15
 */
@Controller
@RequestMapping("/backstage_manager")
@Slf4j
public class BackstageManagerController {
    @Autowired
    private AdminInfoService adminInfoService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisSettingMap redisSettingMap;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private AliyunOSSUtil aliyunOSSUtil;

    @Autowired
    private MainInfoService mainInfoService;

    @Value("${spring.profiles.active}")
    private String profiles;
    /***
     * 管理员登陆
     * @param map
     * @return
     */
    @GetMapping("/adminLogin")
    public ModelAndView adminLoginForm(
            HttpServletRequest request,
            Map<String, Object> map) {

        String url = "http://" + request.getServerName() //服务器地址
                + ":"
                + request.getServerPort()           //端口号
                + request.getRequestURI();
        log.info("adminLogin url={}", url);

        return new ModelAndView("login/login", map);
    }

    /***
     * 管理员登陆
     * @param map
     * @return
     */
    @GetMapping("/blurAdminLogin")
    public ModelAndView blurAdminLoginForm(
            HttpServletRequest request,
            Map<String, Object> map) {

        String url = "http://" + request.getServerName() //服务器地址
                + ":"
                + request.getServerPort()           //端口号
                + request.getRequestURI();
        log.info("adminLogin url={}", url);

        return new ModelAndView("login/blurLogin", map);
    }


    //login
    @RequestMapping("/adminLoginForm")
    @Deprecated
    public ModelAndView adminLoginSubmit(@ModelAttribute("form") AdminForm adminForm,
                                         HttpServletResponse response,
                                         Map<String, Object> map) {
        //todo 1.查找用户密码
        AdminInfo adminInfo = adminInfoService.findByNameAndPassword(adminForm.getAdminName(), adminForm.getAdminPassword());
        if (adminInfo == null) {
            map.put("msg", "用户登陆失败！");
            map.put("url", "/backstage_manager/adminLogin");
            return new ModelAndView("common/error", map);
        }
        //todo 2. 设置token至redis
        String token = UUID.randomUUID().toString();
        Integer expire = RedisConstant.EXPIRE;

        stringRedisTemplate.opsForValue().set(redisSettingMap.getTokenKey(token), adminInfo.getAdminName(), expire, TimeUnit.SECONDS);

        //3. 设置token至cookie
        CookieUtil.set(response, CookieConstant.TOKEN, token, expire);

        map.put("msg", ResultEnum.LOGIN_SUCCESS.getMessage());
        map.put("url", "/backstage_manager/index");
        return new ModelAndView("common/success", map);
    }

    @GetMapping("/logout")
    @Deprecated
    public ModelAndView logout(HttpServletRequest request,
                               HttpServletResponse response,
                               Map<String, Object> map) {
        //1. 从cookie里查询
        Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
        if (cookie != null) {
            //2. 清除redis
            //stringRedisTemplate.opsForValue().getOperations().delete(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue()));
            redisSettingMap.deleteValue(RedisType.TOKEN,cookie.getValue());
            //3. 清除cookie
            CookieUtil.set(response, CookieConstant.TOKEN, null, 0);
        }

        map.put("msg", ResultEnum.LOGOUT_SUCCESS.getMessage());
        map.put("url", "/backstage_manager/adminLogin");
        return new ModelAndView("common/success", map);
    }


    @GetMapping("/backstage_delete_user")
    public ModelAndView backstageDeleteUser(@RequestParam("userId") String userId, Map<String, Object> map) {

        //1.删除头像W
        UserInfo userInfo = userInfoService.findUserInfoById(userId, false);
        if (!userInfo.getAvatarUrl().equals("publicAvatar/defaultAvatar.png") && userInfo.getAvatarUrl() != null && userInfo.getAvatarUrl().length() != 0) {
            if (aliyunOSSUtil.deleteBlog(userInfo.getAvatarUrl())) {
                log.info("删除头像成功");
            }
        }
        //2.删除数据库数据
        mainInfoService.deleteMainInfoById(userId,"backstage_delete_user");

        map.put("msg", "删除用户信息成功");
        map.put("url", "/backstage_user/list");
        return new ModelAndView("common/success", map);
    }


    /**
     * 作为后台入口index
     * @param request
     * @param map
     * @return
     */
    @GetMapping("/index")
    public ModelAndView AdminLoginIndex(
            HttpServletRequest request,
            Map<String, Object> map) {

        String url = "http://" + request.getServerName() //服务器地址
                + ":"
                + request.getServerPort()           //端口号
                + request.getRequestURI();
        log.info("后台入口:adminLogin url={}", url);

        //当前环境
        map.put("profiles",profiles);
        return new ModelAndView("index", map);
    }
}
