package com.yeejoin.equipmanage.controller;

import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.equipmanage.common.entity.Video;
import com.yeejoin.equipmanage.common.entity.dto.VideoDTO;
import com.yeejoin.equipmanage.common.entity.dto.VideoSaveDto;
import com.yeejoin.equipmanage.common.entity.vo.PageVideoVO;
import com.yeejoin.equipmanage.common.entity.vo.VideoListVo;
import com.yeejoin.equipmanage.common.enums.ExcelEnums;
import com.yeejoin.equipmanage.common.utils.CommonResponseUtil;
import com.yeejoin.equipmanage.dto.ExcelDto;
import com.yeejoin.equipmanage.service.IExcelService;
import com.yeejoin.equipmanage.service.IVideoService;
import com.yeejoin.equipmanage.utils.ExcelUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @author ZeHua Li
 * @date 2020/11/23 15:29 * @since v2.0
 */
@RestController
@Api(tags = "视频信息Api")
@Slf4j
@RequestMapping(value = "/video", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class VideoController extends AbstractBaseController {

    @Autowired
    IVideoService videoService;

    @Autowired
    private IExcelService excelService;

    /**
     * 新增
     *
     * @return
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "新增", notes = "新增")
    public Video saveVideo(@RequestBody VideoSaveDto video) {
        Video video1 = video.getVideo();

        if (StringUtils.isNotEmpty(video1.getAddress())) {
            String[] addressData = video1.getAddress().split("@address@");
            if (addressData.length > 1) {
                video1.setAddress(addressData[0]);
                JSONObject langLatObj = JSON.parseObject(addressData[1]);
                if (StringUtils.isNotEmpty(langLatObj.getString("longitude"))) {
                    video1.setLongitude(Double.valueOf(langLatObj.getString("longitude")));
                }
                if (StringUtils.isNotEmpty(langLatObj.getString("latitude"))) {
                    video1.setLatitude(Double.valueOf(langLatObj.getString("latitude")));
                }
                video.setVideo(video1);
            }
        }
        return videoService.saveVideo(video);
    }

    /**
     * 修改
     *
     * @return
     */
    @RequestMapping(value = "/exit", method = RequestMethod.POST)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "修改", notes = "修改")
    public Video updateVideo(@RequestBody VideoSaveDto video) {

        Video video1 = video.getVideo();
        if (StringUtils.isNotEmpty(video1.getAddress())) {
            String[] addressData = video1.getAddress().split("@address@");
            if (addressData.length > 1) {
                video1.setAddress(addressData[0]);
                JSONObject langLatObj = JSON.parseObject(addressData[1]);
                if (StringUtils.isNotEmpty(langLatObj.getString("longitude"))) {
                    video1.setLongitude(Double.valueOf(langLatObj.getString("longitude")));
                }
                if (StringUtils.isNotEmpty(langLatObj.getString("latitude"))) {
                    video1.setLatitude(Double.valueOf(langLatObj.getString("latitude")));
                }
                video.setVideo(video1);
            }
        }
        return videoService.updateVideo(video);
    }

    /**
     * 删除
     *
     * @return
     */
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "删除", notes = "删除")
    public Boolean deleteVideo(@RequestBody List<Long> ids) {
        return videoService.delVideo(ids);
    }

    /**
     * 分页查询
     *
     * @return
     */
    @RequestMapping(value = "/page", method = RequestMethod.POST)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "分页查询", notes = "分页查询")
    public Page<PageVideoVO> pageVideo(@RequestBody VideoDTO video) {
        return videoService.pageVideo(video);
    }

    /**
     * 分页查询
     *
     * @return
     */
    @RequestMapping(value = "/pageList", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "app分页查询", notes = "app分页查询")
    public Page<PageVideoVO> pageVideo(@RequestParam Integer current,
                                       @RequestParam Integer size,
                                       @RequestParam String code,
                                       @RequestParam String name,
                                       @RequestParam String typeCode) {
        VideoDTO videoDTO = new VideoDTO();
        Page page = new Page();
        page.setSize(size);
        page.setCurrent(current);
        videoDTO.setPage(page);
        Video video = new Video();
        video.setName(name);
        video.setCode(code);
        video.setTypeCode(typeCode);
        videoDTO.setVideo(video);
        return videoService.pageVideo(videoDTO);
    }


    /**
     * 根据类型查询视频
     *
     * @return
     */
    @RequestMapping(value = "/listByType/{type}", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据类型查询视频", notes = "根据类型查询视频")
    public ResponseModel<List> listByType(@PathVariable(value = "type") String type) {
        return CommonResponseUtil.success(videoService.listByType(type));
    }


    /**
     * 视频分页资源查询
     *
     * @return
     */
    @RequestMapping(value = "/pageVideo", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "视频分页资源查询", notes = "视频分页资源查询")
    public ResponseModel<Page<VideoListVo>> pageVideo(Integer pageNum, Integer pageSize, Double longitude, Double latitude, Double distance) {

        if (null == pageNum || null == pageSize) {
            pageNum = 1;
            pageSize = Integer.MAX_VALUE;
        } else {
            pageNum = (pageNum - 1) * pageSize;
        }
        List<VideoListVo> listVos = videoService.pageVideoList(pageNum, pageSize, longitude, latitude, distance);
        int num = videoService.pageVideoCount(longitude, latitude, distance);
        Page<VideoListVo> pageBean = new Page<>(pageNum, pageSize);
        pageBean.setRecords(listVos);
        pageBean.setTotal(num);
        return CommonResponseUtil.success(pageBean);
    }


    /**
     * 详情
     *
     * @return
     */
    @GetMapping(value = "/getByid")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "详情", notes = "详情")
    public Video getByid(Long id) {
        return videoService.getById(id);

    }


    /**
     * 详情
     *
     * @return
     */
    @GetMapping(value = "/detail")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "详情", notes = "详情")
    public VideoSaveDto detail(Long id) {
        return videoService.detail(id);

    }

    /**
     * 监控模板下载
     *
     * @return
     */
    @GetMapping(value = "/downList")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "下载模板", notes = "下载模板")
    public void downList(HttpServletResponse response) throws ClassNotFoundException {
        ExcelEnums excelEnums = ExcelEnums.getByKey(ExcelEnums.JKXX.getType());
        ExcelDto excelDto = new ExcelDto(excelEnums.getFileName(), excelEnums.getSheetName(), excelEnums.getClassUrl(), excelEnums.getType());
        String url = excelDto.getClassUrl();
        Class<?> clz = Class.forName(url);
        ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), null, clz, getToken(),
                getAppKey(), getProduct(), false);
    }

    /**
     * 监控信息导入
     *
     * @return
     */
    @PostMapping(value = "/uploadList")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "导入", notes = "导入")
    public boolean uploadList(MultipartFile file) {

        ExcelEnums excelEnums = ExcelEnums.getByKey(ExcelEnums.JKXX.getType());
        ExcelDto excelDto = new ExcelDto(excelEnums.getFileName(), excelEnums.getSheetName(), excelEnums.getClassUrl(), excelEnums.getType());
        try {
            excelService.commonUpload(file, excelDto, getSelectedOrgInfo(), getUserInfo());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new BadRequest(e.getMessage());
        }
        return true;
    }

    /**
     * 通过视频id和预置位获取可播放的flv格式地址
     *
     * @param videoId
     * @param presetIndex
     * @return
     */
    @RequestMapping(value = "/getVideoFlvUrl", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "通过视频id和预置位获取可播放的flv格式地址", notes = "通过视频id和预置位获取可播放的flv格式地址")
    public String getVideoFlvUrl(@RequestParam String videoId,
                                 @RequestParam String presetIndex) {
        String flvUrl = videoService.getVideoUrl(videoId, presetIndex, "");
        return flvUrl;
    }

}
