package com.yonge.cooleshow.cms.controller;

import com.yonge.cooleshow.cms.dal.entity.NewsStatusEnum;
import com.yonge.cooleshow.cms.dto.AppHomeDto;
import com.yonge.cooleshow.cms.dto.AppParam;
import com.yonge.cooleshow.cms.dto.SysNewsInformationDto;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.toolset.base.page.PageInfo;
import com.yonge.toolset.base.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.cms.controller.queryinfo.NewsInformationQueryInfo;
import com.yonge.cooleshow.cms.dal.entity.SysNewsInformation;
import com.yonge.cooleshow.cms.service.SysNewsInformationService;
import com.yonge.cooleshow.common.controller.BaseController;
import com.yonge.toolset.log.model.AuditLogAnnotation;
import com.yonge.toolset.utils.collection.MapUtil;

import javax.validation.Valid;

@RestController
@RequestMapping("news")
@Api(tags = "资讯/广告/闪页/轮播图/乐理服务")
public class NewsController extends BaseController {

	@Autowired
	private SysNewsInformationService sysNewsInformationService;

	@Autowired
	private SysUserFeignService sysUserFeignService;

	@ApiOperation(value = "资讯/广告/闪页/轮播图/乐理 列表分页查询", httpMethod="POST", consumes="application/json", produces="application/json")
	@PostMapping(value = "/page",  consumes="application/json", produces="application/json")
	public HttpResponseResult<PageInfo<SysNewsInformationDto>> getList(@Valid @RequestBody NewsInformationQueryInfo queryInfo) {

		if (queryInfo.getType() == 2) {
			queryInfo.setAttribute2(queryInfo.getSubType());
			queryInfo.setSubType(null);
		}
		Map<String, Object> params = new HashMap<>();
		MapUtil.populateMap(params, queryInfo);
		return succeed(sysNewsInformationService.selectPage(queryInfo));
	}


	@ApiOperation("查询资讯/广告/闪页/轮播图/乐理 详情")
	@ApiImplicitParam(name = "id", value = "资讯ID编号", required = true, dataType = "Long", paramType = "path")
	@GetMapping(value = "/query/{id}")
	public HttpResponseResult<SysNewsInformationDto> query(@PathVariable Long id) {

		return succeed(sysNewsInformationService.queryById(id));
	}

	@ApiOperation(value = "新增资讯/广告/闪页/轮播图/乐理 ", httpMethod="POST", consumes="application/json", produces="application/json")
	@PostMapping(value = "/add",  consumes="application/json", produces="application/json")
	@AuditLogAnnotation(operateName = "资讯新增",interfaceURL = "news/add")
	// @PreAuthorize("@pcs.hasPermissions('news/add')")
	public Object add(@Valid @RequestBody  SysNewsInformation newsInfo) {
		SysUser sysUser = sysUserFeignService.queryUserInfo();
		if (sysUser == null || sysUser.getId() == null) {
			return failed("用户信息获取失败");
		}
		HttpResponseResult<Object> check = check(newsInfo);
		if (!check.getStatus()) {
			return check;
		}
		if (StringUtil.isEmpty(newsInfo.getAttribute1())) {
			newsInfo.setAttribute1("0");
		}
		newsInfo.setStatus(NewsStatusEnum.HIDDEN);
		newsInfo.setCreateTime(new Date());
		newsInfo.setCreateBy(sysUser.getId());
		newsInfo.setUpdateTime(new Date());
		newsInfo.setUpdateBy(sysUser.getId());
		return succeed(sysNewsInformationService.insert(newsInfo));
	}

	HttpResponseResult<Object> check(SysNewsInformation newsInfo) {

		// 1 2 3 4 5 6
		if (StringUtil.isEmpty(newsInfo.getTitle())) {
			return failed("标题不能为空");
		}
		// 6
		if (newsInfo.getSubType() == null && newsInfo.getType() == 6) {
			return failed("章节不能为空");
		}
		// 1 2 3 4 5
		if (newsInfo.getType() != 2 && newsInfo.getType() !=6) {
			if (StringUtil.isEmpty(newsInfo.getCoverImage())) {
				return failed("封面不能为空");
			}
		} else  {
			if ( "IMAGE".equals(newsInfo.getAttribute2())) {
				if (StringUtil.isEmpty(newsInfo.getCoverImage())) {
					return failed("封面不能为空");
				}
			} else if ("VIDEO".equals(newsInfo.getAttribute2())){
				if (StringUtil.isEmpty(newsInfo.getLinkUrl())) {
					return failed("视频地址不能为空");
				}
			}
		}
		if(newsInfo.getType() == 4 ||newsInfo.getType() == 5) {
			if (StringUtil.isEmpty(newsInfo.getClientType() )) {
				return failed("平台不能为空");
			}
		}

		// 1 4 6
		if (newsInfo.getType() == 1 ||newsInfo.getType() == 4 || newsInfo.getType() == 6) {
			if (newsInfo.getOrder() == null) {
				return failed("排序值不能为空");
			}
		}

		// 6
		if (newsInfo.getType() == 6) {
			if (StringUtil.isEmpty(newsInfo.getContent())) {
				return failed("内容不能为空");
			}
		}
		// 2 3 4
		if (newsInfo.getType() == 2 ||newsInfo.getType() == 3 ||newsInfo.getType() == 4 ) {
			if (newsInfo.getOnlineTime() == null || newsInfo.getOfflineTime() == null) {
				return failed("生效时间不能为空");
			}
		}
		// 2
		if (newsInfo.getType() == 2) {
			if (StringUtil.isEmpty(newsInfo.getAttribute2())) {
				return failed("广告类型不能为空");
			}
			// 2
			if (newsInfo.getShowTime() == null || newsInfo.getShowTime() < 1) {
				return failed("显示时长不能为空且不能小于1秒");
			}
		}


		return succeed();
	}

	@ApiOperation(value = "更新资讯/广告/闪页/轮播图/乐理 ", httpMethod="POST", consumes="application/json", produces="application/json")
	@PostMapping(value = "/update",  consumes="application/json", produces="application/json")
	@AuditLogAnnotation(operateName = "资讯更新",interfaceURL = "news/update")
	// @PreAuthorize("@pcs.hasPermissions('news/update')")
	public Object update(@Valid @RequestBody  SysNewsInformation newsInfo) {
		SysUser sysUser = sysUserFeignService.queryUserInfo();
		if (sysUser == null || sysUser.getId() == null) {
			return failed("用户信息获取失败");
		}

		SysNewsInformationDto sysNewsInformationDto = sysNewsInformationService.queryById(newsInfo.getId());
		if (sysNewsInformationDto == null) {
			return failed("未找到相关信息");
		}
		if(NewsStatusEnum.SHOW.getCode().equals(sysNewsInformationDto.getStatus().getCode())) {
			return failed("启用状态下，不可修改");
		}
		if (StringUtil.isEmpty(newsInfo.getAttribute1())) {
			newsInfo.setAttribute1("0");
		}
		if (newsInfo.getType() == 2) {
			if ( "IMAGE".equals(newsInfo.getAttribute2())) {
				newsInfo.setLinkUrl("");
			} else if ("VIDEO".equals(newsInfo.getAttribute2())){
				newsInfo.setCoverImage("");
			}
		}
		HttpResponseResult<Object> check = check(newsInfo);
		if (!check.getStatus()) {
			return check;
		}

		newsInfo.setStatus(NewsStatusEnum.HIDDEN);
		newsInfo.setUpdateTime(new Date());
		newsInfo.setUpdateBy(sysUser.getId());

		return succeed(sysNewsInformationService.update(newsInfo));
	}

	@ApiOperation("删除")
	@PostMapping(value = "/del/{id}")
	@AuditLogAnnotation(operateName = "资讯删除",interfaceURL = "news/del")
	// @PreAuthorize("@pcs.hasPermissions('news/del')")
	public Object add(@PathVariable("id") Long id) {
		SysNewsInformationDto sysNewsInformationDto = sysNewsInformationService.queryById(id);
		if (sysNewsInformationDto == null) {
			return failed("未找到相关信息");
		}
		if(NewsStatusEnum.SHOW.getCode().equals(sysNewsInformationDto.getStatus().getCode())) {
			return failed("启用状态下，不可删除");
		}
		return succeed(sysNewsInformationService.deleteWithLogical(id));
	}

	@ApiOperation("启用/停用")
	@PostMapping(value = "/status/{id}")
	@AuditLogAnnotation(operateName = "资讯启用/停用",interfaceURL = "news/update")
	// @PreAuthorize("@pcs.hasPermissions('news/del')")
	public Object status(@PathVariable("id") Long id) {
		SysNewsInformationDto sysNewsInformationDto = sysNewsInformationService.queryById(id);
		if (sysNewsInformationDto == null) {
			return failed("未找到相关信息");
		}
		return succeed(sysNewsInformationService.updateStatus(id));
	}

	// @ApiOperation("老师手机app首页按钮")
	// @GetMapping(value = "/app/home/teacher")
	public HttpResponseResult<List<SysNewsInformationDto>> teacherMenu() {

		NewsInformationQueryInfo queryInfo = new NewsInformationQueryInfo();
		queryInfo.setStatus(NewsStatusEnum.SHOW.getCode().toString());
		queryInfo.setPlatformType("TEACHER");
		// 1热门资讯
		queryInfo.setType(5);
		queryInfo.setPage(1);
		queryInfo.setRows(999);
		Map<String, Object> params = new HashMap<>();
		MapUtil.populateMap(params, queryInfo);
		List<SysNewsInformationDto> rows = sysNewsInformationService.selectPage(queryInfo).getRows();
		return succeed(rows);
	}

	@ApiOperation("学生/老师端 手机app首页banner、按钮、资讯")
	@PostMapping(value = "/app/home")
	public HttpResponseResult<AppHomeDto> appHome(@RequestBody AppParam param) {

		NewsInformationQueryInfo queryInfo = new NewsInformationQueryInfo();
		//  查询app版本
		String status = sysNewsInformationService.selectAppVersionInfo(param.getPlatform(), param.getVersion());
		if ("auditing".equals(status)) {
			queryInfo.setVersion("1");
		}  else {
			queryInfo.setVersion("0");
		}

		AppHomeDto appHomeDto = new AppHomeDto();
		queryInfo.setStatus(NewsStatusEnum.SHOW.getCode().toString());
		if (StringUtil.isEmpty(param.getClientType())) {
			queryInfo.setPlatformType("STUDENT");
		} else {
			queryInfo.setPlatformType(param.getClientType());
		}
		// 1热门资讯
		queryInfo.setType(1);
		queryInfo.setPage(1);
		queryInfo.setRows(param.getNewsLimit());
		Map<String, Object> params = new HashMap<>();
		MapUtil.populateMap(params, queryInfo);
		List<SysNewsInformationDto> rows = sysNewsInformationService.selectPage(queryInfo).getRows();
		appHomeDto.setInformation(rows);


		// 查所有
		queryInfo.setRows(999);
		// 轮播图
		queryInfo.setType(4);
		params = new HashMap<>();
		MapUtil.populateMap(params, queryInfo);
		appHomeDto.setBanner(sysNewsInformationService.selectPage(queryInfo).getRows());
		// 闪页
		queryInfo.setType(3);
		params = new HashMap<>();
		MapUtil.populateMap(params, queryInfo);
		appHomeDto.setFlashPage(sysNewsInformationService.selectPage(queryInfo).getRows());

		// 按钮
		queryInfo.setType(5);
		params = new HashMap<>();
		MapUtil.populateMap(params, queryInfo);
		appHomeDto.setAppMenu(sysNewsInformationService.selectPage(queryInfo).getRows());
		return succeed(appHomeDto);
	}
}
