package com.hotent.portal.controller;


import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.hotent.base.annotation.ApiGroup;
import com.hotent.base.constants.ApiGroupConsts;
import com.hotent.base.controller.BaseController;
import com.hotent.base.model.CommonResult;
import com.hotent.base.query.FieldRelation;
import com.hotent.base.query.PageBean;
import com.hotent.base.query.PageList;
import com.hotent.base.query.QueryField;
import com.hotent.base.query.QueryFilter;
import com.hotent.base.query.QueryOP;
import com.hotent.base.util.BeanUtils;
import com.hotent.portal.model.PortalMeetingApply;
import com.hotent.portal.persistence.manager.PortalMeetingApplyManager;
import com.hotent.uc.api.impl.util.ContextUtil;

import dm.jdbc.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 会议室申请 前端控制器
 *
 * @company 广州宏天软件股份有限公司
 * @author zhangxw
 * @email zhangxw@jee-soft.cn
 * @since 2021-06-25
 */
@RestController
@Api(tags="会议室申请")
@ApiGroup(group= {ApiGroupConsts.GROUP_PORTAL})
@RequestMapping("/portalMeetingApply/v1/")
public class PortalMeetingApplyController extends BaseController<PortalMeetingApplyManager, PortalMeetingApply> {
	
	@RequestMapping(value="apply",method= {RequestMethod.POST,RequestMethod.PUT}, produces = {"application/json; charset=utf-8" })
	@ApiOperation("会议室申请")
	public CommonResult<String> save(@ApiParam(name="meetingApply", value="申请会议室信息") @RequestBody PortalMeetingApply meetingApply) throws Exception {
		return baseService.apply(meetingApply);
	}
	
	@RequestMapping(value="getApplyByTime",method=RequestMethod.GET, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "根据条件获取会议申请记录", httpMethod = "GET", notes = "根据条件获取会议申请记录")
	public List<PortalMeetingApply> getApplyByTime(@ApiParam(name = "userId",value = "用户id（不传取当前用户）")@RequestParam(required=false) Optional<String> userId,
			@ApiParam(name = "startDate",value = "开始日期（如：2021-07-14 00:00:00）")@RequestParam(required=false) Optional<String> startDate,
			@ApiParam(name = "endDate",value = "结束日期（如：2021-07-15 00:00:00）") @RequestParam(required=false) Optional<String> endDate) throws Exception{
		String id = userId.orElse("");
		QueryFilter filter = QueryFilter.build().withPage(new PageBean(1, PageBean.WITHOUT_PAGE));
		if(StringUtil.isNotEmpty(id)) {
			filter.addFilter("ownerOwnerId", id, QueryOP.EQUAL, FieldRelation.AND ,"myQuery");
		}
		if(BeanUtils.isNotEmpty(startDate.get()) && BeanUtils.isNotEmpty(endDate.get())) {
			filter.addFilter("endTime", startDate.get(), QueryOP.LESS_EQUAL, FieldRelation.AND ,"myQuery");
			filter.addFilter("startTime", endDate.get(), QueryOP.GREAT_EQUAL, FieldRelation.AND ,"myQuery");
		}else if(BeanUtils.isNotEmpty(startDate.get())) {
			filter.addFilter("endTime", startDate.get(), QueryOP.GREAT_EQUAL, FieldRelation.AND ,"myQuery");
		}else if(BeanUtils.isNotEmpty(endDate.get())) {
			filter.addFilter("endTime", endDate.get(), QueryOP.LESS_EQUAL, FieldRelation.AND ,"myQuery");
		}
		PageList<PortalMeetingApply> page = super.query(filter);
		return page.getRows();
	}
	
	@RequestMapping(value="updateMeetingApplyStatus",method= RequestMethod.POST, produces = {"application/json; charset=utf-8" })
	@ApiOperation("根据实例id更新会议申请状态（流程配置结束事件脚本触发）")
	public CommonResult<String> updateMeetingApplyStatus(@ApiParam(name="instId", value="流程实例id") @RequestParam String instId,
			@ApiParam(name="status", value="状态") @RequestParam String status,
			@ApiParam(name="busData", value="bo数据") @RequestParam Optional<String> busData) throws Exception {
		return baseService.updateByInstId(instId, status, busData.orElse(""));
	}
	
	@RequestMapping(value="getApplyCount",method=RequestMethod.GET, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "统计会议室申请状态数量", httpMethod = "GET", notes = "统计会议室申请状态数量")
	public Map<String,Integer> getApplyCount(@ApiParam(name = "ownerId",value = "申请人id")@RequestParam(required=false) Optional<String> ownerId,
			@ApiParam(name = "roomId",value = "会议室id")@RequestParam(required=false) Optional<String> roomId,
			@ApiParam(name="isOwner", value="是否只拉取我申请的：true（是），false（否）") @RequestParam Optional<Boolean> isOwner) throws Exception{
		QueryFilter orderfilter = QueryFilter.build().withPage(new PageBean(1, PageBean.NO_ROW_LIMIT));
		QueryFilter currentFilter = QueryFilter.build().withPage(new PageBean(1, PageBean.NO_ROW_LIMIT));
		QueryFilter completedFilter = QueryFilter.build().withPage(new PageBean(1, PageBean.NO_ROW_LIMIT));
		if(StringUtil.isNotEmpty(roomId.get())) {
			orderfilter.addFilter("OWNER_OWNER_ID_", ownerId.get(), QueryOP.EQUAL);
			currentFilter.addFilter("OWNER_OWNER_ID_", ownerId.get(), QueryOP.EQUAL);
			completedFilter.addFilter("OWNER_OWNER_ID_", ownerId.get(), QueryOP.EQUAL);
		}
		if(StringUtil.isNotEmpty(roomId.get())) {
			orderfilter.addFilter("MEETING_ID_", roomId.get(), QueryOP.EQUAL);
			currentFilter.addFilter("MEETING_ID_", roomId.get(), QueryOP.EQUAL);
			completedFilter.addFilter("MEETING_ID_", roomId.get(), QueryOP.EQUAL);
		}
		PageList<PortalMeetingApply> orderPage = this.getApplyPageByType(orderfilter, Optional.of("order"), isOwner);
		PageList<PortalMeetingApply> currentPage = this.getApplyPageByType(currentFilter, Optional.of("current"), isOwner);
		PageList<PortalMeetingApply> completedPage = this.getApplyPageByType(completedFilter, Optional.of("completed"), isOwner);
		Map<String,Integer> map = new HashMap<String, Integer>();
		
		map.put("order", (int)orderPage.getTotal());
		map.put("current", (int)currentPage.getTotal());
		map.put("completed", (int)completedPage.getTotal());
		return map;
	}
	
	@RequestMapping(value="getApplyPageByType",method=RequestMethod.POST, produces = {
	"application/json; charset=utf-8" })
	@ApiOperation(value = "根据状态类型获取会议室申请分页数据", httpMethod = "POST", notes = "根据状态类型获取会议室申请分页数据")
	public PageList<PortalMeetingApply> getApplyPageByType(@ApiParam(name="queryFilter",value="通用查询对象")@RequestBody QueryFilter queryFilter,
			@ApiParam(name="type", value="order（预约），current（待执行），completed（已完成）") @RequestParam Optional<String> type,
			@ApiParam(name="isOwner", value="是否只拉取我申请的：true（是），false（否）") @RequestParam Optional<Boolean> isOwner) throws Exception{
		String userId = ContextUtil.getCurrentUserId();
		queryFilter.addFilter("OWNER_OWNER_ID_", userId, QueryOP.EQUAL, FieldRelation.AND, "base");
		if(!isOwner.orElse(false)) {
			queryFilter.addFilter("PARTICIPANTS_ID_", userId, QueryOP.LIKE, FieldRelation.OR, "base");
		}
		String typeStr = type.orElse("");
		if(StringUtil.isNotEmpty(typeStr)) {//这里未考虑跨天的会议
			switch (typeStr) {
			case "order":
				queryFilter.addFilter("START_TIME_", LocalDate.now().plusDays(1), QueryOP.GREAT, FieldRelation.AND, "order");
				queryFilter.addFilter("STATUS_", PortalMeetingApply.STATUS_REJECTED, QueryOP.NOT_EQUAL, FieldRelation.AND, "order");
				break;
			case "current":
				queryFilter.addFilter("START_TIME_", LocalDateTime.now(), QueryOP.GREAT_EQUAL, FieldRelation.AND, "current");
				queryFilter.addFilter("START_TIME_", LocalDate.now().plusDays(1), QueryOP.LESS, FieldRelation.AND, "current");
				queryFilter.addFilter("STATUS_", PortalMeetingApply.STATUS_REJECTED, QueryOP.NOT_EQUAL, FieldRelation.AND, "current");
				break;
			case "completed":
				queryFilter.addFilter("END_TIME_", LocalDateTime.now(), QueryOP.LESS, FieldRelation.AND, "completed");
				queryFilter.addFilter("STATUS_", PortalMeetingApply.STATUS_REJECTED, QueryOP.NOT_EQUAL, FieldRelation.AND, "completed");
				break;
			}
		}
		return super.query(queryFilter);
	}
	
	@RequestMapping(value="getApplyPage",method=RequestMethod.POST, produces = {
	"application/json; charset=utf-8" })
	@ApiOperation(value = "获取会议室申请分页数据", httpMethod = "POST", notes = "获取会议室申请分页数据")
	public Map<String,PageList<PortalMeetingApply>> getApplyPage(@ApiParam(name="queryFilter",value="通用查询对象")@RequestBody QueryFilter queryFilter) throws Exception{
		String userId = ContextUtil.getCurrentUserId();
		queryFilter.addFilter("OWNER_OWNER_ID_", userId, QueryOP.EQUAL, FieldRelation.AND, "base");
		queryFilter.addFilter("PARTICIPANTS_ID_", userId, QueryOP.LIKE, FieldRelation.OR, "base");
		QueryFilter orderfilter = QueryFilter.build().withPage(queryFilter.getPageBean());
		QueryFilter currentFilter = QueryFilter.build().withPage(queryFilter.getPageBean());
		QueryFilter completedFilter = QueryFilter.build().withPage(queryFilter.getPageBean());
		
		List<QueryField> queryFields = queryFilter.getQuerys();
		if(BeanUtils.isNotEmpty(queryFields)) {
			for (QueryField queryField : queryFields) {
				orderfilter.addQueryField(queryField);
				currentFilter.addQueryField(queryField);
				completedFilter.addQueryField(queryField);
			}
		}
		Map<String,PageList<PortalMeetingApply>> map = new HashMap<String, PageList<PortalMeetingApply>>();
		orderfilter.addFilter("START_TIME_", LocalDate.now().plusDays(1), QueryOP.GREAT, FieldRelation.AND, "order");
		orderfilter.addFilter("STATUS_", PortalMeetingApply.STATUS_REJECTED, QueryOP.NOT_EQUAL, FieldRelation.AND, "order");
		map.put("order", super.query(orderfilter));
		
		currentFilter.addFilter("START_TIME_", LocalDateTime.now(), QueryOP.GREAT_EQUAL, FieldRelation.AND, "current");
		currentFilter.addFilter("START_TIME_", LocalDate.now().plusDays(1), QueryOP.LESS, FieldRelation.AND, "current");
		currentFilter.addFilter("STATUS_", PortalMeetingApply.STATUS_REJECTED, QueryOP.NOT_EQUAL, FieldRelation.AND, "current");
		map.put("current", super.query(currentFilter));
		
		completedFilter.addFilter("END_TIME_", LocalDateTime.now(), QueryOP.LESS, FieldRelation.AND, "completed");
		completedFilter.addFilter("STATUS_", PortalMeetingApply.STATUS_REJECTED, QueryOP.NOT_EQUAL, FieldRelation.AND, "completed");
		map.put("completed", super.query(completedFilter));
		return map;
	}
}
