package com.yunzhi.marketing.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yunzhi.marketing.base.BaseController;
import com.yunzhi.marketing.base.ResponseBean;
import com.yunzhi.marketing.common.CommConstant;
import com.yunzhi.marketing.common.StringUtils;
import com.yunzhi.marketing.entity.ExtendContent;
import com.yunzhi.marketing.entity.TaLiveActivity;
import com.yunzhi.marketing.po.LiveAndVideoVO;
import com.yunzhi.marketing.reportCustomerAop.ReportCustomer;
import com.yunzhi.marketing.service.IExtendContentService;
import com.yunzhi.marketing.service.ITaLiveActivityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jobob
 * @since 2020-02-20
 */
@RestController
@RequestMapping("/api")
@Api(value = "直播活动", tags = "xlk-直播活动")
public class TaLiveActivityController extends BaseController {

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

    @Autowired
    public ITaLiveActivityService iTaLiveActivityService;

    @Autowired
    public IExtendContentService iExtendContentService;

    /**
     * 分页查询列表
     *
     * @param pageNum
     * @param pageSize
     * @param liveActivityTitle 直播活动标题
     * @param cityId            所属城市
     * @param buildingId        所属楼盘
     * @param liveDetailType    详情类型 0是模板，1是自定义
     * @param status            状态
     * @param source            查询来源，1:直播等活动，2:开屏广告
     * @param request
     * @return
     */
    @RequestMapping(value = "/admin/taLiveActivity", method = RequestMethod.GET)
    public ResponseBean taLiveActivityList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                           @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                           String liveActivityTitle,
                                           String cityId,
                                           String buildingId,
                                           Integer status,
                                           @RequestParam(value = "source", defaultValue = "1") Integer source,
                                           HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            IPage<TaLiveActivity> result = iTaLiveActivityService.listLiveActivityByCondition(pageNum, pageSize, getOrgId(request),
                    liveActivityTitle, cityId, buildingId, status, getTaPersonBuildingListByUserId(request), getUserId(request), source);
            responseBean.addSuccess(result);

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taLiveActivityList -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 保存对象
     *
     * @param taLiveActivity 实体对象
     * @return
     */
    @RequestMapping(value = "/admin/taLiveActivity", method = RequestMethod.POST)
    public ResponseBean taLiveActivityAdd(@RequestBody TaLiveActivity taLiveActivity, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            Integer orgId = getOrgId(request);
            Integer userId = getUserId(request);
            taLiveActivity.setOrgId(orgId);
            taLiveActivity.setCreateUser(userId.toString());
            taLiveActivity.setUpdateUser(userId.toString());
            responseBean = iTaLiveActivityService.taLiveActivityAdd(taLiveActivity);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taLiveActivityAdd -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id删除对象
     *
     * @param id 实体ID
     */
    @ResponseBody
    @RequestMapping(value = "/admin/delTaLiveActivity", method = RequestMethod.PUT)
    public ResponseBean taLiveActivityDelete(@RequestBody List<TaLiveActivity> taLiveActivity, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            List<Integer> liveActivityIds = new ArrayList<>();
            for (TaLiveActivity activity : taLiveActivity) {
                liveActivityIds.add(activity.getLiveActivityId());
            }
            QueryWrapper<ExtendContent> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("org_id", getOrgId(request));
            queryWrapper.eq("content_type", CommConstant.LIVE);
            queryWrapper.in("target_id", liveActivityIds);
            List<ExtendContent> list = iExtendContentService.list(queryWrapper);
            list.forEach(e -> {
                e.setStatus(CommConstant.NOT_PUBLISH);
            });
            if (list.size() > 0) {
                iExtendContentService.updateBatchById(list);
            }

            responseBean = iTaLiveActivityService.delLiveActivityList(getOrgId(request), taLiveActivity);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taLiveActivityDelete -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 修改对象
     *
     * @param id             实体ID
     * @param taLiveActivity 实体对象
     * @return
     */
    @RequestMapping(value = "/admin/taLiveActivity/{id}", method = RequestMethod.PUT)
    public ResponseBean taLiveActivityUpdate(@PathVariable Integer id,
                                             @RequestBody TaLiveActivity taLiveActivity, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            taLiveActivity.setLiveActivityId(id);
            taLiveActivity.setUpdateUser(getUserId(request).toString());
            QueryWrapper<ExtendContent> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("org_id", getOrgId(request));
            queryWrapper.eq("content_type", CommConstant.LIVE);
            queryWrapper.eq("target_id", taLiveActivity.getLiveActivityId());
            List<ExtendContent> list = iExtendContentService.list(queryWrapper);
            if (CommConstant.NOT_PUBLISH.equals(taLiveActivity.getStatus())) {
                list.forEach(e -> {
                    e.setStatus(CommConstant.NOT_PUBLISH);
                });
            }
            if (list.size() > 0) {
                iExtendContentService.updateBatchById(list);
            }

            if (!StringUtils.isEmpty(taLiveActivity.getLiveRoomParam())) {
                taLiveActivity.setLiveAppPath(taLiveActivity.getLiveRoomParam().replace(".html", ""));
            }

            if (iTaLiveActivityService.updateById(taLiveActivity)) {
                responseBean.addSuccess(taLiveActivity);
            } else {
                responseBean.addError("fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taLiveActivityUpdate -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     *
     * @param id 实体ID
     */
    @RequestMapping(value = "/admin/taLiveActivity/{id}", method = RequestMethod.GET)
    public ResponseBean taLiveActivityGet(@PathVariable Integer id) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(iTaLiveActivityService.getDetailById(id));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taLiveActivityDelete -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 访问量自增
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/wx/addVisitNum", method = RequestMethod.PUT)
    public ResponseBean addVisitNum(@RequestParam("id") String id) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaLiveActivityService.addVisitNum(id);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("addVisitNum -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 获取直播详情
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/wx/taLiveActivity/{id}", method = RequestMethod.GET)
    @ReportCustomer(type = "live")
    public ResponseBean getLiveActivityDetailById(@PathVariable("id") String id,
                                                  @RequestParam(value = "qrCodeId", required = false) String qrCodeId,
                                                  @RequestParam(value = "channelId", required = false) String channelId,
                                                  @RequestParam(value = "sceneId", required = false) String sceneId,
                                                  HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaLiveActivityService.getLiveActivityDetailById(id, getOrgId(request));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("getLiveActivityDetailById -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 分页查询列表
     *
     * @param pageNum
     * @param pageSize
     * @param liveActivityTitle 直播活动标题
     * @param cityId            所属城市
     * @param buildingId        所属楼盘
     * @param status            状态
     * @param request
     * @return
     */
    @ApiOperation(value = "wx-视频直播列表", notes = "admin-视频直播列表")
    @RequestMapping(value = "/wx/taLiveActivity", method = RequestMethod.GET)
    public ResponseBean taLiveActivityListForMiniApp(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                     @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                     String liveActivityTitle,
                                                     String cityId,
                                                     String buildingId,
                                                     Integer status,
                                                     @RequestParam(value = "source", defaultValue = "1") Integer source,
                                                     @RequestParam(value = "name", required = false) String name,
                                                     HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            status = status == null ? 1 : status;
            Integer orgId = getOrgId(request);
            IPage<LiveAndVideoVO> result = iTaLiveActivityService.getWxLiveActivityAndVideo(pageNum, pageSize, orgId,
                    liveActivityTitle, cityId, buildingId, status, name, source);
            responseBean.addSuccess(result);

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taLiveActivityListForMiniApp -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
}
