package com.yizhi.application.portal.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.core.application.cache.RedisCache;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.core.application.enums.InternationalEnums;
import com.yizhi.lecturer.application.enums.DeleteFlag;
import com.yizhi.point.application.feign.PointListenerClients;
import com.yizhi.site.application.feign.PortalManagePCFeignClients;
import com.yizhi.site.application.feign.PublicationManageFeignClients;
import com.yizhi.site.application.feign.api.EventTrackApiClients;
import com.yizhi.site.application.vo.domain.ProtalPlateVo;
import com.yizhi.site.application.vo.domain.PublicationVo;
import com.yizhi.site.application.vo.site.*;
import com.yizhi.util.application.constant.ReturnCode;
import com.yizhi.util.application.domain.Response;
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.Date;
import java.util.List;
import java.util.Objects;

/**
 * 投稿管理
 *
 * @author yanglang
 * @Date: 2024/12/17 16:30
 */

@Api(tags = "投稿管理")
@RestController
@RequestMapping("/manage/site/classify/publication")
public class SitePublicationManageController {
    private static final Logger LOGGER = LoggerFactory.getLogger(SitePublicationManageController.class);

    @Autowired
    private PublicationManageFeignClients publicationManageFeignClients;
    @Autowired
    private PortalManagePCFeignClients portalManagePCFeignClient;

    @Autowired
    private PointListenerClients pointListenerClients;

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

    /**
     * 投稿列表
     *
     * @return
     */
    @ApiOperation(value = "查看投稿", notes = "查看投稿", response = PublicationParamVO.class)
    @PostMapping("/list")
    public Response<Page<PublicationVo>> list(HttpServletRequest request, @RequestBody PublicationParamVO vo) {
        try {
            RequestContext context = ContextHolder.get();
            vo.setSiteId(context.getSiteId());

            // 添加我的投稿埋点
            if(request.getHeader("Cookie")!=null&&Objects.equals(redisCache.get(request.getHeader("Cookie").replace("JSESSIONID=","")),"2")){
                eventTrackApiClients.addEvent("event_publication",context.getAccountId());
            }
            return Response.ok(publicationManageFeignClients.list(vo));
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }

    /**
     * 投稿列表
     *
     * @return
     */
    @ApiOperation(value = "查看我的投稿", notes = "查看我的投稿", response = PublicationParamVO.class)
    @PostMapping("/listByMyself")
    public Response<Page<PublicationVo>> listByMyself(@RequestBody PublicationParamVO vo) {
        try {
            vo.setCreateById(ContextHolder.get().getAccountId());
            vo.setSiteId(ContextHolder.get().getSiteId());
            return Response.ok(publicationManageFeignClients.list(vo));
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }

    /**
     * 投稿发布的列表
     *
     */
    @ApiOperation(value = "查看投稿发布列表", notes = "查看投稿发布列表", response = PublicationVo.class)
    @PostMapping("/release/list")
    public Response<Page<PublicationVo>> releaseList(@RequestBody PublicationParamReleaseVO vo) {
        try {
            RequestContext context = ContextHolder.get();
            vo.setCompanyCode(context.getCompanyCode());
            vo.setCompanyId(context.getCompanyId());
            vo.setSiteCode(context.getSiteCode());
            vo.setSiteId(context.getSiteId());
            vo.setAccountId(vo.getAccountId());
            vo.setAdmin(context.isAdmin());
            vo.setOrgId(context.getOrgId());
            vo.setOrgIds(context.getOrgIds());
            vo.setOrgName(context.getOrgName());
            return Response.ok(publicationManageFeignClients.releaseList(vo));
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }

    @ApiOperation(value = "保存投稿", notes = "保存投稿")
    @PostMapping("/insert")
    public Response<Boolean> insert(HttpServletRequest request,@RequestBody PublicationVo information) {
        try {
            Date date = new Date();
            RequestContext context = ContextHolder.get();
            information.setCreateById(context.getAccountId());
            information.setCreateByName(context.getAccountName());
            information.setCreateTime(date);
            information.setUpdateById(context.getAccountId());
            information.setUpdateByName(context.getAccountName());
            information.setUpdateTime(date);
            information.setSiteId(context.getSiteId());
            Long id = publicationManageFeignClients.insert(information);
            if (id == null) {
                Response.fail(InternationalEnums.SITEINFORMATIONMANAGECONTROLLER.getCode());
            }

            // 添加我的投稿埋点
            if(request.getHeader("Cookie")!=null&&Objects.equals(redisCache.get(request.getHeader("Cookie").replace("JSESSIONID=","")),"2")){
                eventTrackApiClients.addEvent("event_my_publication",id);
            }
            information.setId(id);
            return Response.ok(true);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }

    @ApiOperation(value = "修改资料分类", notes = "修改资料分类")
    @PostMapping("/update")
    public Response<Boolean> update(@RequestBody PublicationVo information) {
        try {
            RequestContext context = ContextHolder.get();
            information.setUpdateById(context.getAccountId());
            information.setUpdateByName(context.getAccountName());
            information.setUpdateTime(new Date());
            Boolean update = publicationManageFeignClients.update(information);
            return Response.ok(true);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("" + e);
            return Response.fail(ReturnCode.UPDATE_FAIL.getCode(),ReturnCode.UPDATE_FAIL.getMsg());
        }
    }

    @PostMapping("/delete")
    @ApiOperation(value = "删除站点", notes = "删除站点")
    public Response<String> deleteById(@RequestBody IdOneVO vo) {
        if (vo == null) {
            return Response.fail(InternationalEnums.SITEINFORMATIONMANAGECONTROLLER1.getCode());
        }
        if (vo.getId() == null) {
            return Response.fail(InternationalEnums.SITEINFORMATIONMANAGECONTROLLER1.getCode());
        }
        try {
            return Response.ok(publicationManageFeignClients.deleteById(vo));
        } catch (Exception e) {
            LOGGER.error("", e);
            return Response.fail();
        }
    }

    @GetMapping("/releases")
    @ApiOperation(value = "投稿发布", notes = "投稿发布")
    public Response<Boolean> releases(@RequestParam(name = "id") Long id) {
        boolean flase = publicationManageFeignClients.releases(id);
        if(flase) {
           pointListenerClients.addPoint("point_draft", id);
        }
        return Response.ok(flase);
    }

    @GetMapping("/unreleases")
    @ApiOperation(value = "投稿取消发布", notes = "投稿取消发布")
    public Response<Boolean> unreleases(@RequestParam(name = "id") Long id) {
        //新增新闻下架，校验是否关联首页模块
        ProtalPlateVo protalPlate = new ProtalPlateVo();
        protalPlate.setLinkContent(id);
        protalPlate.setState(DeleteFlag.YES.ordinal());
        ProtalPlateVo plate = portalManagePCFeignClient.getPlate(protalPlate);
        if (plate != null) {
            LOGGER.info("新闻下架失败;informationId={},新闻已经关联到首页配置模块；不能下架",id);
            return Response.fail(InternationalEnums.TRAININGPROJECTCONTROLLER2.getCode());
        }
        boolean b = publicationManageFeignClients.unreleases(id);
        return Response.ok(b);
    }

    @GetMapping("/view")
    @ApiOperation(value = "投稿预览", notes = "投稿预览", response = PublicationVo.class)
    public Response<PublicationVo> view(@RequestParam(name = "id") Long id) {
        PublicationVo info = publicationManageFeignClients.publicationView(id);
        return Response.ok(info);
    }

    @GetMapping("/approve")
    @ApiOperation(value = "投稿审批通过", notes = "投稿审批通过", response = PublicationVo.class)
    public Response<PublicationVo> approve(@RequestParam(name = "id") Long id) {
        boolean info = publicationManageFeignClients.approve(id);
        return Response.ok(info);
    }

    @GetMapping("/unApprove")
    @ApiOperation(value = "投稿审批不通过", notes = "投稿审批通过", response = PublicationVo.class)
    public Response<PublicationVo> unApprove(@RequestParam(name = "id") Long id) {
        boolean info = publicationManageFeignClients.unApprove(id);
        return Response.ok(info);
    }

}
