package com.yizhi.application.live.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.application.accountUtil.AuthorizeQueryAccount;
import com.yizhi.core.application.enums.InternationalEnums;
import com.yizhi.application.tools.HorseLight;
import com.yizhi.application.util.TaskSendMessage;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.live.application.feign.LiveActivityClient;
import com.yizhi.live.application.feign.LiveReplayClient;
import com.yizhi.live.application.vo.*;
import com.yizhi.site.application.feign.PortalManagePCFeignClients;
import com.yizhi.site.application.vo.domain.RelationLiveVo;
import com.yizhi.system.application.system.remote.AccountClient;
import com.yizhi.system.application.vo.AccountVO;
import com.yizhi.system.application.vo.OrgVO;
import com.yizhi.util.application.domain.BizResponse;
import com.yizhi.util.application.domain.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

@Api(tags = "管理端-直播接口")
@RestController
@RequestMapping("/manage/live")
public class LiveController {

    private static final Logger LOG = LoggerFactory.getLogger(LiveController.class);

    @Autowired
    LiveActivityClient liveActivityClient;

    @Autowired
    AccountClient accountClient;

    @Autowired
    private AuthorizeQueryAccount queryAccount;
    @Autowired
    private TaskSendMessage taskSendMessage;

    @Autowired
    PortalManagePCFeignClients portalManagePCFeignClient;
    @Autowired
    private LiveReplayClient liveReplayClient;


    /*@Autowired
    HorseLight horseLight;*/

    @PostMapping("/save")
    @ApiOperation(value = "直播创建", notes = "直播创建")
    public Response save(@ApiParam(name = "liveActivity", value = "需要的基本参数", required = true) @RequestBody LiveActivityResultVO resultVO) {
        RequestContext requestContext = ContextHolder.get();
        resultVO.getLiveActivity().setCompanyId(requestContext.getCompanyId());
        resultVO.getLiveActivity().setSiteId(requestContext.getSiteId());
        resultVO.getLiveActivity().setOrgId(requestContext.getOrgId());
        resultVO.getLiveActivity().setCreateByName(requestContext.getAccountName());
        resultVO.getLiveActivity().setCreateById(requestContext.getAccountId());
        LOG.info("中台直播创建,携带活动那个参数{},可见范围信息{}", resultVO.getLiveActivity(), resultVO.getScopeAuthorizations());
        Boolean f = liveActivityClient.save(resultVO);
        if (f) {
            return Response.ok();
        } else {
            return Response.fail();
        }
    }

    @PostMapping("/update")
    @ApiOperation(value = "直播修改", notes = "直播修改建")
    public Response update(@ApiParam(name = "LiveActivityResultVO", value = "直播修改vo", required = true)
                           @RequestBody LiveActivityResultVO resultVO) {
        Boolean f = liveActivityClient.update(resultVO);
        if (f) {
            return Response.ok();
        } else {
            return Response.fail();
        }
    }

    @GetMapping("/list")
    @ApiOperation(value = "直播列表", notes = "直播列表", response = PageLiveVo.class)
    public Response list(
            @ApiParam(name = "title", value = "直播主题,直播号,关键词", required = false) @RequestParam(value = "title", required = false) String title,
            @ApiParam(name = "startTime", value = "开始时间", required = false) @RequestParam(value = "startTime", required = false) Date startTime,
            @ApiParam(name = "endTime", value = "结束时间", required = false) @RequestParam(value = "endTime", required = false) Date endTime,
            @ApiParam(name = "pageNo", value = "跳转页数,默认第一页", required = true) @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @ApiParam(name = "pageSize", value = "每页条数,默认20条", required = true) @RequestParam(name = "pageSize", defaultValue = "20") Integer pageSize,
            @ApiParam(name = "expTime", value = "过期时间") @RequestParam(name = "expTime", required = false) Date expTime,
            @ApiParam(name = "status", value = "直播状态") @RequestParam(name = "status", required = false) Integer status,
            @ApiParam(name = "viewType", value = "直播类型:0 公开直播。1：站内直播") @RequestParam(name = "viewType", required = false) Integer viewType,
            @RequestParam(name = "startTimeAsc",required = false) Boolean startTimeAsc,
            @RequestParam(name = "endTimeAsc",required = false) Boolean endTimeAsc) {
        RequestContext requestContext = ContextHolder.get();
        LOG.info("直播列表 查询参数：startTime={},endTime={}", startTime, endTime);

        SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        String startTimeString = null;
        if (startTime != null) {
            startTimeString = sim.format(startTime);
        }

        String endTimeString = null;
        if (endTime != null) {
            endTimeString = sim.format(endTime);
        }

        String expTimeString = null;
        if (expTime != null) {
            expTimeString = sim.format(expTimeString);
        }

        Page<PageLiveVo> page = liveActivityClient.listV2(title, startTimeString, endTimeString, requestContext.getCompanyId(), requestContext.getSiteId(),
                null, pageNo, pageSize, expTimeString, status, viewType,startTimeAsc,endTimeAsc);
        return Response.ok(page);
    }


    @ApiOperation(value = "直播选择列表;代替原来的查询接口，原来的接口保留", notes = "直播选择列表", response = PageLiveVo.class)
    @GetMapping(value = "/portal/v2/list")
    public Response portalListV2(
            @ApiParam(name = "title", value = "直播主题", required = false) @RequestParam(value = "title", required = false) String title,
            @ApiParam(name = "startTime", value = "开始时间", required = false) @RequestParam(value = "startTime", required = false) Date startTime,
            @ApiParam(name = "endTime", value = "结束时间", required = false) @RequestParam(value = "endTime", required = false) Date endTime,
            @ApiParam(name = "pageNo", value = "跳转页数,默认第一页", required = true) @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @ApiParam(name = "pageSize", value = "每页条数,默认20条", required = true) @RequestParam(name = "pageSize", defaultValue = "20") Integer pageSize) {
        RequestContext requestContext = ContextHolder.get();
        Page<PageLiveVo> pageLiveVoPage = liveActivityClient.portalListV2(title, startTime, endTime, requestContext.getCompanyId(), requestContext.getSiteId(),
                requestContext.getOrgIds(), pageNo, pageSize);
        return Response.ok(pageLiveVoPage);
    }

    @ApiOperation(value = "直播选择列表", notes = "直播选择列表", response = PageLiveVo.class)
    @GetMapping(value = "/portal/list")
    public Response portalList(
            @ApiParam(name = "title", value = "直播主题", required = false) @RequestParam(value = "title", required = false) String title,
            @ApiParam(name = "startTime", value = "开始时间", required = false) @RequestParam(value = "startTime", required = false) Date startTime,
            @ApiParam(name = "endTime", value = "结束时间", required = false) @RequestParam(value = "endTime", required = false) Date endTime,
            @ApiParam(name = "pageNo", value = "跳转页数,默认第一页", required = true) @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @ApiParam(name = "pageSize", value = "每页条数,默认20条", required = true) @RequestParam(name = "pageSize", defaultValue = "20") Integer pageSize) {
        RequestContext requestContext = ContextHolder.get();
        List<PageLiveVo> page = liveActivityClient.portalList(title, startTime, endTime, requestContext.getCompanyId(), requestContext.getSiteId(),
                requestContext.getOrgIds(), pageNo, pageSize);
        return Response.ok(page);
    }


    @PostMapping("/delete")
    public Response delete(
            @RequestBody LiveActivityVO liveActivity
    ) {

        try {
            LiveActivityResultVO liveActivityResultVO = liveActivityClient.get(liveActivity.getId());
            Integer shelves = liveActivityResultVO.getLiveActivity().getShelves();
            if (shelves==1){
                return Response.fail(InternationalEnums.LIVECONTROLLER1.getCode());
            }

            Boolean f = liveActivityClient.delete(liveActivity);
            if (f) {
                return Response.ok();
            }
        } catch (Exception e) {
            LOG.error("直播删除异常:{}", e.getMessage());

        }
        return Response.fail();
    }

    @GetMapping("/get")
    @ApiOperation(value = "获取直播详细信息", notes = "直播详细信息", response = LiveActivityResultVO.class)
    public Response list(@RequestParam("id") Long id) {
        LiveActivityResultVO liveActivity = liveActivityClient.get(id);
        if (liveActivity != null) {
            List<ScopeAuthorizationVO> ranges = liveActivity.getScopeAuthorizations();

            if (!CollectionUtils.isEmpty(ranges)) {
                List<Long> accountIds = new ArrayList<>(ranges.size());
                List<Long> orgIds = new ArrayList<>(ranges.size());
                ranges.forEach(a -> {
                    if (a.getType().equals(1)) {
                        orgIds.add(a.getAccountId());
                    } else {
                        accountIds.add(a.getAccountId());
                    }
                });
                Map<Long, AccountVO> accountMap = queryAccount.queryAccountByIds(accountIds);
                Map<Long, OrgVO> orgMap = queryAccount.queryOrgByIds(orgIds);
                ranges.forEach(a -> {
                    if (null != accountMap) {
                        AccountVO accountVO = accountMap.get(a.getAccountId());
                        if (null != accountVO && a.getType().equals(2)) {
                            a.setWorkNum(accountVO.getWorkNum());
                            a.setFullName(accountVO.getFullName());
                            a.setName(accountVO.getName());
                        }
                    }
                    if (null != orgMap) {
                        OrgVO orgVO = orgMap.get(a.getAccountId());
                        if (null != orgVO && a.getType().equals(1)) {
                            a.setName(orgVO.getName());
                        }
                    }
                });
            }
        }
        return Response.ok(liveActivity);
    }

    @ApiOperation(value = "直播token设置", notes = "直播token设置")
    @PostMapping("/token")
    public Response getToken(@RequestBody LiveTokenVo liveTokenVo) {
        RequestContext requestContext = ContextHolder.get();
        liveTokenVo.setCreateById(requestContext.getAccountId());
        liveTokenVo.setCreateByName(requestContext.getAccountName());
        String token = liveActivityClient.getToken(liveTokenVo);
        if ("error".equals(token)) {
            return Response.fail();
        }
        return Response.ok(token);
    }

    @ApiOperation(value = "直播用户范围选择保存", notes = "用户范围选择保存")
    @PostMapping("/scopeAuthorization/save")
    public Response saveScopeAuthorizations(@RequestBody List<ScopeAuthorizationVO> scopeAuthorizations) {
        RequestContext requestContext = ContextHolder.get();
        for (ScopeAuthorizationVO scopeAuthorization : scopeAuthorizations) {
            scopeAuthorization.setSiteId(requestContext.getSiteId());
        }
        Boolean f = liveActivityClient.saveScopeAuthorization(scopeAuthorizations);
        if (f) {
            return Response.ok();
        }
        return Response.fail();
    }


    @ApiOperation(value = "直播用户范围选择查询", notes = "用户范围选择查询", response = ScopeAuthorizationVO.class)
    @GetMapping("/scopeAuthorization/list")
    public Response getScopeAuthorizationList(@RequestParam(name = "liveId") Long liveId) {
        List<ScopeAuthorizationVO> scopeAuthorizations = liveActivityClient.getScopeAuthorizationList(liveId);
        return Response.ok(scopeAuthorizations);
    }

    /**
     * 直播上架
     *
     * @param param 带id
     * @return
     */
    @ApiOperation(value = "直播上架", notes = "直播上架")
    @PostMapping("/up")
    public Response up(@RequestBody LiveActivityVO param) {
        if (liveActivityClient.up(param)) {

            return Response.ok();
        }
        return Response.fail();
    }

    /**
     * 直播下架
     *
     * @param param 只带id
     * @return
     */
    @ApiOperation(value = "直播下架", notes = "直播下架")
    @PostMapping("/down")
    public Response down(@RequestBody LiveActivityVO param) {


        try {

            List<RelationLiveVo> relationLive = portalManagePCFeignClient.getRelationLive(ContextHolder.get().getSiteId(), param.getId());
            if (CollectionUtils.isNotEmpty(relationLive)) {
                return Response.fail(InternationalEnums.LIVECONTROLLER2.getCode());
            }
            Boolean delFlag = liveActivityClient.down(param);
            if (delFlag) {
                return Response.ok();
            }
            return Response.ok();
        } catch (Exception e) {
            LOG.info("下架直播异常：{}", e.getMessage());
        }
        return Response.fail();
    }


//    @GetMapping("/public/auth")
//    @ApiOperation(value = "获取直播详细信息", notes = "直播详细信息", response = LiveActivity.class)
//    public JSONObject auth(
//            @RequestParam(name = "userid",required = true) Long userid,
//            @RequestParam(name = "ts",required = true) Long ts,
//            @RequestParam(name = "sign",required = true) String sign,
//            @RequestParam(name = "url",required = true) String url
//    ){
//        LOG.info("提交的参数id:"+userid+"ts"+ts+"sign:"+sign);
//        Map<String, Object> map = new HashMap<>();
//        JSONObject json;
//        AccountVO accountVO = accountClient.findById(userid);
//        if (null != accountVO) {
//            map.put("status", 1);
//            map.put("userid", userid.toString());
//            map.put("nickname", accountVO.getName());
//            map.put("avatar", accountVO.getHeadPortrait()+"");
//            map.put("avatar", accountVO.getHeadPortrait()+"");
//        }else{
//            map.put("status", 0);
//            map.put("errorUrl", "www.baidu.com");
//        }
//        json = JSONObject.parseObject(JSONObject.toJSONString(map));
//        return json;
//    }


    @GetMapping("/public/auth")
    @ApiOperation(value = "获取直播详细信息", notes = "直播详细信息", response = LiveActivityVO.class)
    public String auth(
            @RequestParam(name = "id", required = true) Long id,
            @RequestParam(name = "ts", required = true) Long ts,
            @RequestParam(name = "sign", required = true) String sign,
            @RequestParam(name = "url", required = true) String url
    ) {
        LOG.info("提交的参数id:" + id + "ts" + ts + "sign:" + sign + "url" + url);
        Map<String, Object> map = new HashMap<>();
        map.put("ts", ts);
        map.put("sign", sign);
        map.put("url", url);
        String jsonString = JSON.toJSONString(map);
        return jsonString;
    }

    @GetMapping(value = "/public/horseLight/auth", produces = "application/json; charset=utf-8")
    @ApiOperation(value = "跑马灯授权返回", notes = "跑马灯授权返回")
    public String horseLightAuth(@RequestParam(name = "code", required = false) String code,
                                 @RequestParam(name = "vid") String vid,
                                 @RequestParam(name = "t") String t,
                                 @RequestParam(name = "callback", required = false) String callback) {
        //接受req参数并设置
        HorseLight horseLight = new HorseLight();
        //接受req参数并设置
        //String code = req.getParameter("code");
        LOG.info("################# code={}", code);
        if (StringUtils.isNotBlank(code)) {
            String[] param = {code};
            if ("off".equalsIgnoreCase(code)) {
                //param = code.split("__");
                horseLight.setShow(code);
                horseLight.setCode("");
                horseLight.setUsername("");
            }
            horseLight.setCode(code);
            horseLight.setUsername(code);
        }

        /*horseLight.setVid(req.getParameter("vid"));
        horseLight.setT(req.getParameter("t"));
        String prefix = req.getParameter("callback");*/
        horseLight.setVid(vid);
        horseLight.setT(t);
        String prefix = callback;


        JSONObject jsonpObject = horseLight.getJson();


        //若有则处理jsonp
        String reString = null;
        if (null == prefix) {
            reString = jsonpObject.toString();
        } else {
            reString = prefix + "(" + jsonpObject.toString() + ")";
        }
        System.out.println(reString);


        return reString;
    }

    @GetMapping("/public/status/callback")
    @ApiOperation(value = "直播状态改变,保利威回调接口")
    public BizResponse liveStatusCallback(@RequestParam(value = "channelId") String channelId
            , @RequestParam(value = "status") String status
            , @RequestParam(value = "timestamp") Long timestamp
            , @RequestParam(value = "sign") String sign
            , @RequestParam(value = "sessionId") String sessionId
            , @RequestParam(value = "startTime") String startTime
            , @RequestParam(value = "endTime") String endTime){
        LOG.info("直播状态改变,保利威回调参数: {}",channelId);

        return liveActivityClient.liveStatusCallback(channelId, status, timestamp, sign, sessionId, startTime, endTime);
    }


    @GetMapping("/public/transfer/callback")
    @ApiOperation(value = "转存视频成功,保利威回调接口")
    public BizResponse<String> liveTransferCallback(
            @RequestParam(value = "channelId") String channelId
            , @RequestParam(value = "timestamp") Long timestamp
            , @RequestParam(value = "sign") String sign
            , @RequestParam(value = "vid") String vid){
        LOG.info("转存视频成功,保利威回调参数: channelId = {}",channelId);
        PolyvLiveBackCallbackVo liveCallbackVo = new PolyvLiveBackCallbackVo();
        liveCallbackVo.setChannelId(channelId);
        liveCallbackVo.setVid(vid);
        liveCallbackVo.setSign(sign);
        liveCallbackVo.setTimestamp(timestamp);
        return liveReplayClient.liveTransferCallback(liveCallbackVo);
    }


    @GetMapping("/replay/list")
    @ApiOperation(value = "查询直播的回放列表")
    public BizResponse<Page<LiveReplayVo>> getLiveReplayList(@RequestParam("liveId") Long liveId,@RequestParam(value = "pageNo") Integer pageNo,
                                                             @RequestParam("pageSize") Integer pageSize){
        LiveReviewsVo reviewsVo = new LiveReviewsVo();
        reviewsVo.setLiveId(liveId);
        if (null == pageNo || pageNo.compareTo(1) < 0){
            pageNo = 1;
        }
        if (null == pageSize || pageSize.compareTo(1) < 0){
            pageSize = 10;
        }
        reviewsVo.setPageNo(pageNo.intValue());
        reviewsVo.setPageSize(pageSize.intValue());
        reviewsVo.setRequestContext(ContextHolder.get());
        Page<LiveReplayVo> page = liveReplayClient.getManageReplayList(reviewsVo);
        return BizResponse.ok(page);
    }

    @PostMapping("/replay/status/update")
    @ApiOperation(value = "直播回放上架、下架")
    public BizResponse updateReplayStatus(@RequestBody LiveReplayOperationVo operationVo){

        Boolean aBoolean = liveReplayClient.updateReplayStatus(operationVo);
        if (null == aBoolean || aBoolean.equals(false)){
            return BizResponse.fail("false");
        }
        return BizResponse.ok();
    }

    @PostMapping("/replay/top/update")
    @ApiOperation(value = "直播回放置顶,取消置顶")
    public BizResponse updateReplayTop(@RequestBody LiveReplayOperationVo operationVo){

        Boolean aBoolean = liveReplayClient.updateReplayTop(operationVo);
        if (null == aBoolean || aBoolean.equals(false)){
            return BizResponse.fail("false");
        }
        return BizResponse.ok();
    }

    @PostMapping("/replay/info/update")
    @ApiOperation(value = "直播回放信息修改")
    public BizResponse updateReplayInfo(@RequestBody LiveReplayInfoVo infoVo ){

        infoVo.setContext(ContextHolder.get());
        Boolean aBoolean = liveReplayClient.updateReplayInfo(infoVo);
        if (null == aBoolean || aBoolean.equals(false)){
            return BizResponse.fail("false");
        }
        return BizResponse.ok();
    }

}
