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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
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.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.patrol.business.dao.repository.IInputItemDao;
import com.yeejoin.amos.patrol.business.param.InputItemPageParam;
import com.yeejoin.amos.patrol.business.param.InputItemParam;
import com.yeejoin.amos.patrol.business.service.intfc.IInputItemService;
import com.yeejoin.amos.patrol.business.util.CommonResponse;
import com.yeejoin.amos.patrol.business.util.CommonResponseUtil;
import com.yeejoin.amos.patrol.business.util.DaoCriteria;
import com.yeejoin.amos.patrol.business.util.InputItemParamUtil;
import com.yeejoin.amos.patrol.business.vo.InputItemVo;
import com.yeejoin.amos.patrol.business.vo.PointInputItemVo;
import com.yeejoin.amos.patrol.common.enums.DictTypeEnum;
import com.yeejoin.amos.patrol.core.common.request.CommonPageable;
import com.yeejoin.amos.patrol.core.common.request.CommonRequest;
import com.yeejoin.amos.patrol.core.enums.QueryOperatorEnum;
import org.typroject.tyboot.core.foundation.enumeration.UserType; import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import com.yeejoin.amos.patrol.core.util.StringUtil;
import com.yeejoin.amos.patrol.dao.entity.InputItem;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 检查项
 *
 * @author gaodongdong
 *
 */
@RestController
@RequestMapping(value = "/api/inputItem")
@Api(tags = "巡检项api")
public class InputItemController extends AbstractBaseController {

	private final Logger log = LoggerFactory.getLogger(InputItemController.class);

	@Autowired
	IInputItemService inputItemService;
	@Autowired
	IInputItemDao inputItemDao;

	/**
	 * 新增巡检项
	 *
	 * @param param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "新增检查项", notes = "新增检查项")
	@RequestMapping(value = "/addItem", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public CommonResponse addNewItem(@ApiParam(value = "检查项信息") @RequestBody InputItemParam param) {
		if (ObjectUtils.isEmpty(param.getId())) {
			return updateItem(param);
		}
		 AgencyUserModel user = getUserInfo();
		if (ObjectUtils.isEmpty(user)) {
			return CommonResponseUtil.failure("用户session过期");
		}
		try {
			InputItem inputItem = new InputItem();
			 ReginParams reginParams = getSelectedOrgInfo();
	         String loginOrgCode = getOrgCode(reginParams);

			BeanUtils.copyProperties(param, inputItem);
			///LoginUserParam loginParam = getLoginUserParam();
			  inputItem.setOrgCode(loginOrgCode);
			  inputItem.setCreateBy(user.getUserId());
			inputItemService.addNewInputItem(inputItem);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			return CommonResponseUtil.failure("检查项新增失败: " + e.getMessage());
		}
	}

	/**
	 * 查询巡检项详情
	 *
	 * @param itemID
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "检查项ID", notes = "检查项详情")
	@RequestMapping(value = "/queryItem", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public CommonResponse queryItemDetail(@ApiParam(value = "巡检项ID") @RequestParam(required = true) Long itemID) {
		InputItem bo = inputItemService.queryInputItemDetail(itemID);
		return CommonResponseUtil.success(bo);
	}

	/**
	 *
	 * @param param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "更新检查项", notes = "更新检查项")
	@RequestMapping(value = "/updateItem", produces = "application/json;charset=UTF-8", method = RequestMethod.PUT)
	public CommonResponse updateItem(@ApiParam(value = "检查项详情", required = false) @RequestBody InputItemParam param) {
		if (ObjectUtils.isEmpty(param.getId())) {
			return addNewItem(param);
		}
		AgencyUserModel user = getUserInfo();
		if (ObjectUtils.isEmpty(user)) {
			return CommonResponseUtil.failure("用户session过期");
		}
		try {
			InputItem inputItem = new InputItem();
			BeanUtils.copyProperties(param, inputItem);
			inputItem.setId(param.getId());
			// inputItem.setCreateBy(Integer.parseInt(user.getId() +""));
			inputItemService.updateInputItem(inputItem);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			return CommonResponseUtil.failure("检查项新增失败: " + e.getMessage());
		}
	}

	/**
	 * 批量删除检查项
	 *
	 * @param itemID
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "批量删除检查项", notes = "批量删除检查项")
	@RequestMapping(value = "/batchDelItem", produces = "application/json;charset=UTF-8", method = RequestMethod.DELETE)
	public CommonResponse batchDelItem(
			@ApiParam(value = "巡检项ID(检查项id以英文半角逗号分割。如： 1,2)") @RequestParam(required = true) String itemIDs) {
		try {
			if (ObjectUtils.isEmpty(itemIDs)) {
				return CommonResponseUtil.failure("请选择要删除的检查项");
			}
			String[] ids = itemIDs.split(",");
			inputItemService.batchDelInputItem(ids);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			return CommonResponseUtil.failure("检查项新增失败: " + e.getMessage());
		}
	}

	/**
	 * 删除检查项
	 *
	 * @param itemID
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "删除检查项", notes = "删除检查项")
	@RequestMapping(value = "/delItem", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public CommonResponse delItem(@ApiParam(value = "巡检项ID") @RequestParam(required = true) Long itemID) {
		try {
			inputItemService.delInputItem(itemID);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			return CommonResponseUtil.failure("检查项新增失败: " + e.getMessage());
		}
	}

	/**
	 * 检查项另存为
	 *
	 * @param itemID
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "检查项另存为", notes = "检查项另存为")
	@RequestMapping(value = "/saveAs", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public CommonResponse saveAs(@ApiParam(value = "巡检项ID") @RequestParam(required = true) String itemIDs) {
		AgencyUserModel user = getUserInfo();
		if (ObjectUtils.isEmpty(user)) {
			return CommonResponseUtil.failure("用户session过期");
		}
		try {
			if (ObjectUtils.isEmpty(itemIDs)) {
				return CommonResponseUtil.failure("请选择要另存的检查项");
			}
			String[] ids = itemIDs.split(",");
			inputItemService.saveAs(ids, user.getUserId());
			return CommonResponseUtil.success();
		} catch (Exception e) {
			return CommonResponseUtil.failure("检查项另存为失败: " + e.getMessage());
		}
	}

	/**
	 * 分页查询检查项
	 *
	 * @param queryRequests
	 * @param pageable
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "分页查询检查项", notes = "分页查询检查项")
	@RequestMapping(value = "/queryItemByPage", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public CommonResponse queryItemByPage(
			@ApiParam(value = "组合查询条件", required = false, defaultValue = "[]") @RequestBody(required = false) List<CommonRequest> queryRequests,
			@ApiParam(value = "分页参数", required = false, defaultValue = "current=0&pageSize=10或pageNumber0&pageSize=10") CommonPageable pageable) {
		//LoginUserParam user = CurUserCompanyCache.getInstance().getCurCompany(getUserId(), getToken());

		  ReginParams reginParams = getSelectedOrgInfo();
	        String loginOrgCode = getOrgCode(reginParams);


		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("orgCode", loginOrgCode);
		InputItemPageParam criterias = InputItemParamUtil.fillInputItemPageParam(queryRequests, pageable, paramMap);
		Page<InputItemVo> page = inputItemService.queryInputItemByPage(criterias);
		return CommonResponseUtil.success(page);
	}

	/**
	 * 条件查询检查项
	 *
	 * @param queryRequests
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/queryItemByCondition", produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "条件查询检查项", notes = "条件查询检查项")
	public CommonResponse queryItemByCondition(
			@ApiParam(value = "组合查询条件", required = false, defaultValue = "[]") @RequestBody(required = false) List<CommonRequest> queryRequests) {
		// 1.组织查询条件数据
		 ReginParams reginParams = getSelectedOrgInfo();
	        String loginOrgCode = getOrgCode(reginParams);
	        String roleTypeName = getRoleTypeName(reginParams);
        List<DaoCriteria> criterias = buildDaoCriterias(queryRequests, false, loginOrgCode, roleTypeName);
		// 2.组织数据权限过滤条件，基础数据不管roleType，全按照选择的公司orgCode过滤

		DaoCriteria compDaoCriteria = new DaoCriteria();
		compDaoCriteria.setPropertyName("orgCode");
		compDaoCriteria.setOperator(QueryOperatorEnum.EQUAL.getName());
		compDaoCriteria.setValue(loginOrgCode);
		criterias.add(compDaoCriteria);
		List<InputItem> list = inputItemService.queryInputItemByCondition(criterias);
		return CommonResponseUtil.success(list);
	}
	/**
	 * 条件查询检查项
	 *
	 * @param params
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping (value = "/queryCustomInputItem", produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "条件查询检查项", notes = "条件查询检查项")
	public CommonResponse queryCustomInputItem( @RequestBody HashMap<String,Object> params){
		ReginParams reginParams = getSelectedOrgInfo();
		String orgCode = getOrgCode(reginParams);
		List<PointInputItemVo> list = inputItemService.queryCustomInputItem(params.get("itemType").toString(),params.get("nameOrItemNo").toString(),orgCode);
		return CommonResponseUtil.success(list);
	}
	/**
	 * 条件查询检查项
	 *
	 * @param queryRequests 查询条件
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/queryItemByCondition1", produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "条件查询检查项", notes = "条件查询检查项")
	public CommonResponse queryItemByCondition1(
			@ApiParam(value = "组合查询条件", required = false, defaultValue = "[]") @RequestBody(required = false) List<CommonRequest> queryRequests) {
		// 组织数据权限过滤条件，基础数据不管roleType，全按照选择的公司orgCode过滤
		 ReginParams reginParams = getSelectedOrgInfo();
	        String loginOrgCode = getOrgCode(reginParams);
		List<InputItem> list = null;

		if (ObjectUtils.isEmpty(queryRequests)) {
			list = inputItemDao.findAllByLevel(loginOrgCode);
		} else {
			String level = null;
			for (CommonRequest quest : queryRequests) {
				if (quest.getName().equals("level")) {
					if (StringUtil.isNotEmpty(quest.getValue())) {
						if (quest.getValue().toString().equals("-0")) {  //如果前台传过来等级条件为-0，数据库则存储为空
							level = null;
						} else {
							level = quest.getValue().toString();
						}
					}

				}
			}
			if(ObjectUtils.isEmpty(level)){
				list = inputItemDao.findByLevelNull(loginOrgCode);
			}else{
				list = inputItemDao.findByLevel(loginOrgCode, level);
			}
		}
		return CommonResponseUtil.success(list);
	}

	/**
	 * 查询检查项编号信息
	 *
	 * @param itemId  检查项id,如果为新增，则为-1
	 *
	 * @param queryRequests  查询条件
	 *
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "查询巡检点编号信息", notes = "查询巡检点编号信息")
	@GetMapping(value = "/queryItemNo/{itemId}", produces = "application/json;charset=UTF-8")
	public CommonResponse queryItemNoList(
			@ApiParam(value = "巡检点id", required = true) @PathVariable(name = "itemId") Long itemId,
			@ApiParam(value = "查询条件", required = false) @RequestBody(required = false) List<CommonRequest> queryRequests) {
		 ReginParams reginParams = getSelectedOrgInfo();
	        String loginOrgCode = getOrgCode(reginParams);
	        String roleTypeName = getRoleTypeName(reginParams);
		if (ObjectUtils.isEmpty(reginParams)) {
			return CommonResponseUtil.failure("用户session过期");
		}
		try {
			CommonRequest commonRequest = new CommonRequest();
			commonRequest.setName("orgCode");
			commonRequest.setValue(loginOrgCode);
			if (queryRequests == null) {
				queryRequests = new ArrayList<>();
			}
			queryRequests.add(commonRequest);
            List<DaoCriteria> criterias = buildDaoCriterias(queryRequests, false, loginOrgCode, roleTypeName);

			List<String> pointNoList = inputItemService.qryItemNoList(criterias, itemId);
			return CommonResponseUtil.success(pointNoList);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("查询检查项编号信息失败");
		}
	}

    @TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "获取检查分类", notes = "获取检查分类")
	@GetMapping(value = "/checkClassify")
	public CommonResponse getCheckClassify() {
		return CommonResponseUtil.success(inputItemService.getCheckClassify(getToken(), getProduct(), getAppKey(), DictTypeEnum.CHECK_CLASSIFY.getCode()));
	}
}
