package com.platform.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.platform.annotation.CanUserUpdateRecord;
import com.platform.entity.Result;
import com.platform.entity.TmLiveRoomInfo;
import com.platform.entity.WxLiveRoomRequestVo;
import com.platform.enums.LiveRoomStatusEnum;
import com.platform.enums.ResultCodeEnum;
import com.platform.exception.CommonBaseException;
import com.platform.service.custom.LiveRoomInfoService;
import com.platform.utils.*;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author abnerhou
 * @date 2020/9/14 9:44
 * @desciption
 */
@Api(tags = "管理后台直播间相关接口")
@RestController
@RequestMapping("/liveRoom")
@Slf4j
public class TmLiveRoomController extends AbstractController{

    @Value("${file-backup-path}")
    private String imageLocalBackupPath;



    @Autowired
    LiveRoomInfoService liveRoomInfoService;

    @Autowired
    OssCheckPointUploadUtil ossCheckPointUploadUtil;

    @CanUserUpdateRecord
    @ApiOperation(value = "新增直播间")
    @PostMapping(value = "/add")
    
    @ResponseBody
    public Object addNewLiveRoom(@ApiParam(name = "TmLiveRoomInfo对象", value = "传入json格式", required = true) @RequestBody TmLiveRoomInfo tmLiveRoomInfo) {

        if(null == tmLiveRoomInfo){
            return Result.failure("入参缺失");
        }

        if(null == tmLiveRoomInfo.getCreateUserId() || null == tmLiveRoomInfo.getCreateUserDeptId()){
            return Result.failure("缺失创建者信息");
        }

        if(!StringUtils.isNoneBlank(tmLiveRoomInfo.getName() , tmLiveRoomInfo.getAnchorName())){
            return Result.failure("直播间名称或者主播名称不能为空");
        }
        if(null == tmLiveRoomInfo.getStartTime() || null == tmLiveRoomInfo.getEndTime()){
            return Result.failure("直播起始时间不能为空");
        }

        log.info("开始时间:{}" , tmLiveRoomInfo.getStartTime());
        log.info("结束时间:{}" , tmLiveRoomInfo.getEndTime());
        WxLiveRoomRequestVo wxLiveRoomRequestVo = new WxLiveRoomRequestVo();
        BeanUtils.copyProperties(tmLiveRoomInfo , wxLiveRoomRequestVo);
        log.info("上送给微信创建直播间的数据为:{}" , JSON.toJSONString(wxLiveRoomRequestVo));
        JSONObject wxLiveRoomRspVo = WxOpUtils.creatLiveRoom(wxLiveRoomRequestVo ,  ResourceUtil.getConfigByName("wx.appId") ,
                ResourceUtil.getConfigByName("wx.secret"));
        if(null == wxLiveRoomRspVo){
            log.error("解析微信返回值失败，调用微信创建直播间失败");
            return Result.failure("解析微信返回值失败");
        }
        log.info("微信返回报文为:{}" , wxLiveRoomRspVo.toJSONString());
        Integer errcode = wxLiveRoomRspVo.getInteger("errcode");
        if(null == errcode || 0 != errcode){
            log.error("调用微信创建直播间失败");
            return wxLiveRoomRspVo.toJSONString();
        }
        log.info("调用调用微信创建直播间成功");
        Integer roomId = wxLiveRoomRspVo.getInteger("roomId");
        tmLiveRoomInfo.setRoomId(roomId.longValue());
        tmLiveRoomInfo.setLiveStatus(LiveRoomStatusEnum.NOT_START.getStatus());
        int insert = liveRoomInfoService.addNew(tmLiveRoomInfo);
        if(insert != 1){
            log.error("新增微信直播间记录失败");
        }
        return wxLiveRoomRspVo;
     }

    @CanUserUpdateRecord
    @ApiOperation(value = "上传照片")
    @PostMapping(value = "/uploadImage")
    @ResponseBody
    public Object uploadImage(@RequestParam("file") CommonsMultipartFile file){
        if (null == file) {
            throw new CommonBaseException(ResultCodeEnum.D3001);
        }
        String fileName = file.getOriginalFilename();
        String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
        //保存本地照片
        String newFileName = getRandomName(prefix);
        String imageLocalPath = ResourceUtil.getConfigByName("file-backup-path") + newFileName;
        log.info("照片本地缓存路径:{}" , imageLocalPath);
        File newFile = new File(imageLocalPath);
        long size = file.getSize();
        if(size > 500000L){
            //在这里将图片压缩
            try {
                Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.2f).toFile(imageLocalPath);
            } catch (IOException e) {
                e.printStackTrace();
                return Result.failure("压缩照片失败");
            }
            newFile = new File(imageLocalPath);
            if(null == newFile){
                log.error("压缩照片[{}]失败" , file.getOriginalFilename());
                return "";
            }

        }else{
            log.info("照片大小小于500kb，不压缩");
            try {
                file.transferTo(newFile);
            } catch (IOException e) {
                log.info("本地缓存照片出现异常:{}" , e);
                return Result.failure("本地缓存照片出现异常");
            }
        }
        String mediaId = WxOpUtils.uploadMedia("image" , newFile ,  ResourceUtil.getConfigByName("wx.appId"),
                ResourceUtil.getConfigByName("wx.secret"));
        log.info("微信返回:{}" , mediaId);


        String ossPath =  ResourceUtil.getConfigByName("oss.image.file.path") + newFileName;
        log.info("生成的照片上传oss的路径:{}" , ossPath);
        ossCheckPointUploadUtil.upload2(imageLocalPath, ossPath);
        String imageTotalOssUrl = ResourceUtil.getConfigByName("oss.query.url") + ossPath;
        Map<String ,Object> mp = new HashMap<>();
        mp.put("mediaId" , mediaId);
        mp.put("ossUrl" , imageTotalOssUrl);
        return Result.success(mp);
    }

    /**
     * 文件路径
     *
     * @param prefix 前缀
     * @return 返回上传路径
     */
    public String getRandomName(String prefix) {
        //生成uuid
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //文件路径
        return DateUtils.format(new Date(), "yyyyMMddHHmmssS") + uuid.substring(0, 5) + "." + prefix;

    }

    @ApiOperation(value = "获取直播间列表")
    @GetMapping(value = "/getRoomList")
    
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", paramType = "query", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "limit", value = "每页大小", paramType = "query", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "name", value = "搜索关键字名称", paramType = "query", required = true, dataType = "String")
    })
    public Object getLiveRoomList(String name , @RequestParam(name = "page") long page ,
                                  @RequestParam(name = "limit") long limit){

        IPage<TmLiveRoomInfo> resultPage = new Page<>();
        if(null == getUserId() || null == getDeptId()){
            return Result.failure("缺失用户信息");
        }
        resultPage  = liveRoomInfoService.getOrQuery(name, page , limit , getUserId() , getCompanyId(),getUser());
        if(resultPage != null){
           return CommonDataUtils.toResponsObject(0,"" , CommonDataUtils.assembleResultCustom(resultPage.getTotal() , resultPage.getPages() ,
                    resultPage.getCurrent() ,limit , resultPage.getRecords()));
        }

        return Result.success();
    }

    @CanUserUpdateRecord
    @ApiOperation(value = "更新直播间数据-主要是删除,enable=0即为删除")
    @PostMapping(value = "/update")
    
    @ResponseBody
    public Object updateRoomInfo(@ApiParam(name = "TmLiveRoomInfo对象", value = "传入json格式", required = true)
                                     @RequestBody TmLiveRoomInfo tmLiveRoomInfo){

        if(null == tmLiveRoomInfo){
            return Result.failure("入参缺失");
        }
        if(null == tmLiveRoomInfo.getUpdateUserId()){
            return Result.failure("更新者信息缺失");
        }
        if(StringUtils.isBlank(tmLiveRoomInfo.getLiveId())){
            return Result.failure("liveId缺失");
        }
        int update = liveRoomInfoService.updateLiveRoom(tmLiveRoomInfo);
        if(update != 1){
            log.error("直播间liveId=[{}]更新失败" , tmLiveRoomInfo.getLiveId());
            return Result.failure("更新失败");
        }
        return Result.success();
    }
    
}
