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

import cn.hutool.core.date.DateUtil;
import com.YuyeTech.HeartRate.VO.ResultVO;
import com.YuyeTech.HeartRate.constant.RedisConstant;
import com.YuyeTech.HeartRate.enums.PictureType;
import com.YuyeTech.HeartRate.enums.RedisType;
import com.YuyeTech.HeartRate.enums.ResultEnum;
import com.YuyeTech.HeartRate.enums.UserEnum;
import com.YuyeTech.HeartRate.form.FeedbackForm;
import com.YuyeTech.HeartRate.game.TP_WxInfo.projo.WxInfo;
import com.YuyeTech.HeartRate.game.TP_WxInfo.service.WxInfoService;
import com.YuyeTech.HeartRate.game.cFeedBack.service.CFeedBackService;
import com.YuyeTech.HeartRate.game.cFeedBack.vo.CFeedBackSimpleVo;
import com.YuyeTech.HeartRate.game.cFeedBack.vo.CFeedBackVo;
import com.YuyeTech.HeartRate.game.gameInfo.service.GameInfoService;
import com.YuyeTech.HeartRate.game.imageInfo.projo.Pictures;
import com.YuyeTech.HeartRate.game.imageInfo.service.PicturesService;
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 org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 管理数据库数据
 *
 * @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;

    @Autowired
    private PicturesService picturesService;
    @Autowired
    private CFeedBackService cFeedBackService;
    /**
     * Client 通过类型来判断删除，通常注销账户时候调用此接口
     * 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();
//    }
//
//

    /**
     * 意见反馈接口
     * todo 后台需要处理对应的问题展示页面
     * @param userId
     * @param feedbackForm
     * @param request
     * @return
     */
    @PostMapping("/upload_feedback")
    @ResponseBody
    public ResultVO onUploadFeedback(@RequestParam("userId") String userId,
                                     @Valid FeedbackForm feedbackForm,
                                     HttpServletRequest request) {
        MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
        Map<String,MultipartFile> mapFile = req.getFileMap();
        List<MultipartFile> files = new ArrayList<>();
        if (!mapFile.isEmpty()){
            for(Map.Entry<String,MultipartFile> result : mapFile.entrySet()){
                files.add(result.getValue());
            }
            //uploadService.uploadProjectFile(coreFileListStr,resultList);
        }
        log.info("{}",files.size());
        File uploadCarouselFile = null;
        List<Pictures> picturesList = new ArrayList<>();
        try {
            for (int i = 0; i < files.size(); i++) {
                //获得文件
                MultipartFile multipartFile = files.get(i);
                String fileName = multipartFile.getOriginalFilename();
                if (!"".equals(fileName.trim())) {
                    uploadCarouselFile = new File(fileName);
                    FileOutputStream os = new FileOutputStream(uploadCarouselFile);
                    os.write(multipartFile.getBytes());
                    os.close();
                    multipartFile.transferTo(uploadCarouselFile);
                    //上传到OSS
                    String pictureUrl = aliyunOSSUtil.upload(uploadCarouselFile, "feedBack");
                    //1.向Pictures 添加数据
                    Pictures pictures1 = new Pictures();
                    pictures1.setPictureUrl(pictureUrl);
                    pictures1.setPictureType(PictureType.FEED_BACK.ordinal());
                    pictures1.setCreateTime(DateUtil.date());
                    pictures1.setUpdateTime(DateUtil.date());
                    pictures1 = picturesService.addPictureAndFlush(pictures1);
                    picturesList.add(pictures1);
                    log.info(aliyunOSSUtil.addDomainName(pictures1.getPictureUrl()));
                }
            }

            CFeedBackVo cFeedBackVo = new CFeedBackVo();
            cFeedBackVo.setUserId(userId);
            List<String> pictureIds = picturesList.stream().map(e->e.getPictureId().toString()).collect(Collectors.toList());
            cFeedBackVo.setPictureId(StringUtils.join(pictureIds,","));
            cFeedBackVo.setPictureType(PictureType.FEED_BACK.ordinal());
            cFeedBackVo.setProblemDescription(feedbackForm.getProblemDescription());
            cFeedBackVo.setTelephoneNumber(feedbackForm.getPhoneNumber());
            cFeedBackVo.setName(feedbackForm.getUserName());
            cFeedBackVo.setVersionName(feedbackForm.getVersionName());
            cFeedBackVo.setVersionCode(feedbackForm.getVersionCode());
            cFeedBackVo.setIsResolved(0);
            cFeedBackVo.setIsShow(1);
            cFeedBackVo.setUpdateTime(DateUtil.date());
            cFeedBackVo.setCreateTime(DateUtil.date());
            cFeedBackService.saveReturnVo(cFeedBackVo);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return ResultVOUtil.error(400,e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            return ResultVOUtil.error(400,e.getMessage());
        } finally {
            if (uploadCarouselFile != null)
                uploadCarouselFile.delete();
        }

        Map map = new HashMap();
        map.put("msg","意见反馈成功！");
        return ResultVOUtil.success(map);
    }
}
