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

import com.YuyeTech.HeartRate.VO.ResultVO;
import com.YuyeTech.HeartRate.annotation.Decrypt;
import com.YuyeTech.HeartRate.annotation.Encrypt;
import com.YuyeTech.HeartRate.common.pojo.PageInfo;
import com.YuyeTech.HeartRate.common.pojo.Result;
import com.YuyeTech.HeartRate.config.GameConfigTime;
import com.YuyeTech.HeartRate.dto.GameTagDTO;
import com.YuyeTech.HeartRate.dto.MakeGameTagDTO;
import com.YuyeTech.HeartRate.enums.GameEnum;
import com.YuyeTech.HeartRate.form.GameInfoForm;
import com.YuyeTech.HeartRate.game.gameInfo.projo.*;
import com.YuyeTech.HeartRate.game.gameInfo.service.*;
import com.YuyeTech.HeartRate.game.gameInfo.vo.GameInfoAndTagsVo;
import com.YuyeTech.HeartRate.game.gameInfo.vo.GameInfoVo;
import com.YuyeTech.HeartRate.game.imageInfo.projo.Pictures;
import com.YuyeTech.HeartRate.game.imageInfo.service.PicturesService;
import com.YuyeTech.HeartRate.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * @author:slambb
 * @date:2020/6/15
 */
@RestController
@RequestMapping("/backstage_game")
@Slf4j
public class BackstageGameController {
    @Autowired
    private AliyunOSSUtil aliyunOSSUtil;
    @Autowired
    private GameInfoService gameInfoService;

    @Autowired
    private GameCategoryService gameCategoryService;

    @Autowired
    private GamePictureService gamePictureService;

    @Autowired
    private PicturesService picturesService;

    private ImageUtils imageUtils;

    @Autowired
    private RecommendService recommendService;

    @Autowired
    private GameConfigTime gameConfig;

    @Autowired
    private GameTagReferenceService gameTagReferenceService;

    @Autowired
    private GameTagService gameTagService;


    /**
     * 前端view跳转,配置菜单路径
     * 设置默认参数
     *
     * @return
     */
    @GetMapping("gotoView")
    public ModelAndView gotoView() {
        //查询所有的类目
        List<GameCategory> categoryList = gameCategoryService.findAll();
        //allTags
        List<GameTag> gameTagList = gameTagService.findAll();
        List<MakeGameTagDTO> allCustomTags = gameTagList.stream().map(e -> {
            return new MakeGameTagDTO(e.getId(), e.getTitle(), e.getMode(), e.getIsDefault(), false);
        }).collect(Collectors.toList());
        ModelAndView modelAndView = new ModelAndView("client/gameInfo");
        modelAndView.addObject("categoryList", categoryList);//游戏分类
        modelAndView.addObject("allCustomTags", allCustomTags);//游戏标签
        return modelAndView;
    }

    /**
     * 分页查询数据
     *
     * @param vo
     * @return
     */
    @PostMapping("findAll")
    @Decrypt
    @Encrypt
    public Result<PageInfo<GameInfoVo>> findAll(GameInfoVo vo) {
        return gameInfoService.page(vo);
    }

    /**
     *   返回一个 map 游戏数据
     *   map.put("gameInfo", gameInfo);
     *   map.put("gamePicturesList", picturesList);
     *   map.put("gameTags",gameTagDTOS);
     * @param gameId
     * @return
     */
    @PostMapping("findGameDetail")
    @Decrypt
    @Encrypt
    public Result<?> findGameDetail(@RequestParam("gameId") String gameId){
        Map map = gameInfoService.findByGameDetail(gameId,false);
        return Result.of(map);
    }

    @PostMapping("saveBaseInfo")
    @Decrypt
    @Encrypt
    public Result<GameInfoVo> saveBaseInfo(GameInfoAndTagsVo vo) {
        //1.向gameInfo 添加数据 或者更新数据
        GameInfoVo saveVo = new GameInfoVo();
        BeanUtils.copyProperties(vo, saveVo);
        if(saveVo.getShowTime() == null || !StringUtils.hasText(saveVo.getShowTime().toString())){
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date localDate = sdf.parse(gameConfig.getEndTime());
                saveVo.setShowTime(localDate);
            }catch (ParseException e){
                return Result.of(null,false,"解析日期错误！");
            }

        }
        GameInfoVo gameInfoVo = gameInfoService.saveReturnVo(saveVo);
        //如果saveVO 不存在排行榜信息，则再存储一次GameId
        if(gameInfoVo.getGameRankingId() == null){
            gameInfoVo.setGameRankingId(gameInfoVo.getGameId());
            gameInfoVo.setGameRankingShow(0);
            gameInfoVo = gameInfoService.saveReturnVo(gameInfoVo);
        }

        //先删除对应的tag
        gameTagReferenceService.deleteGameTagByGameId(gameInfoVo.getGameId());
        List<GameTagReference> gameTagReferenceList = new ArrayList<>();
        String[] tagIds = vo.getMultiSelectTag().split(",");
        for (int i = 0; i < tagIds.length; i++) {
            GameTagReference gameTagReference = new GameTagReference();
            gameTagReference.setGameId(gameInfoVo.getGameId());
            gameTagReference.setTagId(Integer.parseInt(tagIds[i]));
            gameTagReference.setStatus(1);
            gameTagReferenceList.add(gameTagReference);

        }
        //保存tags引用
        gameTagReferenceService.saveGameTagReference(gameTagReferenceList);
        return Result.of(gameInfoVo);
    }

    /**
     * 删除数据
     * 删除时候，需要更新缓存列表
     *
     * @param id
     * @return
     */
    @PostMapping("delete")
    @Decrypt
    @Encrypt
    public Result delete(@RequestParam("id") String id) {
        String resultID = gameInfoService.deleteAndCache(id);
        //bluetoothInfoService.updateListToCache();
        return Result.of(resultID);
    }

    /**
     * 修改游戏对应图片
     * @param file
     * @param type
     * @param gameId
     * @return
     */
    @PostMapping("/uploadImg")
    public Result uploadImg(@RequestParam("file") MultipartFile file,
                            @RequestParam("type") String type,
                            @RequestParam("gameId") String gameId) {
        //1.向gameInfo 添加数据 或者更新数据
        GameInfoVo gameInfoVo = gameInfoService.getVo(gameId);
        if (gameInfoVo == null) {
            return Result.of(null, false, "上传游戏图片失败！");
        }
        //存的项目的中模版图片
        String contextPath = "";
        File uploadIconFile = null;
        try {
            if (null != file) {
                String filename = file.getOriginalFilename();
                if (!"".equals(filename.trim())) {
                    uploadIconFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(uploadIconFile);
                    os.write(file.getBytes());
                    os.close();
                    file.transferTo(uploadIconFile);
                    //保存图片
                    picturesService.addPictureToTheGame(uploadIconFile,type,gameInfoVo);
                    return Result.of(null, true, "上传成功");
                }
            }
            //如果没有上传成功，返回失败
            return Result.of(null, false, "上传失败");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (!contextPath.equals("")) {
                imageUtils.deleteImage(contextPath);
            }
            if (uploadIconFile != null)
                uploadIconFile.delete();
        }
        return Result.of(null, false, "上传失败");
    }


    @GetMapping("/list")
    public ModelAndView list(@RequestParam(value = "page", defaultValue = "1") Integer page,
                             @RequestParam(value = "size", defaultValue = "10") Integer size,
                             HttpServletRequest req,
                             Map<String, Object> map) {
        String userId = req.getParameter("userId");

        //添加推荐游戏，和推荐列表 字段信息

        //查询对应游戏数据
        PageRequest requestReCommend = PageRequest.of(0, 10, Sort.by(Sort.Direction.ASC, "createTime"));

        Map videoMap = recommendService.findByRecommendType(userId, 1, gameConfig.getEndTime(), requestReCommend);
        Map gameMap = recommendService.findByRecommendType(userId, 2, gameConfig.getEndTime(), requestReCommend);

        map.put("videoRecommend", videoMap.get("gameList"));
        map.put("gameRecommend", gameMap.get("gameList"));


        PageRequest request = PageRequest.of(page - 1, size);
        Page<GameInfo> GameInfo = gameInfoService.findPage(userId, 0, request);
        //查询所有的类目
        List<GameCategory> categoryList = gameCategoryService.findAll();

        map.put("categoryList", categoryList);
        map.put("gameInfos", GameInfo);
        map.put("currentPage", page);
        map.put("size", size);


        return new ModelAndView("/game/list", map);
    }

    @GetMapping("/detail")
    public ModelAndView detail(@RequestParam(value = "gameId") String gameId,
                               HttpServletRequest req,
                               Map<String, Object> map) {
        String userId = req.getParameter("userId");
        GameInfo gameInfo = gameInfoService.findByGameId(gameId,true);
        map.put("gameInfo", gameInfo);
        //查找图片库对应的图片信息
        List<Integer> pictureIdList = gamePictureService.findGamePictureIDList(gameId);
        List<Pictures> picturesList = picturesService.findAllByPictureIdList(pictureIdList);
        List<String> carouselUrlList = new ArrayList();
        for (Pictures item : picturesList) {
            log.info("=={}", item);
            if (item.getPictureType().equals(0)) {
                carouselUrlList.add(item.getPictureUrl());
            } else if (item.getPictureType().equals(1)) {
                map.put("icon", item);
            } else if (item.getPictureType().equals(2)) {
                map.put("cover", item);
            }
        }
        map.put("carouselUrlList", carouselUrlList);
        //查询所有的类目
        List<GameCategory> categoryList = gameCategoryService.findAll();
        map.put("categoryList", categoryList);

        List<GameTagDTO> gameTagDTOList = gameTagReferenceService.findGameTagByGameId(gameId);
        //allTags
        List<GameTag> gameTagList = gameTagService.findAll();
        List<MakeGameTagDTO> allCustomTags = gameTagList.stream().map(e -> {
            return new MakeGameTagDTO(e.getId(), e.getTitle(), e.getMode(), e.getIsDefault(), false);
        }).collect(Collectors.toList());
        for (int i = 0; i < allCustomTags.size(); i++) {
            for (int j = 0; j < gameTagDTOList.size(); j++) {
                if (allCustomTags.get(i).getTagId() == gameTagDTOList.get(j).getTagId()) {
                    allCustomTags.get(i).setTagSelect(true);
                }
            }
        }
        map.put("allCustomTags", allCustomTags);

        return new ModelAndView("/game/detail", map);
    }


    /**
     * 添加新游戏
     *
     * @param map
     * @return
     */
    @GetMapping("/add")
    public ModelAndView addGame(Map<String, Object> map) {

        GameInfo gameInfo = new GameInfo();
        map.put("gameInfo", gameInfo);

        //查询所有的类目
        List<GameCategory> categoryList = gameCategoryService.findAll();
        map.put("categoryList", categoryList);

        //allTags
        List<GameTag> gameTagList = gameTagService.findAll();
        List<MakeGameTagDTO> allCustomTags = gameTagList.stream().map(e -> {
            return new MakeGameTagDTO(e.getId(), e.getTitle(), e.getMode(), e.getIsDefault(), false);
        }).collect(Collectors.toList());
        map.put("allCustomTags", allCustomTags);

        return new ModelAndView("/game/detail", map);
    }


    @PostMapping("/upload")
    public ModelAndView upload(@RequestParam("icon") MultipartFile icon,
                               @RequestParam("cover") MultipartFile cover,
                               @RequestParam("scroll") MultipartFile[] scroll,
                               @Valid GameInfoForm gameInfoForm,
                               @RequestParam("multiselectTag") Integer[] multiselectTag,
                               Map<String, Object> map) {
        if (StringUtils.isEmpty(gameInfoForm.getShowTime())) {
            map.put("msg", "显示时间不能为空！");
            map.put("url", "/backstage_game/detail");
            return new ModelAndView("common/error", map);
        }
        //存的项目的中模版图片
        String contextPath = "";
        File uploadIconFile = null, uploadCoverFile = null, uploadCarouselFile = null;
        //是否是添加新的，用bool 值判断
        Boolean BAddIcon = false, BAddCover = false, BAddCarousel = false;
        Pictures pictureIcon = new Pictures();
        Pictures pictureCover = new Pictures();
        try {
            String uploadUrl = "";
            if (null != icon) {
                String filename = icon.getOriginalFilename();
                if (!"".equals(filename.trim())) {
                    uploadIconFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(uploadIconFile);
                    os.write(icon.getBytes());
                    os.close();
                    icon.transferTo(uploadIconFile);
                    //上传到OSS
                    uploadUrl = aliyunOSSUtil.upload(uploadIconFile, "gameIcon");

                    //添加icon 数据，type = 1
                    pictureIcon.setPictureUrl(uploadUrl);
                    pictureIcon.setPictureType(1);
                    pictureIcon = picturesService.addPictureAndFlush(pictureIcon);

                    BAddIcon = true;
                }
            }
            String coverUrl = "";
            if (null != cover) {
                String filename = cover.getOriginalFilename();
                if (!"".equals(filename.trim())) {
                    uploadCoverFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(uploadCoverFile);
                    os.write(cover.getBytes());
                    os.close();
                    cover.transferTo(uploadCoverFile);
                    //上传到OSS
                    coverUrl = aliyunOSSUtil.upload(uploadCoverFile, "pictures");

                    //添加cover 数据，type = 2
                    pictureCover.setPictureUrl(coverUrl);
                    pictureCover.setPictureType(2);
                    pictureCover = picturesService.addPictureAndFlush(pictureCover);

                    BAddCover = true;
                }
            }
            //轮播图
            List<Pictures> picturesList = new ArrayList<>();
            try {
                for (int i = 0; i < scroll.length; i++) {
                    //获得文件
                    MultipartFile multipartFile = scroll[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, "pictures");
                        //1.向Pictures 添加数据
                        Pictures pictures1 = new Pictures();
                        pictures1.setPictureUrl(pictureUrl);
                        pictures1.setPictureType(0);
                        pictures1 = picturesService.addPictureAndFlush(pictures1);
                        picturesList.add(pictures1);
                        log.info(aliyunOSSUtil.addDomainName(pictures1.getPictureUrl()));

                        BAddCarousel = true;
                    }
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            //1.向gameInfo 添加数据 或者更新数据
            GameInfo gameInfo = new GameInfo();
            if (!StringUtils.isEmpty(gameInfoForm.getGameId())) {
                gameInfo = gameInfoService.findByGameId(gameInfoForm.getGameId(), false);
            } else {
                String _id = KeyUtil.genUniqueKey();
                gameInfoForm.setGameId(_id);
            }
            BeanUtils.copyProperties(gameInfoForm, gameInfo);

            //如果上传的文件存在 uploadUrl != "" coverUrl != ""
            if (BAddIcon)
                gameInfo.setGameIcon(uploadUrl);
            if (BAddCover)
                gameInfo.setGamePicture(coverUrl);

            //todo 后续修改成可以选择，后台
            gameInfo.setGameRankingId(gameInfo.getGameId());
            gameInfo.setGameRankingShow(1);
            GameInfo gameInfoTemp = gameInfoService.addGameInfoAndFlush(gameInfo);
            //保存tags引用
            List<GameTagReference> gameTagReferenceList = new ArrayList<>();
            for (int i = 0; i < multiselectTag.length; i++) {
                GameTagReference gameTagReference = new GameTagReference();
                gameTagReference.setGameId(gameInfoTemp.getGameId());
                gameTagReference.setTagId(multiselectTag[i]);
                gameTagReference.setStatus(1);
                gameTagReferenceList.add(gameTagReference);

            }
            gameTagReferenceService.saveGameTagReference(gameTagReferenceList);

            //把图片库数据和游戏信息绑定起来
            if (BAddIcon) {
                GamePicture gamePictureIcon = new GamePicture();
                gamePictureIcon.setGpType(1);
                gamePictureIcon.setGameId(gameInfoTemp.getGameId());
                gamePictureIcon.setPictureId(pictureIcon.getPictureId());
                gamePictureService.addGamePicture(gamePictureIcon);

                map.put("icon", aliyunOSSUtil.addDomainName(pictureIcon.getPictureUrl()));
            }

            if (BAddCover) {
                GamePicture gamePictureCover = new GamePicture();
                gamePictureCover.setGpType(2);
                gamePictureCover.setGameId(gameInfoTemp.getGameId());
                gamePictureCover.setPictureId(pictureCover.getPictureId());
                gamePictureService.addGamePicture(gamePictureCover);

                map.put("cover", aliyunOSSUtil.addDomainName(pictureCover.getPictureUrl()));

            }


            //绑定轮播图 type =0
            List<String> carouselUrlList = new ArrayList();

            for (int i = 0; i < picturesList.size(); i++) {
                GamePicture gamePictureList = new GamePicture();
                gamePictureList.setGpType(0);
                gamePictureList.setGameId(gameInfoTemp.getGameId());
                gamePictureList.setPictureId(picturesList.get(i).getPictureId());
                gamePictureService.addGamePicture(gamePictureList);

                log.info("绑定轮播图");
                carouselUrlList.add(aliyunOSSUtil.addDomainName(picturesList.get(i).getPictureUrl()));
            }


            if (!StringUtils.isEmpty(gameInfoTemp.getGameIcon()))
                gameInfoTemp.setGameIcon(aliyunOSSUtil.addDomainName(gameInfoTemp.getGameIcon()));
            if (!StringUtils.isEmpty(gameInfoTemp.getGamePicture()))
                gameInfoTemp.setGamePicture(aliyunOSSUtil.addDomainName(gameInfoTemp.getGamePicture()));

            map.put("gameInfo", gameInfoTemp);

            map.put("carouselUrlList", carouselUrlList);

            //查询所有的类目
            List<GameCategory> categoryList = gameCategoryService.findAll();
            map.put("categoryList", categoryList);

            //allTags
            List<GameTag> gameTagList = gameTagService.findAll();
            List<MakeGameTagDTO> allCustomTags = gameTagList.stream().map(e -> {
                return new MakeGameTagDTO(e.getId(), e.getTitle(), e.getMode(), e.getIsDefault(), false);
            }).collect(Collectors.toList());
            for (int i = 0; i < allCustomTags.size(); i++) {
                for (int j = 0; j < multiselectTag.length; j++) {
                    if (allCustomTags.get(i).getTagId() == multiselectTag[j]) {
                        allCustomTags.get(i).setTagSelect(true);
                    }
                }
            }
            map.put("allCustomTags", allCustomTags);

            return new ModelAndView("/game/detail", map);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (!contextPath.equals("")) {
                imageUtils.deleteImage(contextPath);
            }
            if (uploadIconFile != null)
                uploadIconFile.delete();
            if (uploadCoverFile != null)
                uploadCoverFile.delete();
            if (uploadCarouselFile != null)
                uploadCarouselFile.delete();
        }

        map.put("msg", "游戏数据更新失败！");
        map.put("url", "/backstage_game/detail");
        return new ModelAndView("common/error", map);
    }

    /**
     * 处理修改游戏信息
     *
     * @param icon
     * @param cover
     * @param scroll
     * @param gameInfoForm
     * @param map
     * @return
     */
    @PostMapping("/modify")
    public ModelAndView modify(@RequestParam("icon") MultipartFile icon,
                               @RequestParam("cover") MultipartFile cover,
                               @RequestParam("scroll") MultipartFile[] scroll,
                               @Valid GameInfoForm gameInfoForm,
                               @RequestParam("multiselectTag") Integer[] multiselectTag,
                               Map<String, Object> map) {

        if (StringUtils.isEmpty(gameInfoForm.getShowTime())) {
            map.put("msg", "显示时间不能为空！");
            map.put("url", "/backstage_game/detail");
            return new ModelAndView("common/error", map);
        }
        //存的项目的中模版图片
        String contextPath = "";
        File uploadIconFile = null, uploadCoverFile = null, uploadCarouselFile = null;
        //是否是添加新的，用bool 值判断
        Boolean BAddIcon = false, BAddCover = false, BAddCarousel = false;
        try {
            String uploadUrl = "";
            if (null != icon) {
                String filename = icon.getOriginalFilename();
                if (!"".equals(filename.trim())) {
                    uploadIconFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(uploadIconFile);
                    os.write(icon.getBytes());
                    os.close();
                    icon.transferTo(uploadIconFile);
                    //上传到OSS
                    uploadUrl = aliyunOSSUtil.upload(uploadIconFile, "gameIcon");

                    //修改icon 数据，type = 1
                    GamePicture gamePicture = gamePictureService.findByGameIdAndType(1, gameInfoForm.getGameId());
                    if (gamePicture != null) {
                        //删除游戏绑定图片库的信息，图片库 不做删除操作
                        gamePictureService.deleteGamePictureByGpId(gamePicture.getGpId());
                    }
                    //写入图片库
                    Pictures pictureIcon = new Pictures();
                    pictureIcon.setPictureUrl(uploadUrl);
                    pictureIcon.setPictureType(1);
                    pictureIcon = picturesService.addPictureAndFlush(pictureIcon);
                    //添加新的绑定信息
                    GamePicture gamePictureIcon = new GamePicture();
                    gamePictureIcon.setGpType(1);
                    gamePictureIcon.setGameId(gameInfoForm.getGameId());
                    gamePictureIcon.setPictureId(pictureIcon.getPictureId());
                    gamePictureService.addGamePicture(gamePictureIcon);

                    BAddIcon = true;

                    map.put("icon", aliyunOSSUtil.addDomainName(pictureIcon.getPictureUrl()));
                }
            }
            String coverUrl = "";
            if (null != cover) {
                String filename = cover.getOriginalFilename();
                if (!"".equals(filename.trim())) {
                    uploadCoverFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(uploadCoverFile);
                    os.write(cover.getBytes());
                    os.close();
                    cover.transferTo(uploadCoverFile);
                    //上传到OSS
                    coverUrl = aliyunOSSUtil.upload(uploadCoverFile, "pictures");

                    //添加cover 数据，type = 2
                    GamePicture gamePictureCover = gamePictureService.findByGameIdAndType(2, gameInfoForm.getGameId());

                    if (gamePictureCover != null) {
                        //删除游戏绑定图片库的信息，图片库 不做删除操作
                        gamePictureService.deleteGamePictureByGpId(gamePictureCover.getGpId());
                    }
                    //写入图片库
                    Pictures pictureCover = new Pictures();
                    pictureCover.setPictureUrl(coverUrl);
                    pictureCover.setPictureType(2);
                    pictureCover = picturesService.addPictureAndFlush(pictureCover);
                    //添加新的绑定信息
                    GamePicture gamePictureIcon = new GamePicture();
                    gamePictureIcon.setGpType(2);
                    gamePictureIcon.setGameId(gameInfoForm.getGameId());
                    gamePictureIcon.setPictureId(pictureCover.getPictureId());
                    gamePictureService.addGamePicture(gamePictureIcon);

                    BAddCover = true;

                    map.put("cover", aliyunOSSUtil.addDomainName(pictureCover.getPictureUrl()));
                }
            }
            //轮播图
            List<Pictures> picturesList = new ArrayList<>();
            try {
                for (int i = 0; i < scroll.length; i++) {
                    //获得文件
                    MultipartFile multipartFile = scroll[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, "pictures");
                        //1.向Pictures 添加数据
                        Pictures pictures1 = new Pictures();
                        pictures1.setPictureUrl(pictureUrl);
                        pictures1.setPictureType(0);
                        pictures1 = picturesService.addPictureAndFlush(pictures1);
                        picturesList.add(pictures1);
                        log.info(aliyunOSSUtil.addDomainName(pictures1.getPictureUrl()));

                        BAddCarousel = true;
                    }
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            //1.向gameInfo 添加数据 或者更新数据
            GameInfo gameInfo = new GameInfo();
            if (!StringUtils.isEmpty(gameInfoForm.getGameId())) {
                gameInfo = gameInfoService.findByGameId(gameInfoForm.getGameId(), false);
            } else {
                String _id = KeyUtil.genUniqueKey();
                gameInfoForm.setGameId(_id);
            }
            BeanUtils.copyProperties(gameInfoForm, gameInfo);

            //如果上传的文件存在 uploadUrl != "" coverUrl != ""
            if (BAddIcon)
                gameInfo.setGameIcon(uploadUrl);
            if (BAddCover)
                gameInfo.setGamePicture(coverUrl);

            GameInfo gameInfoTemp = gameInfoService.addGameInfoAndFlush(gameInfo);

            //todo 如果tags更新，先删除旧的tags
            gameTagReferenceService.deleteGameTagByGameId(gameInfoTemp.getGameId());
            List<GameTagReference> gameTagReferenceList = new ArrayList<>();
            for (int i = 0; i < multiselectTag.length; i++) {
                GameTagReference gameTagReference = new GameTagReference();
                gameTagReference.setGameId(gameInfoTemp.getGameId());
                gameTagReference.setTagId(multiselectTag[i]);
                gameTagReference.setStatus(1);
                gameTagReferenceList.add(gameTagReference);

            }
            gameTagReferenceService.saveGameTagReference(gameTagReferenceList);

            List<String> carouselUrlList = new ArrayList();
            //如果轮播图更新，删除旧的数据绑定
            if (BAddCarousel) {
                gamePictureService.deleteAllByTypeAndGameId(0, gameInfoTemp.getGameId());
                log.info("删除轮播图");
                //绑定轮播图 type =0
                for (int i = 0; i < picturesList.size(); i++) {
                    GamePicture gamePictureList = new GamePicture();
                    gamePictureList.setGpType(0);
                    gamePictureList.setGameId(gameInfoTemp.getGameId());
                    gamePictureList.setPictureId(picturesList.get(i).getPictureId());
                    gamePictureService.addGamePicture(gamePictureList);
                    log.info("绑定轮播图");
                    carouselUrlList.add(aliyunOSSUtil.addDomainName(picturesList.get(i).getPictureUrl()));
                }
            } else {
                //查找图片库对应的图片信息
                List<Integer> pictureIdList = gamePictureService.findGamePictureIDList(gameInfoTemp.getGameId());
                List<Pictures> getPicturesList = picturesService.findAllByPictureIdList(pictureIdList);
                for (Pictures item : getPicturesList) {
                    log.info("=={}", item);
                    if (item.getPictureType().equals(0)) {
                        carouselUrlList.add(item.getPictureUrl());
                    } else if (item.getPictureType().equals(1)) {
//                        map.put("icon", item);
                        log.info("数据库的icon={}", item);
                    } else if (item.getPictureType().equals(2)) {
//                        map.put("cover", item);
                        log.info("数据库的cover={}", item);

                    }
                }
            }

            if (!StringUtils.isEmpty(gameInfoTemp.getGameIcon()))
                gameInfoTemp.setGameIcon(aliyunOSSUtil.addDomainName(gameInfoTemp.getGameIcon()));
            if (!StringUtils.isEmpty(gameInfoTemp.getGamePicture()))
                gameInfoTemp.setGamePicture(aliyunOSSUtil.addDomainName(gameInfoTemp.getGamePicture()));

            map.put("gameInfo", gameInfoTemp);

            map.put("carouselUrlList", carouselUrlList);
            //查询所有的类目
            List<GameCategory> categoryList = gameCategoryService.findAll();
            map.put("categoryList", categoryList);

            //allTags
            List<GameTag> gameTagList = gameTagService.findAll();
            List<MakeGameTagDTO> allCustomTags = gameTagList.stream().map(e -> {
                return new MakeGameTagDTO(e.getId(), e.getTitle(), e.getMode(), e.getIsDefault(), false);
            }).collect(Collectors.toList());
            for (int i = 0; i < allCustomTags.size(); i++) {
                for (int j = 0; j < multiselectTag.length; j++) {
                    if (allCustomTags.get(i).getTagId() == multiselectTag[j]) {
                        allCustomTags.get(i).setTagSelect(true);
                    }
                }
            }
            map.put("allCustomTags", allCustomTags);

            return new ModelAndView("/game/detail", map);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (!contextPath.equals("")) {
                imageUtils.deleteImage(contextPath);
            }
            if (uploadIconFile != null)
                uploadIconFile.delete();
            if (uploadCoverFile != null)
                uploadCoverFile.delete();
            if (uploadCarouselFile != null)
                uploadCarouselFile.delete();
        }

        map.put("msg", "游戏数据更新失败！");
        map.put("url", "/backstage_game/detail");
        return new ModelAndView("common/error", map);
    }


    @PostMapping("/upload_new_game")
    public ResultVO uploadNewGame(@Valid GameInfoForm gameInfoForm) {

        //1.向gameInfo 添加数据
        GameInfo gameInfo = new GameInfo();
        if (!StringUtils.isEmpty(gameInfoForm.getGameId())) {
            gameInfo = gameInfoService.findByGameId(gameInfoForm.getGameId(), false);
            if (gameInfo == null) {
                return ResultVOUtil.error(GameEnum.NOT_GAME_INFO.getCode(), GameEnum.NOT_GAME_INFO.getMessage());
            }
        } else {
            String _id = KeyUtil.genUniqueKey();
            gameInfoForm.setGameId(_id);
        }

        BeanUtils.copyProperties(gameInfoForm, gameInfo);
        gameInfo.setGameIcon("");
        gameInfo.setGamePicture("");

        if (StringUtils.isEmpty(gameInfo.getCreateTime())) {
            ResultVOUtil.error(GameEnum.NOT_TIME_INFO.getCode(), GameEnum.NOT_TIME_INFO.getMessage());
        }
        GameInfo gameInfoTemp = gameInfo;//gameInfoService.addGameInfoAndFlush(gameInfo);
        Map<String, Object> map = new HashMap<>();
        map.put("gameInfo", gameInfoTemp);
        //查询所有的类目
        List<GameCategory> categoryList = gameCategoryService.findAll();
        map.put("categoryList", categoryList);

        return ResultVOUtil.success(map);
    }

    /**
     * 查看封面图片
     *
     * @param gameId
     * @param req
     * @param map
     * @return
     */
    @GetMapping("/scrollPictures")
    public ModelAndView scrollPictures(@RequestParam(value = "gameId") String gameId,
                                       @RequestParam(value = "page", defaultValue = "1") Integer page,
                                       @RequestParam(value = "size", defaultValue = "10") Integer size,
                                       HttpServletRequest req,
                                       Map<String, Object> map) {

        PageRequest request = PageRequest.of(page - 1, size);
        Page<GamePicture> gamePictures = gamePictureService.findGamePictureByGameId(gameId, request);

        //根据pictureId 查找对应的图片信息


        map.put("gamePictures", gamePictures);
        map.put("gameId", gameId);
        map.put("currentPage", page);
        map.put("size", size);
        return new ModelAndView("/game/scrollPictureList", map);
    }

    @PostMapping("/bindPicture")
    public ModelAndView bindPicture(@RequestParam("pictureId") Integer pictureId,
                                    @RequestParam("gameId") String gameId,
                                    @RequestParam(value = "page", defaultValue = "1") Integer page,
                                    @RequestParam(value = "size", defaultValue = "10") Integer size,
                                    Map<String, Object> map) {

        if (StringUtils.isEmpty(pictureId)) {
            map.put("msg", "图片id不能为空，参考图片列表");
            map.put("url", "/backstage_game/scrollPictures?gameId=" + gameId);
            return new ModelAndView("common/error", map);
        }
        Pictures pictures = picturesService.findById(pictureId);
        if (StringUtils.isEmpty(pictures)) {
            map.put("msg", "图片id不存在，参考图片列表");
            map.put("url", "/backstage_game/scrollPictures?gameId=" + gameId);
            return new ModelAndView("common/error", map);
        }

        GamePicture gamePicture = new GamePicture();
        gamePicture.setGameId(gameId);
        gamePicture.setPictureId(pictureId);
        gamePicture.setGpType(0);
        gamePictureService.addGamePicture(gamePicture);

        PageRequest request = PageRequest.of(page - 1, size);
        Page<GamePicture> gamePictures = gamePictureService.findGamePictureByGameId(gameId, request);

        map.put("gamePictures", gamePictures);
        map.put("gameId", gameId);
        map.put("currentPage", page);
        map.put("size", size);
        map.put("pictureId", pictureId);
        return new ModelAndView("/game/scrollPictureList", map);
    }

    //unBindPicture
    @GetMapping("/unBindPicture")
    public ModelAndView unBindPicture(@RequestParam("gpId") Integer gpId,
                                      @RequestParam("gameId") String gameId,
                                      @RequestParam(value = "page", defaultValue = "1") Integer page,
                                      @RequestParam(value = "size", defaultValue = "10") Integer size,
                                      Map<String, Object> map) {


        gamePictureService.deleteGamePictureByGpId(gpId);

        PageRequest request = PageRequest.of(page - 1, size);
        Page<GamePicture> gamePictures = gamePictureService.findGamePictureByGameId(gameId, request);

        map.put("gamePictures", gamePictures);
        map.put("gameId", gameId);
        map.put("currentPage", page);
        map.put("size", size);
        return new ModelAndView("/game/scrollPictureList", map);
    }


//    @PostMapping("/delete")
//    public ResultVO delete(@RequestParam(value = "gameId") String gameId,
//                           Map<String, Object> map) {
//
//        //1.向gameInfo 添加数据
//        log.info("删除的游戏id：" + gameId);
//        String str = gameInfoService.deleteByGameId(gameId);
//        map.put("msg", str);
//        return ResultVOUtil.success(map);
//
//    }

    @PostMapping("/upload_folder")
    public ResultVO uploadFolder(@RequestParam("folder") MultipartFile folder) {

        String uploadFilePath = "D:/testUploadFolder";

        String fileName = folder.getOriginalFilename();  // 文件名
        File dest = new File(uploadFilePath + '/' + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            folder.transferTo(dest);
        } catch (Exception e) {
            return ResultVOUtil.error(901, "程序错误，请重新上传");
        }
        return ResultVOUtil.success();
    }

}
