package com.yizhi.application.protal.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.application.protal.constant.BannerNameEnum;
import com.yizhi.application.protal.constant.TerminalEnum;
import com.yizhi.core.application.cache.RedisCache;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.library.application.feign.StudyCaseClient;
import com.yizhi.site.application.feign.InformationStudentFeignClients;
import com.yizhi.site.application.feign.api.EventTrackApiClients;
import com.yizhi.site.application.vo.domain.InformationVo;
import com.yizhi.site.application.vo.site.*;
import com.yizhi.util.application.constant.ReturnCode;
import com.yizhi.util.application.domain.Response;
import com.yizhi.util.application.enums.i18n.Constants;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;



import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Api(tags = "学员端-资讯接口")
@RestController
@RequestMapping("/api/info")
public class InformationStudentController {

    private static final Logger LOGGER = LoggerFactory.getLogger(InformationStudentController.class);

    @Autowired
    InformationStudentFeignClients informationStudentFeignClients;

    @Autowired
    private EventTrackApiClients eventTrackApiClients;
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private StudyCaseClient studyCaseClient;

    @PostMapping("/page/list")
    @ApiOperation(value = "资讯列表新", notes = "资讯列表新", response = InformationListVO.class)
    public Response<InformationListVO> listInformation(@RequestBody InfoVO infoVO) {
        try {
            String terminalName = TerminalEnum.getTerminalKey(infoVO.getTerminalName());
            if (StringUtils.isBlank(terminalName)) {
                return Response.fail("终端名称错误");
            }
//			if(StringUtils.isBlank(infoVO.getTypeName())){
//				return Response.fail("类型名称错误");
//			}
            Integer pageNo = infoVO.getPageNo() == null ? 1 : infoVO.getPageNo();
            Integer pageSize = infoVO.getPageSize() == null ? 10 : infoVO.getPageSize();
            infoVO.setPageNo(pageNo);
            infoVO.setPageSize(pageSize);
            infoVO.setTerminalName(terminalName);
            infoVO.setBannerName(BannerNameEnum.NEWS.getKey());
            infoVO.setContext(ContextHolder.get());

            InformationListVO vo = informationStudentFeignClients.informationPageList(infoVO);
            return Response.ok(vo);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("资讯列表:", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }

    @PostMapping("/mobile/bannerImages")
    @ApiOperation(value = "资讯列表新", notes = "资讯列表新", response = ImageListVO.class)
    public Response<ImageListVO> listBannerImages(@RequestBody InfoVO infoVO) {
        try {
            String terminalName = TerminalEnum.getTerminalKey(infoVO.getTerminalName());
            if (StringUtils.isBlank(terminalName)) {
                return Response.fail("终端名称错误");
            }
//			if(StringUtils.isBlank(infoVO.getTypeName())){
//				return Response.fail("类型名称错误");
//			}
            infoVO.setTerminalName(terminalName);
            infoVO.setBannerName(BannerNameEnum.NEWS.getKey());
            List<ImageListVO> imageListVOS = informationStudentFeignClients.listBannerImages(infoVO);
            return Response.ok(imageListVOS);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("资讯列表:", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }

    @PostMapping("/page/pcList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "当前页", paramType = "body"),
            @ApiImplicitParam(name = "pageSize", value = "每页个数", paramType = "body"),
            @ApiImplicitParam(name = "typeName", value = "资讯名称", paramType = "body", required = true),
            @ApiImplicitParam(name = "typeOne", value = "资讯父类型", paramType = "body"),
            @ApiImplicitParam(name = "typeTwo", value = "资讯子类型", paramType = "body"),
            @ApiImplicitParam(name = "terminalName", value = "终端名称, PC：PC，APP： MOBILE, 微信: WECHAT", paramType = "body"),
            @ApiImplicitParam(name = "bannerName", value = "轮播图所属栏目, MARKET:营销, TRAIN:培训, HOMEPAGE:首页, COURSE:课程, NEWS:新闻资讯", paramType = "body"),
            @ApiImplicitParam(name = "relationId", value = "绑定业务的ID", paramType = "body")
    }
    )
    @ApiOperation(value = "pc端,新闻/公告列表", notes = "pc端,新闻/公告列表", response = InformationListVO.class)
    public Response<InformationListPcVo> ListPcInformation(HttpServletRequest request, @RequestBody InfoVO infoVO) {
        Map<String, Integer> pageMap = new HashMap<>();
        try {
            String terminalName = null;
            if (null != infoVO.getTerminalName()) {
                terminalName = TerminalEnum.getTerminalKey(infoVO.getTerminalName());
                if (StringUtils.isBlank(terminalName)) {
                    return Response.fail(Constants.PORT_MSG_TERMINAL_NAME_ERROR);
                }
            }

//			if(StringUtils.isBlank(infoVO.getTypeName())){
//				return Response.fail("类型名称错误");
//			}
            Integer pageNo = infoVO.getPageNo() == null ? 1 : infoVO.getPageNo();
            Integer pageSize = infoVO.getPageSize() == null ? 10 : infoVO.getPageSize();
            infoVO.setPageNo(pageNo);
            infoVO.setPageSize(pageSize);
            infoVO.setTerminalName(terminalName);
            infoVO.setBannerName(BannerNameEnum.NEWS.getKey());
            infoVO.setContext(ContextHolder.get());

            InformationListPcVo vo = informationStudentFeignClients.informationPcPageListV2(infoVO);
            // 添加阅读文章埋点
            if(request.getHeader("Cookie")!=null&& Objects.equals(redisCache.get(request.getHeader("Cookie").replace("JSESSIONID=","")),"2")){
                eventTrackApiClients.addEvent(String.valueOf(infoVO.getRelationId()),infoVO.getTypeTwo()!=null?infoVO.getTypeTwo():infoVO.getRelationId());
            }
            pageMap.put("pageNo", pageNo);
            pageMap.put("pageSize", pageSize);
            if (null != vo) {
                pageMap.put("pageRecords", vo.getPageTotal());
            }
            return Response.ok(vo, pageMap);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("pc端,新闻/公告列表:", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @PostMapping("/page/pcView")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "listNo", value = "所在列表的索引", paramType = "body"),
            @ApiImplicitParam(name = "typeName", value = "资讯名称", paramType = "body"),
            @ApiImplicitParam(name = "id", value = "该条信息id", paramType = "body", required = true),
            @ApiImplicitParam(name = "typeOne", value = "资讯父类型,所选信息在新闻/公告所有信息时必传", paramType = "body"),
            @ApiImplicitParam(name = "typeTwo", value = "资讯子类型,所选信息在新闻分类信息时必传", paramType = "body")
    })
    @ApiOperation(value = "pc端点击新闻分类列表", notes = "pc端点击新闻分类列表", response = InformationViewVO.class)
    public Response<InformationViewVO> getPcView(@RequestBody IdOneVO idOneVO) {
        try {
            InformationViewVO informationViewVO = informationStudentFeignClients.getPcInformation(idOneVO);
            if(informationViewVO!=null) {
                informationViewVO.setFavoriteState(studyCaseClient.favoriteStudentCase(informationViewVO.getId())?1:0);
            }
            return Response.ok(informationViewVO);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("pc端点击新闻分类列表:", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @PostMapping("/list")
    @ApiOperation(value = "资讯列表老", notes = "资讯列表老", response = InformationListVO.class)
    public Response<InformationListVO> getInformation(@RequestBody InfoVO infoVO) {
        try {
            String terminalName = TerminalEnum.getTerminalKey(infoVO.getTerminalName());
            if (StringUtils.isBlank(terminalName)) {
                return Response.fail("终端名称错误");
            }
            infoVO.setTerminalName(terminalName);
            infoVO.setBannerName(BannerNameEnum.NEWS.getKey());
            infoVO.setContext(ContextHolder.get());

            InformationListVO vo = informationStudentFeignClients.informationList(infoVO);
            return Response.ok(vo);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("资讯列表:", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }

    @PostMapping("/view")
    @ApiOperation(value = "资讯详情", notes = "资讯详情", response = InformationVO.class)
    public Response<InformationViewVO> getInformation(HttpServletRequest request,@RequestBody IdOneVO vo) {
        try {
            vo.setContext(ContextHolder.get());
            InformationViewVO info = informationStudentFeignClients.getInformation(vo);
            if(info!=null) {
                info.setFavoriteState(studyCaseClient.favoriteStudentCase(info.getId())?1:0);
                // 添加阅读文章埋点
                //if(request.getHeader("Cookie")!=null&& Objects.equals(redisCache.get(request.getHeader("Cookie").replace("JSESSIONID=","")),"2")){
                    eventTrackApiClients.addEvent(String.valueOf(info.getTypeOne()),info.getId());
                //}
            }
            return Response.ok(info);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("资讯详情:", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }

    @PostMapping("/home/search")
    @ApiOperation(value = "首页搜索新闻资讯", notes = "首页搜索新闻资讯", response = InformationVO.class)
    public Response<Page<InformationVO>> searchInformation(@RequestBody InfomationParamVO vo) {
        try {
            vo.setContext(ContextHolder.get());
            Page<InformationVo> page = informationStudentFeignClients.searchInformation(vo);
            return Response.ok(page);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("首页搜索新闻资讯", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }
}
