package com.YuyeTech.HeartRate.game.userinfo.controller;

import com.YuyeTech.HeartRate.VO.ResultVO;
import com.YuyeTech.HeartRate.constant.RedisConstant;
import com.YuyeTech.HeartRate.enums.RedisType;
import com.YuyeTech.HeartRate.enums.ResultEnum;
import com.YuyeTech.HeartRate.enums.UserEnum;
import com.YuyeTech.HeartRate.game.TP_WxInfo.projo.WxInfo;
import com.YuyeTech.HeartRate.game.TP_WxInfo.service.WxInfoService;
import com.YuyeTech.HeartRate.game.gameInfo.service.GameInfoService;
import com.YuyeTech.HeartRate.game.userinfo.projo.MainInfo;
import com.YuyeTech.HeartRate.game.userinfo.projo.UserInfo;
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.AppleUtil;
import com.YuyeTech.HeartRate.utils.RedisSettingMap;
import com.YuyeTech.HeartRate.utils.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 管理数据库数据
 *
 * @author:slambb
 * @date:2020/4/3
 */
@RestController
@RequestMapping("/manager")
@Slf4j
public class ManagerController {

    @Autowired
    private MainInfoService mainInfoService;

    @Autowired
    private GameInfoService gameInfoService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AliyunOSSUtil aliyunOSSUtil;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisSettingMap redisSettingMap;

    @Autowired
    private WxInfoService wxInfoService;
    /**
     * 通过类型来判断删除
     * 1。电话：密码或者验证码
     * 2。邮箱：密码或者验证码
     * 3。微信：微信授权code
     * 4。苹果：苹果授权code
     * @param userId
     * @param code
     * @param request
     * @return
     */
    @PostMapping("/deleteUserByType")
    public ResultVO deleteUserByType(@RequestParam("userId") String userId,
                                     @RequestParam("type") String type,
                                     @RequestParam("code") String code,
                                     HttpServletRequest request){

        if(type.equals("apple")){
           if(!AppleUtil.appleRevoke(code))
           {
               return ResultVOUtil.error(ResultEnum.APPLE_REVOKE_ERROR.getCode(), ResultEnum.APPLE_REVOKE_ERROR.getMessage());
           }
        }else if(type.equals("weixin")){
            WxInfo wxInfo = wxInfoService.findWxInfoByOpenid(code);
            if(wxInfo == null){
                return ResultVOUtil.error(ResultEnum.REVOKE_ERROR.getCode(), ResultEnum.REVOKE_ERROR.getMessage());
            }
        } else if(type.equals("phoneNumber") || type.equals("mailBox")){
            //查询电话号码
            MainInfo mainInfo = mainInfoService.findMainInfoById(userId);
            if(mainInfo == null){
                return ResultVOUtil.error(UserEnum.USER_PASSWORD_ERROR.getCode(), UserEnum.USER_PASSWORD_ERROR.getMessage());
            }
            String account = type.equals("phoneNumber")? mainInfo.getTelephoneNumber():mainInfo.getEmail();
            String codeValue = redisSettingMap.getValue(RedisType.SMS,account);
            if (!StringUtils.equals(codeValue, code)) {
                return ResultVOUtil.error(UserEnum.USER_CODE_ERROR.getCode(), UserEnum.USER_CODE_ERROR.getMessage());
            }
            Boolean bSuccess =redisSettingMap.deleteValue(RedisType.SMS, account);
            if (!bSuccess) {
                //删除不成功，redis不存在
                log.info("redis 没有对应的token");
                return ResultVOUtil.error(ResultEnum.PHONE_NUMBER_REVOKE_ERROR.getCode(), ResultEnum.PHONE_NUMBER_REVOKE_ERROR.getMessage());
            }
        } else {
            return ResultVOUtil.error(ResultEnum.REVOKE_ERROR.getCode(), ResultEnum.REVOKE_ERROR.getMessage());
        }

        //1.删除token
        String headToken = request.getHeader("token");
        log.info("{}",request.getParameterValues("userId")[0]);
        if (StringUtils.isNotBlank(headToken)) {
            log.info(String.format(RedisConstant.TOKEN_PREFIX, headToken));
//            Boolean bSuccess = redisTemplate.delete(String.format(RedisConstant.TOKEN_PREFIX, headToken));
            Boolean bSuccess = redisSettingMap.deleteValue(RedisType.TOKEN,headToken);
            if (!bSuccess) {
                //删除不成功，redis不存在，是非法token
                log.info("redis 没有对应的token");
                return ResultVOUtil.error(ResultEnum.TOKEN_IS_ILLEGAL.getCode(), ResultEnum.TOKEN_IS_ILLEGAL.getMessage());
            }
        }
        //2.删除头像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("删除头像成功");
            }
        }
        //3.删除数据库数据
        mainInfoService.deleteMainInfoById(userId,type);

        return ResultVOUtil.success();
    }
//    /**
//     * 删除用户数据
//     * @param userId
//     * @return
//     */
//    @GetMapping("/deleteUser")
//    public ResultVO deleteUser(@RequestParam("userId") String userId,
//                               HttpServletRequest request) {
//        //1.删除token
//        String headToken = request.getHeader("token");
//        log.info("{}",request.getParameterValues("userId")[0]);
//        if (StringUtils.isNotBlank(headToken)) {
//            log.info(String.format(RedisConstant.TOKEN_PREFIX, headToken));
//            Boolean bSuccess = redisTemplate.delete(String.format(RedisConstant.TOKEN_PREFIX, headToken));
//            if (!bSuccess) {
//                //删除不成功，redis不存在，是非法token
//                log.info("redis 没有对应的token");
//                return ResultVOUtil.error(ResultEnum.TOKEN_IS_ILLEGAL.getCode(), ResultEnum.TOKEN_IS_ILLEGAL.getMessage());
//            }
//        }
//        //2.删除头像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("删除头像成功");
//            }
//        }
//        //3.删除数据库数据
//        mainInfoService.deleteMainInfoById(userId);
//
//        return ResultVOUtil.success();
//    }
//
//    /**
//     * 更加userId 来删除信息
//     * @param userId
//     * @return
//     */
//    @GetMapping("/deleteUserById")
//    public ResultVO deleteUserById(@RequestParam("userId") String userId) {
//        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("删除头像成功");
//            }
//        }
//        //3.删除数据库数据
//        mainInfoService.deleteMainInfoById(userId);
//
//        return ResultVOUtil.success();
//    }
//
//    /**
//     * 删除游戏
//     * @param gameId
//     * @return
//     */
//    @GetMapping("/deleteGame")
//    @Transactional
//    public ResultVO deleteGame(@RequestParam("gameId") String gameId) {
//        gameInfoService.deleteByGameId(gameId);
//        return ResultVOUtil.success();
//    }
//
//
//    @PostMapping("/upload_feedback")
//    @ResponseBody
//    public ResultVO toUploadBlogPost(@RequestParam(value = "files", required = false) MultipartFile[] files,
//                                     @Valid FeedbackForm feedbackForm,
//                                     Map<String, Object> map) {
//
//        log.info("{}",files.length);
//
//
//        return ResultVOUtil.success();
//    }
}
