package com.yizhi.application.portal.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.application.tools.PageTools;
import com.yizhi.certificate.application.feign.CertificateClient;
import com.yizhi.certificate.application.vo.domain.CertificateVo;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.core.application.enums.InternationalEnums;
import com.yizhi.course.application.feign.CourseClient;
import com.yizhi.course.application.feign.OfflineCourseClient;
import com.yizhi.course.application.vo.OfflineCourseVo;
import com.yizhi.course.application.vo.domain.CourseEntityVo;
import com.yizhi.drools.application.feign.RecommendStrategyClient;
import com.yizhi.drools.application.vo.manage.StrategyPageVo;
import com.yizhi.library.application.feign.StudentCaseClient;
import com.yizhi.library.application.param.HomeListParam;
import com.yizhi.library.application.vo.StudentCaseVO;
import com.yizhi.live.application.feign.LiveActivityClient;
import com.yizhi.live.application.vo.LiveActivityVO;
import com.yizhi.site.application.feign.PortalManageFeignClients;
import com.yizhi.site.application.feign.api.PortalApiFeignClients;
import com.yizhi.site.application.vo.domain.PortalLoginVo;
import com.yizhi.site.application.vo.domain.PortalTemplateVo;
import com.yizhi.site.application.vo.domain.RelationReportVo;
import com.yizhi.site.application.vo.site.*;
import com.yizhi.training.application.feign.TpPlanActivityClient;
import com.yizhi.training.application.vo.domain.TpPlanActivityVo;
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.*;
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.util.*;
import java.util.stream.Collectors;

/**
 * 门户管理
 * 
 * @author mei
 * @Date: 2018/3/17 20:30
 */

@Api(tags = "门户管理")
@RestController
@RequestMapping("/manage/portal")
public class SitePortalManageController {

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

	@Autowired
	private PortalManageFeignClients portalManages;
	@Autowired
	private TpPlanActivityClient activityManages;

	@Autowired
	LiveActivityClient liveActivityClient;

//	@Autowired
//	private VoteClient voteClient;

	@Autowired
	private CertificateClient certificateClient;

	@Autowired
	private OfflineCourseClient offlineCourseClient;

	@Autowired
	private PortalApiFeignClients portalApiFeignClient;
	@Autowired
	StudentCaseClient studentCaseClient;
	@Autowired
	private RecommendStrategyClient recommendStrategyClient;

	@ApiOperation(value = "门户列表", notes = "返回门户列表", response = TerminalListVO.class)
	@GetMapping("/list")
	public Response<List<TerminalListVO>> listPortal() {
		try {
			SiteComponyIdVO siteComponyIdVO = new SiteComponyIdVO();
			Long accountId = ContextHolder.get().getAccountId();
			String accountName = ContextHolder.get().getAccountName();
			siteComponyIdVO.setCompanyId(ContextHolder.get().getCompanyId());
			siteComponyIdVO.setCreateById(accountId);
			siteComponyIdVO.setCreateByName(accountName);
			siteComponyIdVO.setOrgId(ContextHolder.get().getOrgId());
			siteComponyIdVO.setSiteId(ContextHolder.get().getSiteId());

			List<TerminalListVO> listPortal = portalManages.listPortal(siteComponyIdVO);
			return Response.ok(listPortal);
		} catch (Exception e) {
			LOG.error("门户列表:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "门户发布", notes = "返回id")
	@PostMapping("/release")
	@ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "终端id", dataType = "Long") })
	public Response<String> releasePortal(@RequestBody IdOneVO vo) {
		try {
			Long id = portalManages.releasePortal(vo.getId());
			return Response.ok(id);
		} catch (Exception e) {
			LOG.error("门户发布:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "门户取消发布", notes = "返回id")
	@PostMapping("/unrelease")
	@ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "终端id", dataType = "Long") })
	public Response<String> unreleasePortal(@RequestBody IdOneVO vo) {
		try {
			Long id = portalManages.unreleasePortal(vo.getId());
			return Response.ok(id);
		} catch (Exception e) {
			LOG.error("门户取消发布:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "登录页配置（APP,PC,微信）", notes = "返回背景图片路径")
	@GetMapping("/login/view")
	public Response<PortalLoginVo> loginPageView(
			@ApiParam(name = "terminalId", value = "终端id", required = true) String terminalId) {
		try {
			PortalLoginVo loginPageView = portalManages.loginPageView(Long.valueOf(terminalId));
			return Response.ok(loginPageView);
		} catch (Exception e) {
			LOG.error("登录页配置（PC、微信）:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "登录页修改（APP,PC,微信）", notes = "返回id")
	@PostMapping("/login/update")
	@ApiImplicitParams({ @ApiImplicitParam(name = "siteId", value = "站点ID", dataType = "Long"),
			@ApiImplicitParam(name = "terminalId", value = "终端ID", dataType = "Long"),
			@ApiImplicitParam(name = "bgimgPath", value = "背景图片路径", dataType = "String") })
	public Response<String> loginPageUpdate(@RequestBody PortalLoginListVO vo) {
		try {
			if (vo.getTerminalId() == null) {
				return Response.fail(InternationalEnums.SITEPORTALMANAGECONTROLLER1.getCode());
			}
			RequestContext context = ContextHolder.get();
			Date date = new Date();
			PortalLoginVo pl = new PortalLoginVo();
			pl.setSiteId(context.getSiteId());
			pl.setTerminalId(vo.getTerminalId());
			String type = vo.getType();
			if (StringUtils.equals("1", type)) {
				pl.setBgimgPath(vo.getBgimgPath());
				pl.setLoginNameDesc("N");
				pl.setLoginPwdDesc("N");
			} else if (StringUtils.equals("2", type)) {
				pl.setBgimgPath("N");
				pl.setLoginNameDesc(vo.getLoginNameDesc());
				pl.setLoginPwdDesc("N");
			} else if (StringUtils.equals("3", type)) {
				pl.setBgimgPath("N");
				pl.setLoginNameDesc("N");
				pl.setLoginPwdDesc(vo.getLoginPwdDesc());

			}

			pl.setCreateById(context.getAccountId());
			pl.setCreateByName(context.getAccountName());
			pl.setCreateTime(date);
			pl.setUpdateById(context.getAccountId());
			pl.setUpdateByName(context.getAccountName());
			pl.setUpdateTime(date);
			return Response.ok(portalManages.loginPageUpdate(pl));
		} catch (Exception e) {
			LOG.error("登录页修改（PC、微信）:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "登录页发布(APP, PC、微信)", notes = "返回id")
	@PostMapping("/login/release")
	@ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "登录页ID", dataType = "Long", required = true),
			@ApiImplicitParam(name = "siteId", value = "站点ID", dataType = "Long"),
			@ApiImplicitParam(name = "terminalId", value = "终端ID", dataType = "Long"),
			@ApiImplicitParam(name = "bgimgPath", value = "背景图片路径", dataType = "String") })
	public Response<String> loginPageRelease(@RequestBody PortalLoginListVO vo) {
		try {
			RequestContext context = ContextHolder.get();
			Date date = new Date();
			PortalLoginVo pl = new PortalLoginVo();
			pl.setId(vo.getId());
			pl.setSiteId(vo.getSiteId());
			pl.setTerminalId(vo.getTerminalId());
			pl.setBgimgPath(vo.getBgimgPath());
			pl.setCreateById(context.getAccountId());
			pl.setCreateByName(context.getAccountName());
			pl.setCreateTime(date);
			pl.setUpdateById(context.getAccountId());
			pl.setUpdateByName(context.getAccountName());
			pl.setUpdateTime(date);
			return Response.ok(portalManages.loginPageRelease(pl));
		} catch (Exception e) {
			LOG.error("登录页发布（PC、微信）:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "首页发布（APP, PC、微信）", notes = "返回")
	@PostMapping("/home/release")
	@ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "首页id", dataType = "Long") })
	public Response<String> homeRelease(@RequestBody IdOneVO vo) {
		try {
			RequestContext context = ContextHolder.get();
			vo.setContext(context);
			return Response.ok(portalManages.homeRelease(vo));
		} catch (Exception e) {
			LOG.error("首页发布（PC、微信）:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "头部导航栏功能入口列表", notes = "返回导航栏列表", response = NavigateListVO.class)
	@PostMapping("/navigate/list")
	@ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "首页ID", dataType = "Long"),
			@ApiImplicitParam(name = "pageNo", value = "开始", dataType = "integer"),
			@ApiImplicitParam(name = "pageSize", value = "每页显示", dataType = "integer") })
	public Response<HeadNavigateListVO> listNavigate(@RequestBody PageParamVO vo) {
		try {
			HeadNavigateListVO listNavigate = portalManages.listNavigate(vo);
			return Response.ok(listNavigate);
		} catch (Exception e) {
			LOG.error("头部导航栏功能入口列表:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "头部导航栏功能入口修改", notes = "返回导航栏ID",response = NavigateListVO.class)
	@PostMapping("/navigate/update")
	@ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "导航栏ID", dataType = "Long"),
			@ApiImplicitParam(name = "homeId", value = "首页ID", dataType = "Long"),
			@ApiImplicitParam(name = "siteId", value = "站点ID", dataType = "Long"),
			@ApiImplicitParam(name = "showName", value = "显示名称", dataType = "String"),
			@ApiImplicitParam(name = "imgPath", value = "图片路径", dataType = "String"),
			@ApiImplicitParam(name = "relationFunc", value = "关联功能类型， 自定义的为 1，  系统提供的为0", dataType = "integer"),
			@ApiImplicitParam(name = "relationFuncName", value = "关联功能名称", dataType = "String"),
			@ApiImplicitParam(name = "relationFuncUrl", value = "关联功能链接", dataType = "String"),
			@ApiImplicitParam(name = "display", value = "显示状态, 0 不显示  1 显示", dataType = "integer") })
	public Response<Boolean> updateAndInsertNavigate(@RequestBody NavigateListVO vo) {
		try {
			RequestContext context = ContextHolder.get();
			vo.setAccountId(context.getAccountId());
			vo.setAccountName(context.getAccountName());
			return Response.ok(portalManages.updateNavigate(vo));
		} catch (Exception e) {
			LOG.error("头部导航栏功能入口修改:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "头部导航栏功能入口删除", notes = "返回true和false")
	@PostMapping("/navigate/delete")
	@ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "ID", dataType = "Long"),
			@ApiImplicitParam(name = "homeId", value = "首页ID", dataType = "Long") })
	public Response<Boolean> deleteNavigate(@RequestBody NavigateListVO vo) {
		try {
			RequestContext context = ContextHolder.get();
			vo.setAccountId(context.getAccountId());
			vo.setAccountName(context.getAccountName());
			return Response.ok(portalManages.deleteNavigate(vo));
		} catch (Exception e) {
			LOG.error("头部导航栏功能入口删除:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "头部导航栏功能入口新增", notes = "返回true和false")
	@PostMapping("/navigate/list/drag")
	@ApiImplicitParams({ @ApiImplicitParam(name = "sourceId", value = "源ID", dataType = "Long"),
			@ApiImplicitParam(name = "targetId", value = "目标ID", dataType = "Long"), })
	public Response<Boolean> dragNavigate(@RequestBody IdTwoVO vo) {
		try {
			if (vo.getSourceId() == null || vo.getTargetId() == null) {
				return Response.fail(InternationalEnums.SITEPORTALMANAGECONTROLLER2.getCode());
			}
			RequestContext context = ContextHolder.get();
			vo.setAccountId(context.getAccountId());
			vo.setAccountName(context.getAccountName());
			return Response.ok(portalManages.dragNavigate(vo));
		} catch (Exception e) {
			LOG.error("头部导航栏功能入口新增集合:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "选择公告列表", notes = "返回首页logoVo", response = AnnouncementVO.class)
	@PostMapping("/home/announcement/select/list")
	@ApiImplicitParams({ @ApiImplicitParam(name = "pageNo", value = "开始", dataType = "integer"),
			@ApiImplicitParam(name = "pageSize", value = "每页显示", dataType = "integer") })
	public Response<Page<AnnouncementVO>> selectAnnouncement(@RequestBody PageParamVO vo) {
		try {
			if (vo.getPageNo() == null || vo.getPageSize() == null) {
				return Response.fail(InternationalEnums.SITEPORTALMANAGECONTROLLER2.getCode());
			}
			vo.setSiteId(ContextHolder.get().getSiteId());
			return Response.ok(portalManages.selectAnnouncement(vo));
		} catch (Exception e) {
			LOG.error("首页logo 查看:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "预览公告", notes = "返回公告Vo", response = PreviewImformationVO.class)
	@GetMapping("/home/announcement/preview")
	public Response<PreviewImformationVO> previewAnnouncement(
			@ApiParam(name = "imformationId", value = "资讯ID", required = true) String imformationId) {
		try {
			if (imformationId.equals("") || imformationId.equals(null)) {
				return Response.fail(InternationalEnums.SITEPORTALMANAGECONTROLLER3.getCode());
			}
			return Response.ok(portalManages.previewAnnouncement(imformationId));
		} catch (Exception e) {
			LOG.error("预览公告:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "添加公告列表", notes = "返回公告Vo", response = PreviewImformationVO.class)
	@PostMapping("/home/announcement/list")
	@ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "首页ID", dataType = "integer"),
			@ApiImplicitParam(name = "pageNo", value = "开始", dataType = "integer"),
			@ApiImplicitParam(name = "pageSize", value = "每页显示", dataType = "integer") })
	public Response<Page<AnnouncementVO>> listAnnouncement(@RequestBody PageParamVO vo) {
		try {
			if (vo.getPageNo() == null || vo.getPageSize() == null || vo.getId() == null) {
				return Response.fail(InternationalEnums.SITEPORTALMANAGECONTROLLER2.getCode());
			}
			vo.setSiteId(ContextHolder.get().getSiteId());
			return Response.ok(portalManages.listAnnouncement(vo));
		} catch (Exception e) {
			LOG.error("首页logo 查看:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "添加公告 删除", notes = "返回true 或 false")
	@PostMapping("/home/announcement/delete")
	@ApiImplicitParams({ @ApiImplicitParam(name = "homeId", value = "首页ID", dataType = "Long"),
			@ApiImplicitParam(name = "informationId", value = "公告ID", dataType = "Long") })
	public Response<Boolean> deleteAnnouncement(@RequestBody HomeInformationListVO vo) {
		try {
			vo.setContext(ContextHolder.get());
			return Response.ok(portalManages.deleteAnnouncement(vo));
		} catch (Exception e) {
			LOG.error("首页logo 查看:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "添加公告 保存", notes = "返回true 或 false")
	@PostMapping("/home/announcement/list/insert")
	@ApiImplicitParams({ @ApiImplicitParam(name = "homeId", value = "首页ID", dataType = "Long"),
			@ApiImplicitParam(name = "ids", value = "已选择轮播id 的集合", dataType = "List") })
	public Response<Boolean> insertAnnouncementList(@RequestBody InsertListVO vo) {
		try {
			List<Long> ids = vo.getIds();
			if (ids.size() < 1) {
				return Response.fail(InternationalEnums.SITEPORTALMANAGECONTROLLER4.getCode());
			}
			if (ids.size() > 5) {
				return Response.fail(InternationalEnums.SITEPORTALMANAGECONTROLLER5.getCode());
			}
			vo.setContext(ContextHolder.get());
			return Response.ok(portalManages.insertAnnouncementList(vo));
		} catch (Exception e) {
			LOG.error("首页logo 查看:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "已选择轮播图片 拖动排序", notes = "已选择轮播图片 拖动排序")
	@PostMapping("/template/selected/image/drag")
	@ApiImplicitParams({ @ApiImplicitParam(name = "sourceId", value = "源ID", dataType = "Long"),
			@ApiImplicitParam(name = "targetId", value = "目标ID", dataType = "Long") })
	public Response<Boolean> dragImage(@RequestBody IdTwoVO vo) {
		if (vo.getSourceId() == null || vo.getTargetId() == null) {
			return Response.fail(InternationalEnums.SITEPORTALMANAGECONTROLLER2.getCode());
		}
		try {
			RequestContext context = ContextHolder.get();
			vo.setAccountId(context.getAccountId());
			vo.setAccountName(context.getAccountName());
			return Response.ok(portalManages.dragImage(vo));
		} catch (Exception e) {
			LOG.error("已选择轮播图列表:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "已选择轮播图片列表", notes = "返回已选择轮播图列表", response = ImageListVO.class)
	@PostMapping("/template/selected/image/list")
	@ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "首页ID", dataType = "Long") })
	public Response<List<ImageListVO>> listImage(@RequestBody IdOneVO vo) {
		try {
			return Response.ok(portalManages.listImage(vo.getId()));
		} catch (Exception e) {
			LOG.error("已选择轮播图列表:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "已选择轮播图删除", notes = "返回true和false")
	@PostMapping("/template/selected/delete")
//	@ApiImplicitParams({
//		@ApiImplicitParam(name="homeId" , value="首页ID", dataType="Long"),
//		@ApiImplicitParam(name="imageId" , value="轮播图片ID", dataType="Long")
//	})
	public Response<Boolean> deleteBannerImage(@RequestBody HomeImageListVO vo) {
		try {
			vo.setContext(ContextHolder.get());
			return Response.ok(portalManages.deleteBannerImage(vo));
		} catch (Exception e) {
			LOG.error("已选择轮播图删除:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "已选择轮播图片预览", notes = "返回轮播图片信息")
	@GetMapping("/template/image/preview")
	public Response<String> previewImage(
			@ApiParam(name = "bannerId", value = "轮播图ID", required = true) String imageId) {
		try {
			return Response.ok(portalManages.previewImage(Long.valueOf(imageId)));
		} catch (Exception e) {
			LOG.error("已选择轮播图预览:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "选择已有图片列表", notes = "返回选择已有图片列表", response = ImageListVO.class)
	@PostMapping("/template/selected/list")
	@ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "终端ID", dataType = "Long"),
			@ApiImplicitParam(name = "pageNo", value = "开始", dataType = "integer"),
			@ApiImplicitParam(name = "pageSize", value = "每页显示", dataType = "integer") })
	public Response<Page<ImageListVO>> selectBannerImage(@RequestBody PageParamVO vo) {
		try {
			return Response.ok(portalManages.selectBannerImage(vo));
		} catch (Exception e) {
			LOG.error("选择已有Banner列表:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "已选择轮播片新增集合", notes = "返回true或false")
	@PostMapping("/template/image/list/insert")
	@ApiImplicitParams({ @ApiImplicitParam(name = "homeId", value = "首页ID", dataType = "Long"),
			@ApiImplicitParam(name = "siteId", value = "轮播图ID", dataType = "Long"),
			@ApiImplicitParam(name = "ids", value = "已选择轮播id 集合", dataType = "List") })
	public Response<Boolean> insertListBannerImage(@RequestBody InsertListVO vo) {
		try {
			vo.setContext(ContextHolder.get());
			return Response.ok(portalManages.insertBannerImageList(vo));
		} catch (Exception e) {
			LOG.error("已选择轮播Banner新增集合:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "上传新的轮播图片", notes = "返回图片Id")
	@PostMapping("/template/image/upload")
	@ApiImplicitParams({ @ApiImplicitParam(name = "homeId", value = "首页ID", dataType = "Long"),
			@ApiImplicitParam(name = "siteId", value = "站点ID", dataType = "Long"),
			@ApiImplicitParam(name = "terminalId", value = "终端ID", dataType = "Long"),
			@ApiImplicitParam(name = "bannerName", value = "所属栏目", dataType = "String"),
			@ApiImplicitParam(name = "imgTitle", value = "图片标题", dataType = "String"),
			@ApiImplicitParam(name = "bannerPath", value = "存放图片路径", dataType = "String"),
			@ApiImplicitParam(name = "linkUrl", value = "链接地址", dataType = "String"), })
	public Response<Boolean> uploadBannerImage(@RequestBody UploadImageVO vo) {
		try {
			vo.setContext(ContextHolder.get());
			if (portalManages.uploadBannerImage(vo) != null) {
				return Response.ok(true);
			}
			return Response.ok(false);
		} catch (Exception e) {
			LOG.error("已选择轮播Banner新增集合:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "模块新增", notes = "返回模块id")
	@PostMapping("/template/insert")
	@ApiImplicitParams({ @ApiImplicitParam(name = "homeId", value = "首页ID", dataType = "Long"),
			@ApiImplicitParam(name = "siteId", value = "轮播图ID", dataType = "Long"),
			@ApiImplicitParam(name = "moduleType", value = "板块类型,1:推荐/精选,2:项目培训,3:课程,4:直播,5:新闻", dataType = "integer") })
	public Response<TemplateAddVO> insertTemplate(@RequestBody TemplateAddVO vo) {
		try {
			LOG.info("传的参数VO：" + vo);
			vo.setContext(ContextHolder.get());
			return Response.ok(portalManages.insertTemplate(vo));
		} catch (Exception e) {
			LOG.error("模块新增:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "模块删除", notes = "返回true或false")
	@PostMapping("/template/delete")
	@ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "模块ID", dataType = "Long"),
			@ApiImplicitParam(name = "homeId", value = "首页ID", dataType = "Long") })
	public Response<Boolean> deleteTemplate(@RequestBody TemplateListVO vo) {
		try {
			RequestContext context = ContextHolder.get();
			PortalTemplateVo pt = new PortalTemplateVo();
			pt.setId(vo.getId());
			pt.setHomeId(vo.getHomeId());
			pt.setUpdateById(context.getAccountId());
			pt.setUpdateByName(context.getAccountName());
			return Response.ok(portalManages.deleteTemplate(pt));
		} catch (Exception e) {
			LOG.error("模块删除:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "模块查看", notes = "返回模块", response = TemplateListVO.class)
	@GetMapping("/template/view")
	public Response<TemplateListVO> viewTemplate(
			@ApiParam(name = "templateId", value = "模块ID", required = true) String templateId) {
		try {
			return Response.ok(portalManages.viewTemplate(Long.valueOf(templateId)));
		} catch (Exception e) {
			LOG.error("模块查看:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "模块修改", notes = "返回模块Id")
	@PostMapping("/template/update")
	@ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "模块ID", dataType = "Long"),
			@ApiImplicitParam(name = "homeId", value = "首页ID", dataType = "Long"),
			@ApiImplicitParam(name = "siteId", value = "轮播图ID", dataType = "Long"),
			@ApiImplicitParam(name = "moduleType", value = "板块类型,1:推荐/精选,2:项目培训,3:课程,5:直播,4:新闻，6:案例库", dataType = "integer"),
			@ApiImplicitParam(name = "icon", value = "图片logo", dataType = "String"),
			@ApiImplicitParam(name = "moduleName", value = "显示名称", dataType = "String"),
			@ApiImplicitParam(name = "selectProject", value = "选择项目, 推荐/精选 有", dataType = "Long"),
			@ApiImplicitParam(name = "selectProjectName", value = "选择项目名称", dataType = "String"),
			@ApiImplicitParam(name = "num", value = "内容个数", dataType = "integer"), })
	public Response<Long> updateTemplate(@RequestBody TemplateUpdateVO vo) {
		try {
			vo.setContext(ContextHolder.get());
			return Response.ok(portalManages.updateTemplate(vo));
		} catch (Exception e) {
			LOG.error("模块修改:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "热门课程分类列表", notes = "返回模块Id", response = PopCourseListVO.class)
	@GetMapping("/template/course/list")
	public Response<List<PopCourseListVO>> ListTemplateCourse(
			@ApiParam(name = "templateId", value = "模块ID", required = true) String templateId) {
		try {
			return Response.ok(portalManages.ListTemplateCourse(Long.valueOf(templateId)));
		} catch (Exception e) {
			LOG.error("热门课程分类列表:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "热门课程分类保存", notes = "返回模块Id")
	@PostMapping("/template/course/list/insert")
	public Response<Boolean> insertTemplateCourse(@RequestBody CourseAddVO listVo) {
		try {
			List<PopCourseListVO> courseList = listVo.getCourseList();
			if (courseList.size() > 0) {
				return Response.fail(InternationalEnums.SITEPORTALMANAGECONTROLLER6.getCode());
			}
			listVo.setContext(ContextHolder.get());
			return Response.ok(portalManages.insertTemplateCourse(listVo));
		} catch (Exception e) {
			LOG.error("热门课程分类列表:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "首页logo新增", notes = "返回首页logo Id")
	@PostMapping("/home/logo/insert")
	@ApiImplicitParams({ @ApiImplicitParam(name = "homeId", value = "首页ID", dataType = "Long"),
			@ApiImplicitParam(name = "logoPath", value = "logo图片地址", dataType = "Long"), })
	public Response<String> insertHomeLogo(@RequestBody HomeLogoVO vo) {
		try {
			vo.setContext(ContextHolder.get());
			return Response.ok(portalManages.insertHomeLogo(vo));
		} catch (Exception e) {
			LOG.error("首页logo新增:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "首页logo修改", notes = "返回首页logo Id")
	@PostMapping("/home/logo/update")
	@ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "首页logoID", dataType = "Long"),
			@ApiImplicitParam(name = "homeId", value = "首页ID", dataType = "Long"),
			@ApiImplicitParam(name = "logoPath", value = "logo图片地址", dataType = "Long") })
	public Response<String> updateHomeLogo(@RequestBody HomeLogoVO vo) {
		try {
			vo.setContext(ContextHolder.get());
			return Response.ok(portalManages.updateHomeLogo(vo));
		} catch (Exception e) {
			LOG.error("首页logo修改:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "首页logo 查看", notes = "返回首页logoVo", response = HomeLogoVO.class)
	@GetMapping("/home/logo/view")
	public Response<HomeLogoVO> viewHomeLogo(
			@ApiParam(name = "homeId", value = "首页ID", required = true) String homeId) {
		try {
			return Response.ok(portalManages.viewHomeLogo(Long.valueOf(homeId)));
		} catch (Exception e) {
			LOG.error("首页logo 查看:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "新闻资讯 列表", notes = "返回首页logoVo", response = TemplateNewsVO.class)
	@GetMapping("/template/selected/news/list")
	public Response<List<TemplateNewsVO>> listSelectedNews(
			@ApiParam(name = "templateId", value = "模块ID", required = true) String templateId) {
		try {
			return Response.ok(portalManages.listSelectedNews(Long.valueOf(templateId)));
		} catch (Exception e) {
			LOG.error("首页logo 查看:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "新闻资讯 预览", notes = "返回首页logoVo", response = PreviewNewsVO.class)
	@GetMapping("/template/selected/news/preview")
	public Response<PreviewNewsVO> previewNews(@ApiParam(name = "id", value = "新闻id", required = true) String id) {
		try {
			return Response.ok(portalManages.previewNews(Long.valueOf(id)));
		} catch (Exception e) {
			LOG.error("首页logo 查看:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@ApiOperation(value = "模板新闻资讯 保存", notes = "返回首页logoVo")
	@PostMapping("/template/news/list/insert")
	@ApiImplicitParams({ @ApiImplicitParam(name = "templateId", value = "模板id", dataType = "Long"),
			@ApiImplicitParam(name = "ids", value = "资讯ID 集合", dataType = "Long"), })
	public Response<Boolean> insertTemplateNews(@RequestBody NewsAddVO vo) {
		try {
			if (vo.getIds().size() > 2) {
				return Response.fail(InternationalEnums.SITEPORTALMANAGECONTROLLER7.getCode());
			}
			vo.setContext(ContextHolder.get());
			return Response.ok(portalManages.insertTemplateNews(vo));
		} catch (Exception e) {
			LOG.error("模板新闻资讯 保存:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@Autowired
	private CourseClient courseClient;

	@ApiOperation(value = "获取培训活动", notes = "获取培训活动", response = TpPlanActivityVo.class)
	@GetMapping("/activity/project/list")
	public Response<List<PortalProjectActivityVO>> getActivityByProject(
			@ApiParam(name = "projectId", value = "培训ID", required = true) String projectId) {

		List<PortalProjectActivityVO> list = new ArrayList<PortalProjectActivityVO>();

		try {
			List<TpPlanActivityVo> activityList = activityManages.allListByTpId(Long.valueOf(projectId));
			if (CollectionUtils.isNotEmpty(activityList)) {
				PortalProjectActivityVO vo = null;
				LOG.info("值：" + activityList);
				for (TpPlanActivityVo activity : activityList) {
					vo = new PortalProjectActivityVO();
					// 活动类型： 0课程 1考试 2调研 3直播 4投票 5作业 6证书 7外部链接 8报名 9签到 10线下课程")

					vo.setId(activity.getId());
					vo.setName(activity.getName());

					Integer type = activity.getType();
					Long id = activity.getRelationId();

					LOG.info("活动相关的id{}" + id);
					String icon = "";
					CourseEntityVo course = null;
					LiveActivityVO live = null;
//					Vote vote = null;
					CertificateVo certificate = null;
					OfflineCourseVo offlineCourseVo = null;

					switch (type) {
					case 0:
						try {
							course = courseClient.view(id);
						} catch (Exception e) {
							LOG.info("{}", e);
						}
						icon = (course != null ? course.getImage() : "");
						break;
					case 1:
						try {
							icon = portalApiFeignClient.getRelationLink(102).getUrl();
						} catch (Exception e) {
							LOG.info("{}", e);
						}
						break;
					case 2:
						try {
							icon = portalApiFeignClient.getRelationLink(101).getUrl();
						} catch (Exception e) {
							LOG.info("{}", e);
						}
						break;
					case 3:
						try {
							live = liveActivityClient.getLive(id);
						} catch (Exception e) {
							live = null;
						}
						icon = (live != null ? live.getLogoImage() : "");
						break;
					case 4:
//						try {
//							vote = voteClient.getVote(id);
//						} catch (Exception e) {
//							LOG.info("{}", e);
//						}
//						icon = (vote != null ? vote.getAdvertPictureUrl() : "");
						break;
					case 5:
						try {
							icon = portalApiFeignClient.getRelationLink(104).getUrl();
						} catch (Exception e) {
							LOG.info("{}", e);
						}
						break;
					case 6:
						try {
							certificate = certificateClient.getCertificate(id);
						} catch (Exception e) {
							certificate = null;
						}
						icon = (certificate != null ? certificate.getLogourl() : "");
						break;
					case 10:
						try {
							offlineCourseVo = offlineCourseClient.get(id);
						} catch (Exception e) {
							offlineCourseVo = null;
						}
						icon = (offlineCourseVo != null ? offlineCourseVo.getImage() : "");
						break;
					default:
						break;
					}

					vo.setIcon(icon);
					LOG.info("message:" + vo);
					list.add(vo);

				}
			}
			return Response.ok(list);
		} catch (Exception e) {
			LOG.error("获取培训活动:", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	/**
	 * 移动端添加课程时课程列表
	 * 
	 * @param type
	 * @param courseType
	 * @param name
	 * @param templateId
	 * @param classifyId
	 * @param shelves
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@GetMapping("/course/list")
	@ApiOperation(value = "配置页面添加课程", notes = "返回分页结果集", response = CourseEntityVo.class)
	public Response<Page<CourseEntityVo>> list(@RequestParam(required = false, value = "type", defaultValue = "0") Integer type,
			@ApiParam(name = "courseType", value = "课程类型", required = false) @RequestParam(required = false, value = "courseType") Integer courseType,
			@ApiParam(name = "name", value = "课程名称或作者", required = false) @RequestParam(name = "name", required = false) String name,
			@ApiParam(name = "templateId", value = "模块的id", required = false) @RequestParam(name = "templateId", required = false) Long templateId,
			@ApiParam(name = "classifyId", value = "分类id ", required = false) @RequestParam(name = "classifyId", required = false) Long classifyId,
			@ApiParam(name = "shelves", value = "0 未上架 1 已上架 2 草稿", required = false) @RequestParam(name = "shelves", required = false) Integer shelves,
			@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) {

		List<Long> ids = getIds(templateId);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("pageNo", pageNo);
		map.put("pageSize", pageSize);
		map.put("name", name);
		map.put("shelves", shelves);
		map.put("classifyId", classifyId);
		map.put("type", type);
		map.put("courseType", courseType);

		RequestContext requestContext = ContextHolder.get();
		map.put("companyId", requestContext.getCompanyId());
		map.put("siteId", requestContext.getSiteId());
		map.put("orgIds", requestContext.getOrgIds());
		map.put("courseIds", ids);
		Page<CourseEntityVo> page = courseClient.list(map);
		return Response.ok(page);
	}

	@GetMapping("/case/list")
	@ApiOperation(value = "移动端配置案例库的列表", notes = "移动端配置案例库的列表")
	public Response getCaseList(
			@ApiParam(name = "name", value = "模糊搜索的关键字", required = false) @RequestParam(name = "name", required = false) String name,
			@ApiParam(name = "templateId", value = "模块的id", required = false) @RequestParam(name = "templateId", required = false) Long templateId,
			@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) {
		List<Long> ids = getIds(templateId);
		HomeListParam homeListParam = new HomeListParam();
		homeListParam.setPageNo(pageNo);
		homeListParam.setPageSize(pageSize);
		homeListParam.setStudentCaseIds(ids);
		homeListParam.setKey(name);
		try {
			Page<StudentCaseVO> studentCaseHomeList = studentCaseClient.getStudentCaseHomeList(homeListParam);
			LOG.info("返回信息：" + studentCaseHomeList);
			return Response.ok(PageTools.convertPage(studentCaseHomeList));
		} catch (Exception e) {
			return Response.fail(Constants.CASELIBRARY_MSG_BIZ_ERROR);
		}

	}

	private List<Long> getIds(Long templateId) {
		List<PortalPlateVO> plateVOList = null;
		try {
			plateVOList = portalApiFeignClient.getPlateVOList(templateId);
		} catch (Exception e) {
			LOG.info("模板的接口：{}", e.getMessage());
		}

		List<Long> ids = null;
		if (CollectionUtils.isNotEmpty(plateVOList)) {
			ids = plateVOList.parallelStream().map(portalPlateVO -> {
				return portalPlateVO.getId();
			}).collect(Collectors.toList());
			LOG.info("返回的ids：{}", ids);
		}
		return ids;
	}

	@ApiOperation(value = "根据模块id模块关内容的列表")
	@GetMapping("/getPlateListByTemplateId")
	public Response<TemplatePlateVO> getPlateListByTemplateId(
			@ApiParam(name = "templateId", value = "模块id") @RequestParam(name="templateId") Long templateId) {
		try {
			List<PortalPlateVO> plateVOList = portalApiFeignClient.getPlateVOList(templateId);
			LOG.info("返回的列表：{}",plateVOList);
			Map<String,Object> map = new HashMap<>();

			if (CollectionUtils.isNotEmpty(plateVOList)) {
				PortalPlateVO portalPlateVO = plateVOList.get(0);
				LOG.info("返回的实体：{}",portalPlateVO);

				map.put("moduleId",templateId);
				map.put("moduleType",portalPlateVO.getType());
				map.put("moduleName",portalPlateVO.getModuleName());
				map.put("num",portalPlateVO.getNum());
				List<Long> ids = plateVOList.parallelStream().map(protalPlate -> {
						return protalPlate.getId();
					}).collect(Collectors.toList());
				try {
				    LOG.info("ids{}",ids);
					Map<Long, StrategyPageVo> strategyPageVoMap = recommendStrategyClient.list4PortalConfig(ids);

					LOG.info("策略列表:{}",strategyPageVoMap);
					map.put("list",strategyPageVoMap);
					return Response.ok(map);
				} catch (Exception e) {
					return Response.fail(Constants.MSG_BIZ_FAIL);
				}
			} else {
                PortalTemplateVo template = portalManages.getTemplateById(templateId);
                map.put("moduleId",templateId);
                map.put("num", 1);
                map.put("moduleType",template.getModuleType());
                map.put("moduleName",template.getModuleName());
                map.put("list",new ArrayList<>());
				if (template.getModuleType() != null && template.getModuleType() == 7) {
					//智能推荐默认值为3
					map.put("num", 3);
				}
                return Response.ok(map);
			}
		} catch (Exception e) {
			return Response.fail(Constants.PORT_MSG_TERMINAL_NAME_ERROR);
		}
	}

	@ApiOperation(value = "移动端首页配置平台报告保存", notes = "移动端首页配置平台报告保存")
	@PostMapping("/report/save")
	public Response<String> reportUpdate(
			@ApiParam(name = "paramVO", value = "传入终端id及选中的报告") @RequestBody ReportParamVO paramVO) {
		try {
			Boolean update = portalManages.reportUpdate(paramVO);
			if (update) {
				return Response.ok();
			} else {
				return Response.fail(Constants.MSG_BIZ_FAIL);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Response.fail(Constants.MSG_BIZ_FAIL);
		}
	}

	@ApiOperation(value = "移动端首页配置平台报告置顶", notes = "移动端首页配置平台报告置顶")
	@GetMapping("/top")
	public Response<String> top(@ApiParam(name = "id", value = "首页关联报告id") @RequestParam("id") Long id) {
		try {
			Boolean top = portalManages.top(id);
			if (top) {
				return Response.ok();
			} else {
				return Response.fail(Constants.MSG_BIZ_FAIL);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Response.fail(Constants.MSG_BIZ_FAIL);
		}
	}

	@ApiOperation(value = "移动端首页配置平台报告删除", notes = "移动端首页配置平台报告删除")
	@GetMapping("/delete")
	public Response<String> delete(@ApiParam(name = "id", value = "首页关联报告id") @RequestParam("id") Long id) {
		try {
			Boolean delete = portalManages.delete(id);
			if (delete) {
				return Response.ok();
			} else {
				return Response.fail(Constants.MSG_BIZ_FAIL);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Response.fail(Constants.MSG_BIZ_FAIL);
		}
	}

	@GetMapping("/report/list")
	@ApiOperation(value = "移动端首页配置关联报告列表", notes = "移动端首页配置关联报告列表", response = RelationReportVo.class)
	public Response<List<RelationReportVo>> list(
			@ApiParam(name = "terminalId", value = "终端id") @RequestParam("terminalId") Long terminalId) {
		try {
			List<RelationReportVo> list = portalManages.list(terminalId);
			return Response.ok(list);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Response.fail(Constants.MSG_BIZ_FAIL);
		}
	}

	@GetMapping("/report/update")
	public Response<String> update(@RequestParam("id") Long id, @RequestParam("startPush") String startPush,
			@RequestParam("endPush") String endPush) {
		try {
			Boolean update = portalManages.update(id, startPush, endPush);
			if (update) {
				return Response.ok();
			} else {
				return Response.fail(Constants.MSG_BIZ_FAIL);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Response.fail(Constants.MSG_BIZ_FAIL);
		}
	}
}
