package com.yunzhi.marketing.xlk.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunzhi.marketing.base.BaseController;
import com.yunzhi.marketing.base.ResponseBean;
import com.yunzhi.marketing.common.StringUtils;
import com.yunzhi.marketing.entity.TaBuilding;
import com.yunzhi.marketing.entity.TaPerson;
import com.yunzhi.marketing.service.ITaBuildingService;
import com.yunzhi.marketing.xlk.dto.SearchHouseDTO;
import com.yunzhi.marketing.xlk.dto.VideoDTO;
import com.yunzhi.marketing.xlk.entity.Brand;
import com.yunzhi.marketing.xlk.entity.SearchHouse;
import com.yunzhi.marketing.xlk.entity.Video;
import com.yunzhi.marketing.xlk.service.IVideoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
    * 视频表  前端控制器
    * </p>
 *
 * @author jobob
 * @since 2021-05-18
 */
@RestController
@RequestMapping("/api")
@Api(value = "视频表", tags = "xlk-视频表")
public class VideoController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(VideoController.class);

    @Autowired
    public IVideoService iVideoService;

    @Autowired
    private ITaBuildingService taBuildingService;


    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "admin-视频列表", notes = "admin-视频列表")
    @RequestMapping(value="/admin/video",method= RequestMethod.GET)
    public ResponseBean videoList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                  @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                  @RequestParam(value ="name",required = false) String name,
                                  @RequestHeader("authorization") String token, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
		    IPage<Video> pg = new Page<>(pageNum, pageSize);
            LambdaQueryWrapper<Video> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(!StringUtils.isEmpty(name),Video::getName,name);
            queryWrapper.eq(Video::getOrgId,getOrgId(request));
            queryWrapper.orderByDesc(Video::getWeight);
            queryWrapper.orderByDesc(Video::getCreatedTime);

            IPage<Video> result = iVideoService.page(pg, queryWrapper);
            List<Video> records = result.getRecords();
            records.forEach(e -> {
                TaBuilding building = taBuildingService.getById(e.getBuildingId());
                if (null != building) {
                    e.setBuildingName(building.getBuildingName());
                }
            });
            responseBean.addSuccess(result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("videoList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 保存对象
     * @param videoDTO 实体对象
     * @return
     */
    @ApiOperation(value = "admin-添加视频", notes = "admin-添加视频")
    @RequestMapping(value="/admin/video",method= RequestMethod.POST)
    public ResponseBean videoAdd(@RequestBody VideoDTO videoDTO, @RequestHeader("authorization") String token, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            Video video = new Video();
            BeanUtils.copyProperties(videoDTO,video);
            video.setCreatedTime(LocalDateTime.now());
            video.setCreatedBy(getUserId(request));
            video.setOrgId(getOrgId(request));
            if (iVideoService.save(video)){
                responseBean.addSuccess(video);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("videoAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     */
    @ApiOperation(value = "admin-根据id删除视频", notes = "admin-根据id删除视频")
    @ResponseBody
    @RequestMapping(value="/admin/video/{id}", method= RequestMethod.DELETE)
    public ResponseBean videoDelete(@PathVariable String id,@RequestHeader("authorization") String token){
        ResponseBean responseBean = new ResponseBean();
        try {
            if(iVideoService.removeById(id)){
                responseBean.addSuccess("success");
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("videoDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 修改对象
     * @param id  实体ID
     * @param videoDTO 实体对象
     * @return
     */
    @ApiOperation(value = "admin-根据id修改视频", notes = "admin-根据id修改视频")
    @RequestMapping(value="/admin/video/{id}",method= RequestMethod.PUT)
    public ResponseBean videoUpdate(@PathVariable String id,
                                        @RequestBody VideoDTO videoDTO,@RequestHeader("authorization") String token){
        ResponseBean responseBean = new ResponseBean();
        try {
            Video video = new Video();
            BeanUtils.copyProperties(videoDTO,video);
            video.setVideoId(id);
            if (iVideoService.updateById(video)){
                responseBean.addSuccess(video);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("videoUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @ApiOperation(value = "admin-根据id查询详情", notes = "admin-根据id查询详情")
    @RequestMapping(value="/admin/video/{id}",method= RequestMethod.GET)
    public ResponseBean videoGet(@PathVariable String id,@RequestHeader("authorization") String token){
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(iVideoService.getById(id));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("videoDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 修改对象
     * @param id  实体ID
     * @return
     */
    @ApiOperation(value = "admin-根据id发布或取消发布视频", notes = "admin-根据id发布或取消发布视频")
    @RequestMapping(value="/admin/publish/{id}",method= RequestMethod.PUT)
    public ResponseBean publishVideo(@PathVariable String id,@RequestHeader("authorization") String token){
        ResponseBean responseBean = new ResponseBean();
        try {
            Video video = iVideoService.getById(id);
            video.setIsPublish(!video.getIsPublish());
            if (iVideoService.updateById(video)){
                responseBean.addSuccess(video);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("videoUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }


    /**
     * 保存对象
     * @param
     * @return
     */
    @ApiOperation(value = "wx-查询视频详情", notes = "wx-查询视频详情")
    @GetMapping(value="/wx/detail/{id}")
    public ResponseBean searchHouseAdd(@PathVariable String id, @RequestHeader("authorization") String token, HttpServletRequest request){
        Video video = iVideoService.getById(id);
        if (null == video.getLookNum()){
            video.setLookNum(1);
        }else {
            video.setLookNum(video.getLookNum() + 1);
        }
        iVideoService.updateById(video);
        return ResponseBean.success(video);
    }

}
