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

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.data.domain.Page;
import org.springframework.http.MediaType;
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.RestController;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.fas.business.param.PointListParam;
import com.yeejoin.amos.fas.business.param.QueryParamUtil;
import com.yeejoin.amos.fas.business.service.intfc.ICommonService;
import com.yeejoin.amos.fas.business.service.intfc.IRiskSourceService;
import com.yeejoin.amos.fas.config.Permission;
import com.yeejoin.amos.fas.core.common.request.CommonPageable;
import com.yeejoin.amos.fas.core.common.request.CommonRequest;
import com.yeejoin.amos.fas.core.util.CommonResponse;
import com.yeejoin.amos.fas.core.util.CommonResponseUtil;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.DepartmentModel;

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

@RestController
@RequestMapping(value = "/api/common")
@Api(tags = "公共资源api")
public class CommonController extends AbstractBaseController {
    private final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ICommonService commonService;
    @Autowired
    private IRiskSourceService iRiskSourceService;



    /**
     * 根据当前用户获取公司下部门信息
     *
     * @return
     */
    @Permission
    @ApiOperation(httpMethod = "GET", value = "根据当前用户获取公司下部门信息", notes = "根据当前用户获取公司下部门信息")
    @RequestMapping(value = "/deptment/list", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse getDeptments() {
		ReginParams reginParams =getSelectedOrgInfo();
		String companyId =getCompanyId(reginParams);
        if (companyId == null) {
            return CommonResponseUtil.failure("公司信息获取失败！");
        }
        List<DepartmentModel> deps = commonService.getDepartment(getToken(),getProduct(),getAppKey(), companyId);

        return CommonResponseUtil.success(objectsToMaps(deps));
    }


    public static <T> Map<String, Object> beanToMap(T bean) { 
  	  Map<String, Object> map = Maps.newHashMap(); 
  	  if (bean != null) { 
  	    BeanMap beanMap = BeanMap.create(bean); 
  	    for (Object key : beanMap.keySet()) { 
  	    if("sequenceNbr".equals(key+"")){
    	      map.put(key+"", beanMap.get(key)+""); 

  	    }else{
    	      map.put(key+"", beanMap.get(key)); 

  	    }
  	    }       
  	  } 
  	  return map; 
  	} 
  
  public static <T> List<Map<String, Object>> objectsToMaps(List<T> objList) { 
  	  List<Map<String, Object>> list = Lists.newArrayList(); 
  	  if (objList != null && objList.size() > 0) { 
  	    Map<String, Object> map = null; 
  	    T bean = null; 
  	    for (int i = 0,size = objList.size(); i < size; i++) { 
  	      bean = objList.get(i); 
  	      map = beanToMap(bean); 
  	      list.add(map); 
  	    } 
  	  } 
  	  return list; 
  	}
    
    /**
     * 查询巡检点信息
     *
     * @param
     * @return
     */
  	@Permission
    @ApiOperation(value = "查询巡检点信息", notes = "查询巡检点信息")
    @PostMapping(value = "/pointList", produces = "application/json;charset=UTF-8")
    public CommonResponse getPoints(
            @ApiParam(value = "查询条件", required = false) @RequestBody(required = false) List<CommonRequest> queryRequests,
            @ApiParam(value = "分页参数", required = true, defaultValue = "pageNumber=0&pageSize=10") CommonPageable commonPageable) {
        try {
            PointListParam params = new PointListParam();
            QueryParamUtil.fillPointListParam(queryRequests, commonPageable, params);
            Page<HashMap<String, Object>> pointList = commonService.getPointList(params);
            return CommonResponseUtil.success(pointList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResponseUtil.failure("查询巡检点信息失败");
        }
    }


    /**
     * 根据巡检点查询巡检项
     *
     * @param
     * @return
     */
    //@Authorization(ingore = true)
  	@Permission
    @ApiOperation(value = "查询巡检点项信息", notes = "查询巡检点项信息")
    @PostMapping(value = "/pointInputlist", produces = "application/json;charset=UTF-8")
    public CommonResponse getPointInputs(
            @ApiParam(value = "查询条件", required = false) @RequestBody(required = false) List<CommonRequest> queryRequests,
            @ApiParam(value = "分页参数", required = true, defaultValue = "pageNumber=0&pageSize=10") CommonPageable commonPageable) {

        try {
            PointListParam params = new PointListParam();
//			params.setOrgCode(getUserInfo().getOrgCode());
            QueryParamUtil.fillPointListParam(queryRequests, commonPageable, params);
            Page<HashMap<String, Object>> pointInputList = commonService.getPointInputList(params);
            return CommonResponseUtil.success(pointInputList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResponseUtil.failure("查询巡检点信息失败");
        }
    }

    /**
     * 根据部门获取部门人员信息
     *
     * @return
     */
  	@Permission
    @ApiOperation(httpMethod = "GET", value = "根据部门获取部门人员信息", notes = "根据部门获取部门人员信息")
    @RequestMapping(value = "/{departmentId}/user/list", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse getUsers(@ApiParam(value = "部门ID", required = true) @PathVariable String departmentId) {
        if (departmentId == null) {
            return CommonResponseUtil.failure("部门信息获取失败！");
        }
        List<AgencyUserModel> users = commonService.getUsers(getToken(),getProduct(),getAppKey(),departmentId);
        return CommonResponseUtil.success(users);
    }

  	@Permission
    @ApiOperation(httpMethod = "GET", value = "获取公司下人员列表", notes = "获取公司下人员列表")
    @GetMapping(value = "/user/list", produces = "application/json;charset=UTF-8")
    public  CommonResponse getAllUser() {
    	ReginParams reginParams = getSelectedOrgInfo();
		String compCode = getOrgCode(reginParams);
        List<AgencyUserModel> users = commonService.getAllUser(getToken(),getProduct(),getAppKey(), compCode);
        return CommonResponseUtil.success(users);
    }

    @ApiOperation(value = "查询公司下的风险模型（厂区、区域、风险点）")
    @GetMapping(value = "/riskSource/list/{orgCode}",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public CommonResponse getRiskSourceList(@PathVariable String orgCode){
        return CommonResponseUtil.success(iRiskSourceService.findRiskSourceTrees(orgCode));
    }
}
