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

import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.patrol.business.dao.mapper.CatalogTreeMapper;
import com.yeejoin.amos.patrol.business.param.CatalogTreePageParam;
import com.yeejoin.amos.patrol.business.service.intfc.ICatalogTreeService;
import com.yeejoin.amos.patrol.business.util.CatalogTreePageParamUtil;
import com.yeejoin.amos.patrol.business.util.CommonResponse;
import com.yeejoin.amos.patrol.business.util.CommonResponseUtil;
import com.yeejoin.amos.patrol.core.common.request.CommonPageable;
import com.yeejoin.amos.patrol.core.common.request.CommonRequest;
import com.yeejoin.amos.patrol.dao.entity.CatalogTree;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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 java.util.HashMap;
import java.util.List;
@RestController
@RequestMapping(value = "/api/catalogTree")
@Api(tags="分类api")
public class CatalogTreeController extends AbstractBaseController {
	private final Logger log = LoggerFactory.getLogger(CatalogTreeController.class);
	@Autowired
	private ICatalogTreeService catalogTreeService ;
	@Autowired
	private CatalogTreeMapper catalogTreeMapper;
	/**
	 * 树结构查询
	 * @param param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "树结构查询", notes = "树结构查询")
	@RequestMapping(value = "/getCatalogTree", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public CommonResponse getCatalogTree() {
		  ReginParams reginParams = getSelectedOrgInfo();
	        String orgCode = getOrgCode(reginParams);
		List<Object> list  = catalogTreeService.getCatalogTree(orgCode);
		return CommonResponseUtil.success(list);
	}

	/**
	 * 树结构查询
	 * @param param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "树结构查询", notes = "树结构查询")
	@RequestMapping(value = "/catalogList", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public CommonResponse getCatalogList() {
		  ReginParams reginParams = getSelectedOrgInfo();
	        String orgCode = getOrgCode(reginParams);
		List<CatalogTree> list  = catalogTreeService.getCatalogList(orgCode);
		return CommonResponseUtil.success(list);
	}

	/**
	 * 分类新增
	 * @param param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "分类新增", notes = "分类新增")
	@RequestMapping(value = "/addCatalogTree", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public CommonResponse catalogTreeAdd(@ApiParam(value = "分类", required = true) @RequestBody CatalogTree param) {
		try {
			 String userId = getUserId();
	            ReginParams reginParams = getSelectedOrgInfo();
	            String orgCode = getOrgCode(reginParams);
			HashMap<String,Object> map = new HashMap<String,Object>();
			map.put("org_code", orgCode);
			map.put("user_id", userId);
			map.put("param", param);

			//查询分类名称是否重复
			List<HashMap<String, Object>>  num=catalogTreeMapper.countCatalognum(param.getName());
			if(param.getId()!=0){

				if(param.getId()==param.getParentId()){
					return CommonResponseUtil.failure("上级不能为自己！");
				}

				if(num!=null){
					if(num.size()==1){
						if(param.getId()!=Long.valueOf(num.get(0).get("id").toString())){
							return CommonResponseUtil.failure("名称不能重复！");
						};
					}
				}

				// 修改上级目录不能是自己的子目录
				catalogTreeService.checkModifyCatalogTreeResult(param);

			}else{
				if(num!=null&&num.size()>0){
					return CommonResponseUtil.failure("名称不能重复！");
				}
			}

			catalogTreeService.addCatalogTree(map);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(),e);
			return CommonResponseUtil.failure(e.getMessage());
		}
	}

	/**
	 * 分类删除（支持批量）
	 * @param param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "删除分类", notes = "删除分类")
	@RequestMapping(value = "/deleteCatalogTreeById", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public CommonResponse deleteCatalogTreeById(
			@ApiParam(value = "分类ID", required = true) @RequestBody  Long[] param) {
		try {
			catalogTreeService.delCatalogTreeById(param);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			return CommonResponseUtil.failure("删除分类失败：" + e.getMessage());
		}
	}

	/**
	 * 分类数据查询
	 * @param
	 * @param param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "分类数据查询", notes = "分类数据查询")
	@RequestMapping(value = "/list", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public CommonResponse qryCatalogTreeInfoPage(@ApiParam(value = "查询条件", required = false) @RequestBody(required = false) List<CommonRequest> queryRequests,
			@ApiParam(value = "分页参数", required = true) CommonPageable commonPageable) {
		 ReginParams reginParams = getSelectedOrgInfo();
	        String orgCode = getOrgCode(reginParams);
		HashMap<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("orgCode",orgCode);
		CatalogTreePageParam param = CatalogTreePageParamUtil.fillPageParam(queryRequests, commonPageable, paramMap);
		Page<HashMap<String,Object>> list= catalogTreeService.getCatalogTreeInfo(getToken(),getProduct(),getAppKey(),param);
		return CommonResponseUtil.success(list);
	}

	/**
	 * 查询分类按照id
	 *
	 * @param id
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "查询分类按照id", notes = "查询分类按照id")
	@RequestMapping(value = "/catalogTreeDetById/{id}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public CommonResponse queryCatalogTreeById(@ApiParam(value = "分类id", required = true) @PathVariable(name = "id") Long id) {
		CatalogTree plan = catalogTreeService.queryCatalogTreeById(id);
		return CommonResponseUtil.success(plan);

	}
}
