package com.yeejoin.amos.supervision.business.controller;

import static org.hamcrest.CoreMatchers.nullValue;

import java.util.HashMap;
import java.util.List;
import java.util.Map;import java.util.stream.Collector;
import java.util.stream.Collectors;

import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.GroupModel;
import com.yeejoin.amos.supervision.common.enums.CheckTypeSuEnum;
import com.yeejoin.amos.supervision.common.enums.DangerCheckTypeLevelEnum;
import com.yeejoin.amos.supervision.common.enums.PlanStatusEnum;
import com.yeejoin.amos.supervision.core.common.request.AddPlanRequest;
import com.yeejoin.amos.supervision.core.common.response.PlanPointRespone;
import com.yeejoin.amos.supervision.core.framework.PersonIdentify;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;

import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.supervision.business.param.PlanInfoPageParam;
import com.yeejoin.amos.supervision.business.service.intfc.IPlanService;
import com.yeejoin.amos.supervision.business.util.CommonResponse;
import com.yeejoin.amos.supervision.business.util.CommonResponseUtil;
import com.yeejoin.amos.supervision.business.util.PlanPageParamUtil;
import com.yeejoin.amos.supervision.core.common.request.CommonPageable;
import com.yeejoin.amos.supervision.core.common.request.CommonRequest;
import com.yeejoin.amos.supervision.dao.entity.Plan;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

@RestController
@RequestMapping(value = "/api/plan")
@Api(tags = "巡检计划api")
public class PlanController extends AbstractBaseController {
	private final Logger log = LoggerFactory.getLogger(PlanController.class);
	@Autowired
	private IPlanService planService;
	
	@Value("${supervision.role.isIncludOrgAirRoleId}")
	private Long isIncludOrgAirRoleId;
	
	@Value("${supervision.role.includOrgCompanyRoleId}")
	private Long includOrgCompanyRoleId;

	/**
	 * 巡检计划查询
	 *
	 * @param
	 * @param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "巡检计划查询", notes = "巡检计划查询")
	@RequestMapping(value = "/list", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@PersonIdentify
	public CommonResponse qryCheckInfoPage(
			@ApiParam(value = "查询条件", required = false) @RequestBody(required = false) List<CommonRequest> queryRequests,
			@ApiParam(value = "分页参数", required = true) CommonPageable commonPageable) {
//        ReginParams reginParams = getSelectedOrgInfo();
//        String loginOrgCode = getOrgCode(reginParams);
//        HashMap<String, Object> paramMap = buildMybatisCriterias(loginOrgCode, null);
//        buildRequestCxt();
		PlanInfoPageParam param = PlanPageParamUtil.fillPlanInfoParam(queryRequests, commonPageable, new HashMap<>());
		Page<HashMap<String, Object>> list = planService.getPlanInfo(param);
		return CommonResponseUtil.success(list);
	}

	/**
	 * 业主单位维保计划查询
	 *
	 * @param
	 * @param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "业主单位维保计划查询", notes = "业主单位维保计划查询")
	@RequestMapping(value = "/owner/list", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public CommonResponse queryInfoPage(
			@ApiParam(value = "查询条件", required = false) @RequestBody(required = false) List<CommonRequest> queryRequests,
			@ApiParam(value = "分页参数", required = true) CommonPageable commonPageable) {
		HashMap<String, Object> paramMap = buildMybatisCriterias(null, null);
//        buildRequestCxt();
		PlanInfoPageParam param = PlanPageParamUtil.fillPlanInfoParam(queryRequests, commonPageable, paramMap);
		Page<HashMap<String, Object>> list = planService.getPlanInfo(param);
		return CommonResponseUtil.success(list);
	}

	/**
	 * 巡检计划新增
	 *
	 * @param param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PersonIdentify
	@ApiOperation(value = "巡检计划新增及编辑", notes = "巡检计划新增及编辑")
	@RequestMapping(value = "/addPlan", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public CommonResponse checkPlanAdd(@ApiParam(value = "巡检计划", required = true) @RequestBody AddPlanRequest param) {
		try {
			AgencyUserModel user = getUserInfo();
			ReginParams reginParams = getSelectedOrgInfo();
			String loginOrgCode = getOrgCode(reginParams);
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("org_code", loginOrgCode);
			map.put("user_id", user.getUserId());
			map.put("user_name", user.getRealName());
			map.put("param", param);
			planService.addPlan(map, reginParams);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("巡检计划新增失败");
		}
	}

	/**
	 * 巡检计划删除（支持批量）
	 *
	 * @param param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "删除巡检计划", notes = "删除巡检计划")
	@RequestMapping(value = "/deletePlanById", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public CommonResponse deletePlanById(@ApiParam(value = "巡检计划ID", required = true) @RequestBody String[] param) {
		try {
			planService.delPlanById(param);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("删除巡检计划失败" + ":" + e.getMessage());
		}
	}

	/**
	 * 编辑巡检另存(支持批量)
	 *
	 * @param param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "另存巡检计划", notes = "另存巡检计划")
	@RequestMapping(value = "/saveAs", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public CommonResponse planSaveAs(@ApiParam(value = "参数", required = true) @RequestBody String[] param) {
		try {
			planService.planSaveAs(param);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("另存巡检计划失败");
		}
	}

	/**
	 * 根据id查询巡检计划
	 *
	 * @param id
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "查询巡检计划明细", notes = "查询巡检计划明细")
	@RequestMapping(value = "/detail/{id}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public CommonResponse queryPointById(
			@ApiParam(value = "计划id", required = true) @PathVariable(name = "id") Long id) {

		Plan plan = planService.queryPlanById(id);
		return CommonResponseUtil.success(plan);

	}

	/**
	 * 巡检计划查询
	 *
	 * @param
	 * @param param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "巡检计划查询", notes = "巡检计划查询")
	@RequestMapping(value = "/queryPlanByOrgCode", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public CommonResponse qryCheckInfo(
			@ApiParam(value = "查询条件") @RequestBody(required = false) List<CommonRequest> queryRequests) {
		ReginParams reginParams = getSelectedOrgInfo();
		String loginOrgCode = getOrgCode(reginParams);
		HashMap<String, Object> paramMap = buildMybatisCriterias(loginOrgCode, null);
		PlanInfoPageParam param = PlanPageParamUtil.fillPlanInfoParam(queryRequests, null, paramMap);
		List<HashMap<String, Object>> list = planService.getPlanInfoNoPage(param);
		return CommonResponseUtil.success(list);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "查询计划列表(<font color='blue'>手机app</font>)", notes = "查询计划列表(<font color='blue'>手机app</font>)")
	@RequestMapping(value = "/queryPlanList", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public CommonResponse queryPlanList() {
		ReginParams reginParams = getSelectedOrgInfo();
		String loginOrgCode = getOrgCode(reginParams);
		List<HashMap<String, Object>> list = planService.queryPlanListByOrgCode(loginOrgCode);
		return CommonResponseUtil.success(list);
	}

	/**
	 * 计划启用停用
	 * 
	 * @param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "计划启用停用", notes = "计划启用停用")
	@RequestMapping(value = "/setPlanStatus", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public CommonResponse setPlanStatus(
			@ApiParam(value = "计划id") @RequestParam(value = "planId", required = false) Long planId,
			@ApiParam(value = "计划状态") @RequestParam(value = "status", required = false) Integer status) {
		planService.setplanstatus(planId, status);
		return CommonResponseUtil.success();
	}

	/**
	 * 获取计划详情
	 * 
	 * @param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "计划启用停用", notes = "计划启用停用")
	@RequestMapping(value = "/getPlanDetails", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public CommonResponse getPlanDetails(
			@ApiParam(value = "计划id") @RequestParam(value = "planId", required = false) Long planId) {
		PlanPointRespone planRequest = planService.getplandetails(planId);
		return CommonResponseUtil.success(planRequest);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "计划状态", notes = "计划状态")
	@RequestMapping(value = "/planStatus/list", method = RequestMethod.GET)
	public ResponseModel getPlanStatusList() {
		return ResponseHelper.buildResponse(PlanStatusEnum.getEnumList());
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "计划检查类型", notes = "计划检查类型")
	@RequestMapping(value = "/checkTypeSuEnum/list", method = RequestMethod.GET)
	public ResponseModel getCheckTypeSuEnumList() {
		return ResponseHelper.buildResponse(CheckTypeSuEnum.getEnumList());
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "检查级别", notes = "检查级别")
	@RequestMapping(value = "/checkTypeLevelEnum/list", method = RequestMethod.GET)
	public ResponseModel getCheckTypeLevelEnumList() {
		boolean includOrgAirRole = false;
		boolean includOrgCompanyRole = false;
		ReginParams reginParams = getSelectedOrgInfo();
		String userId = reginParams.getUserModel().getUserId();
		FeignClientResult<List<GroupModel>> groupList = Privilege.groupClient.queryByUserId(userId);
		List<GroupModel> list = groupList.getResult();

		for (GroupModel groupModel : list) {
			if (groupModel.getSequenceNbr().equals(includOrgCompanyRoleId)) {// 单位管理员的对应主键值
				includOrgCompanyRole = true;
			}
			if (groupModel.getSequenceNbr().equals(isIncludOrgAirRoleId)) {// 机场管理员的对应主键值
				includOrgAirRole = true;
			}
		}

		List<Map<String, Object>> getEnumList = DangerCheckTypeLevelEnum.getEnumList();
		List<Map<String, Object>> resultList=null;
		if (!includOrgAirRole && includOrgCompanyRole) {
			resultList  = getEnumList.stream().filter(i -> i.get("code").toString().equals("1")).collect(Collectors.toList());
			return ResponseHelper.buildResponse(resultList);
		}
		return ResponseHelper.buildResponse(getEnumList);
	}
}
