package com.YuyeTech.HeartRate.game.imageInfo.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.AliyunConfig;
import com.YuyeTech.HeartRate.game.gameInfo.service.GamePictureService;
import com.YuyeTech.HeartRate.game.gameInfo.vo.GamePictureSimpleVo;
import com.YuyeTech.HeartRate.game.gameInfo.vo.GamePictureVo;
import com.YuyeTech.HeartRate.game.imageInfo.projo.Pictures;
import com.YuyeTech.HeartRate.game.imageInfo.service.PicturesService;
import com.YuyeTech.HeartRate.game.imageInfo.vo.PicturesAndGameSimpleVo;
import com.YuyeTech.HeartRate.game.imageInfo.vo.PicturesVo;
import com.YuyeTech.HeartRate.utils.AliyunOSSUtil;
import com.YuyeTech.HeartRate.utils.CopyUtil;
import com.YuyeTech.HeartRate.utils.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Map;

/**
 * @author:slambb
 * @date:2020/6/15
 */
@RestController
@RequestMapping("/backstage_picture")
@Slf4j
public class BackstagePictureController {
    @Autowired
    private PicturesService picturesService;
    @Autowired
    private GamePictureService gamePictureService;

    @Autowired
    private AliyunOSSUtil aliyunOSSUtil;

    @Autowired
    private AliyunConfig aliyunConfig;

    /**
     * 前端view跳转,配置菜单路径
     * 设置默认参数
     *
     * @return
     */
    @GetMapping("gotoView")
    public ModelAndView gotoView() {
        //查询所有的类目
        String bucketName = aliyunConfig.getBucketName();
        System.out.println(bucketName);
        List<String> objectList = aliyunOSSUtil.getObjectList(bucketName);
        ModelAndView modelAndView = new ModelAndView("client/imageInfo");
        modelAndView.addObject("ossList", objectList);
        return modelAndView;
    }

    /**
     * 分页查询数据
     *
     * @param vo
     * @return
     */
    @PostMapping("findAll")
    @Decrypt
    @Encrypt
    public Result<PageInfo<PicturesAndGameSimpleVo>> findAll(PicturesVo vo) {
        PageInfo pageInfo = picturesService.pageByClass(vo,PicturesAndGameSimpleVo.class);
        List<PicturesAndGameSimpleVo> list = pageInfo.getRows();
        for (PicturesAndGameSimpleVo simpleVo :list){
            GamePictureVo gamePictureVo = gamePictureService.getVo(simpleVo.getPictureId());
            if(gamePictureVo !=null)
                simpleVo.setGamePicture(CopyUtil.copy(gamePictureVo, GamePictureSimpleVo.class));

        }
        pageInfo.setRows(list);
        return Result.of(pageInfo);
    }


    @PostMapping("/delete")
    @Decrypt
    @Encrypt
    public Result delete(@RequestParam(value = "pictureId") Integer pictureId) {
        picturesService.deletePictureById(pictureId);
        return Result.of(null,true,"删除图片成功");
    }


    @GetMapping("/list")
    @Deprecated
    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 request = PageRequest.of(page - 1, size);
        Page<Pictures> pictures = picturesService.findAllByPageable(request);
        pictures.stream().forEach(e -> {
            e.setPictureUrl(aliyunOSSUtil.addDomainName(e.getPictureUrl()));
        });
        map.put("Pictures", pictures);
        map.put("currentPage", page);
        map.put("size", size);
        return new ModelAndView("/picture/list", map);
    }


    @PostMapping("/upload")
    @Deprecated
    public ModelAndView upload(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "10") Integer size,
            @RequestParam("pictures") MultipartFile pictures,
            Map<String, Object> map) {

        map.put("currentPage", page);
        map.put("size", size);

        //存的项目的中模版图片
        File uploadFile = null;
        try {
            String pitcureUrl = "";
            if (null != pictures) {
                String filename = pictures.getOriginalFilename();
                if (!"".equals(filename.trim())) {
                    uploadFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(uploadFile);
                    os.write(pictures.getBytes());
                    os.close();
                    pictures.transferTo(uploadFile);
                    //上传到OSS
                    pitcureUrl = aliyunOSSUtil.upload(uploadFile, "pictures");
                    //1.向gameInfo 添加数据
                    Pictures pictures1 = new Pictures();
                    pictures1.setPictureUrl(pitcureUrl);
                    pictures1.setPictureType(0);
                    picturesService.addPicture(pictures1);

                    PageRequest request = PageRequest.of(page - 1, size);
                    Page<Pictures> pictures2 = picturesService.findAllByPageable(request);
                    pictures2.stream().forEach(e -> {
                        e.setPictureUrl(aliyunOSSUtil.addDomainName(e.getPictureUrl()));
                    });
                    map.put("Pictures", pictures2);
                    map.put("picture", aliyunOSSUtil.addDomainName(pitcureUrl));
                    return new ModelAndView("/picture/list", map);
                }
            } else {
                map.put("msg", "图片不能为空");
                map.put("url", "/backstage_picture/list");
                return new ModelAndView("common/error", map);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (uploadFile != null)
                uploadFile.delete();
        }

        map.put("msg", "上传图片不成功！");
        map.put("url", "/backstage_picture/list");
        return new ModelAndView("common/error", map);

    }


    @GetMapping("/deletePicture")
    @Deprecated
    public ModelAndView deletePicture(@RequestParam(value = "pictureId") Integer pictureId,
                                      @RequestParam(value = "page", defaultValue = "1") Integer page,
                                      @RequestParam(value = "size", defaultValue = "10") Integer size,
                                      Map<String, Object> map) {
        picturesService.deletePictureById(pictureId);

        map.put("msg", "删除图片！");
        map.put("url", "/backstage_picture/list?currentPage=" + page + "&size=" + size);
        return new ModelAndView("common/success", map);
    }


    @PostMapping("/upload_multiple")
    @Deprecated
    public ResultVO uploadPictures(HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("{}", request);
        //存的项目的中模版图片
        File uploadFile = null;

        //转型为MultipartHttpRequest
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

        List<MultipartFile> fileList = multipartRequest.getFiles("scroll-picture");
        for (int i = 0; i < fileList.size(); i++) {
            //获得文件
            MultipartFile multipartFile = fileList.get(i);
            try {
                String fileName = multipartFile.getOriginalFilename();
                uploadFile = new File(fileName);
                FileOutputStream os = new FileOutputStream(uploadFile);
                os.write(multipartFile.getBytes());
                os.close();
                multipartFile.transferTo(uploadFile);

                //上传到OSS
                String pictureUrl = aliyunOSSUtil.upload(uploadFile, "pictures");

                if (pictureUrl == null) {
                    return ResultVOUtil.error(801, "上传图片不成功！");
                }
                //1.向Pictures 添加数据
                Pictures pictures1 = new Pictures();
                pictures1.setPictureUrl(pictureUrl);
                pictures1.setPictureType(0);
                pictures1 = picturesService.addPictureAndFlush(pictures1);

                log.info(aliyunOSSUtil.addDomainName(pictures1.getPictureUrl()));

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
//            return ResultVOUtil.error(801, "上传图片不成功！");
        }
        return ResultVOUtil.error(800, "上传图片成功！");

    }

    /**
     * 上传处理icon 和 cover，对应type 1,2
     * @param request
     * @return
     */
    @PostMapping("/upload_single_key")
    @Deprecated
    public ResultVO uploadSingleBasedOnKey(
            HttpServletRequest request) {
        log.info("{}",request.getParameter("img_key"));
        String name = request.getParameter("img_key");
        Integer type = 0;
        //这里只处理icon 和封面
        if(name.equals("icon")){
            type =1;
        }else if(name.equals("cover")){
            type =2;
        }else{
            return ResultVOUtil.error(801, "上传图片不成功！");
        }
        //转型为MultipartHttpRequest
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile multiFile = multipartRequest.getFile(name);
        //存的项目的中模版图片
        File uploadFile = null;
        try {
            String pitcureUrl = "";
            if (null != multiFile) {
                String filename = multiFile.getOriginalFilename();
                if (!"".equals(filename.trim())) {
                    uploadFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(uploadFile);
                    os.write(multiFile.getBytes());
                    os.close();
                    multiFile.transferTo(uploadFile);
                    //上传到OSS
                    pitcureUrl = aliyunOSSUtil.upload(uploadFile, "pictures");
                    //1.向gameInfo 添加数据
                    Pictures pictures1 = new Pictures();
                    pictures1.setPictureUrl(pitcureUrl);
                    pictures1.setPictureType(type);
                    pictures1 = picturesService.addPictureAndFlush(pictures1);
                    log.info("{}",pictures1);
                    return ResultVOUtil.success(pictures1);
                }
            } else {
                return ResultVOUtil.error(801, "上传图片不成功！");
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (uploadFile != null)
                uploadFile.delete();
        }

        return ResultVOUtil.error(801, "上传图片不成功！");

    }
}
