package com.palmnest.webapp.controller.permission;

import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.ElementConstant;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.AppResultUtil;
import com.palmnest.application.dto.OrgDto;
import com.palmnest.application.dto.WebPageResultDto;
import com.palmnest.application.dto.bo.VirServiceBO;
import com.palmnest.application.dto.output.GoodsConfigDto;
import com.palmnest.application.dto.output.enterprise.OpenedFunctionOutDto;
import com.palmnest.application.dto.output.enterprise.VirPermConfigDTO;
import com.palmnest.model.User;
import com.palmnest.service.AppUserService;
import com.palmnest.service.estateserve.EnterprisePermissionManager;
import com.palmnest.service.estateserve.ServiceProjectAllocationManager;
import com.palmnest.webapp.controller.BaseFormController;

import lombok.extern.slf4j.Slf4j;

import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import scala.Int;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

/**
 * @Author hxt
 * @Description 企业功能权限控制类
 * @Date 2019/2/15 15:54
 **/
@Slf4j
@Controller
@RequestMapping(value = "/admin/virPerm/*")
public class EnterprisePermissionController extends BaseFormController {


	@Autowired
	private ServiceProjectAllocationManager serviceProjectAllocationManager;
	@Autowired
	private EnterprisePermissionManager     enterprisePermissionManager;
	@Autowired
	private AppUserService                  appUserService;

	/**
	 * 跳转企业权限类型列表页面
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/toVirPermTypePage")
	public ModelAndView toVirPermTypePage(HttpServletRequest request, HttpServletResponse response) {
		Model model = new ExtendedModelMap();
		User  user  = (User) request.getSession().getAttribute("UserCache");
		if (!user.isAdmin()) {
			// 是项目管理员或普通管理员,项目只有一个
			List<OrgDto> dtos = appUserService.getUserOrgs(user.getId());
			model.addAttribute("org", dtos.get(0));
		}

		model.addAttribute("isAdmin", user.isAdmin());
		return new ModelAndView("admin/virPerm/virPermList", model.asMap());
	}

	/**
	 * 跳转身份类型列表页面
	 *
	 * @return
	 */
	@RequestMapping(value = "/toIdentityTypePage")
	public ModelAndView toIdentityTypePage(HttpServletRequest request) {

		Model model = new ExtendedModelMap();

		User user = (User) request.getSession().getAttribute("UserCache");

		if (!user.isAdmin()) {
			// 是项目管理员或普通管理员,项目只有一个
			List<OrgDto> dtos = appUserService.getUserOrgs(user.getId());
			model.addAttribute("org", dtos.get(0));
		}

		initPageOrgInfo(request, model);
		return new ModelAndView("admin/virPerm/identityList", model.asMap());
	}

	/**
	 * 获取企业权限列表
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/virPermList")
	@ResponseBody
	public WebPageResultDto virPermList(HttpServletRequest request) {

		User         user   = (User) request.getSession().getAttribute("UserCache");
		StringBuffer strSbf = new StringBuffer(" where 1=1");

		String orgId       = request.getParameter("orgId");
		String virPermName = request.getParameter("virPermName");
		String permType    = request.getParameter("permType");// 类型 0-企业权限 1-身份权限
		String pageSize    = request.getParameter("pageSize");
		String pageNo      = request.getParameter("pageNo");

		String virId = request.getParameter("virId");// 企业ID,企业账号查询是有

		if (StringUtils.isBlank(pageNo)) {
			pageNo = "1";
		}

		if (StringUtils.isBlank(pageSize)) {
			pageSize = "10";
		}

		if (StringUtils.isNotBlank(virPermName)) {
			strSbf.append(" and t1.name like '%" + virPermName + "%'");
		}

		if (StringUtils.isBlank(orgId)) {
			orgId = getUserManageOrgIds(user);
		}

		if (StringUtils.isNotBlank(virId) && user.getUserType() == 5) {
			strSbf.append(" and t1.virId=" + virId);
		}

		strSbf.append(" and t1.isEnable='" + ElementConstant.YESORNO_1 + "'");
		strSbf.append(" and t1.permType=" + permType);
		strSbf.append(" and t1.orgId in(" + orgId + ")");

		try {
			Page             pagenation = enterprisePermissionManager.queryVirPermListPage(Integer.parseInt(pageNo), Integer.parseInt(pageSize), strSbf.toString());
			WebPageResultDto dto        = new WebPageResultDto("200", "成功", pagenation.getItems());
			dto.setCount(pagenation.getTotalCount());
			return dto;
		} catch (Exception e) {
			log.error("查询企业权限列表失败 virPermList ===>" + e.getMessage(), e);
		}

		return new WebPageResultDto("100", "查询企业权限列表失败", null);
	}

	/**
	 * 添加/修改 企业权限类型
	 *
	 * @param serviceId 服务id串,用分号";"相隔
	 * @return
	 */
	@RequestMapping(value = "/addUpdateVirPerm")
	@ResponseBody
	public AppResultDto addUpdateVirPerm(HttpServletRequest request,
										 @RequestParam String serviceId,
										 @RequestParam String serviceChildId,
										 @RequestParam Integer checkRole,
										 @RequestParam Integer orgId,
										 @RequestParam String virPermName,
//                                         @RequestParam Integer isGeneral,
										 @RequestParam(required = false) Long id,
										 @RequestParam Integer permType,
										 @RequestParam(required = false) Integer virId) {

		User user = (User) request.getSession().getAttribute("UserCache");

		VirServiceBO virServiceBO = new VirServiceBO();

		virServiceBO.setCreator(user.getId());
//        virServiceBO.setIsGeneral(isGeneral);
		virServiceBO.setOrgId(orgId);
		virServiceBO.setServiceId(serviceId);
		virServiceBO.setServiceChildId(serviceChildId);
		virServiceBO.setVirPermName(virPermName);
		virServiceBO.setId(id);
		virServiceBO.setVirId(virId);
		virServiceBO.setPermType(permType);

		if (checkRole == null) {
			checkRole = 0;
		}
		virServiceBO.setCheckRole(checkRole);
		try {
			enterprisePermissionManager.addUpdateVirPerm(virServiceBO);
			return AppResultUtil.createSuccesDto();
		} catch (Exception e) {
			log.error("EnterprisePermissionController addUpdateVirPerm error==>" + e.getMessage(), e);
		}

		return AppResultUtil.createErrorDto("100", "操作失败");
	}

	/**
	 * 删除操作
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/delVirPerm")
	@ResponseBody
	public AppResultDto delVirPerm(@RequestParam Long id) {
		try {
			enterprisePermissionManager.delVirPerm(id);
			return AppResultUtil.createSuccesDto();
		} catch (Exception e) {
			log.error("EnterprisePermissionController delVirPerm error==>" + e.getMessage(), e);
		}

		return AppResultUtil.createErrorDto("100", "操作失败");
	}


	/**
	 * 批量设置企业功能权限
	 *
	 * @param virIds
	 * @param virPermId
	 * @return
	 */
	@RequestMapping(value = "/batchSetVirPerm")
	@ResponseBody
	public AppResultDto batchSetVirPerm(@RequestParam String virIds, @RequestParam String virPermId) {

		try {
			enterprisePermissionManager.batchSetVirPerm(virIds, virPermId);
			return AppResultUtil.createSuccesDto();
		} catch (Exception e) {
			log.error("EnterprisePermissionController batchSetVirPerm error==>" + e.getMessage(), e);
		}

		return AppResultUtil.createErrorDto("100", "操作失败");

	}

	/**
	 * 获取企业权限类型详情信息
	 *
	 * @return
	 */
	@RequestMapping(value = "/virPermInfo")
	@ResponseBody
	public AppResultDto virPermInfo(@RequestParam Long virPermId) {

		try {
			VirPermConfigDTO dto = enterprisePermissionManager.virPermInfo(virPermId);
			return AppResultUtil.createSuccesDto(dto);
		} catch (Exception e) {
			log.error("EnterprisePermissionController virPermInfo error==>" + e.getMessage(), e);
		}

		return AppResultUtil.createErrorDto("100", "操作失败");
	}

	/**
	 * 获取该项目开启的功能权限列表
	 *
	 * @param orgId 项目id
	 * @return
	 */
	@RequestMapping(value = "/openedFunctionPermissionList")
	@ResponseBody
	public AppResultDto openedFunctionPermissionList(@RequestParam Integer orgId) {

		// 获取当前项目开启功能权限的功能列表
		List<OpenedFunctionOutDto> serviceList   = serviceProjectAllocationManager.getOpenedFunctionServiceList(orgId);
		List<Integer>              serviceIdList = new ArrayList<>();

		for (OpenedFunctionOutDto openedFunctionOutDto : serviceList) {
			serviceIdList.add(openedFunctionOutDto.getServiceId());
		}

		List<OpenedFunctionOutDto> serviceChildList = serviceProjectAllocationManager.getOpenedFunctionServiceChildList(serviceIdList);

		Map<String, Object> map = new HashMap<>();

		map.put("funcList", serviceList);
		map.put("funcChildList", serviceChildList);

		return AppResultUtil.createSuccesDto(map);
	}

	/**
	 * 获取该项目下的企业权限列表
	 *
	 * @param orgId 项目id
	 * @return
	 */
	@RequestMapping(value = "/getOrgRelationVirPermList")
	@ResponseBody
	public AppResultDto getOrgRelationVirPermList(@RequestParam Integer orgId) {
		List<Map<String, Object>> orgRelationVirPermList = enterprisePermissionManager.getOrgRelationVirPermList(orgId);
		return AppResultUtil.createSuccesDto(orgRelationVirPermList);
	}

	/**
	 * 新增或者修改审核配置
	 *
	 * @param orgId 项目id
	 * @return
	 */
	@RequestMapping(value = "/saveOrUpdateGoodsConfig")
	@ResponseBody
	public AppResultDto saveOrUpdateGoodsConfig(@RequestParam Long orgId,
												@RequestParam(value = "companyName", required=false) String companyName,
												@RequestParam(value = "type", required=false) String type,
												HttpServletRequest request) {

		try {
			log.error("EnterprisePermissionController saveOrUpdateGoodsConfig companyName==>" +companyName);
			boolean isSaveGoodsRelease = false;//是否保存物品放行

			String virList = request.getParameter("virList");
			String proList = request.getParameter("proList");


			if (StringUtils.isNotEmpty(virList) || StringUtils.isNotEmpty(proList)) {
				isSaveGoodsRelease = true;
			}

			String passVirList = request.getParameter("passVirList");
			String passProList = request.getParameter("passProList");

			String[] virLists = null;
			String[] proLists = null;

			String[] passVirLists = null;
			String[] passProLists = null;


			if (StringUtils.isNotBlank(virList)) {
				virLists = virList.split(";");
			}
			if (StringUtils.isNotBlank(proList)) {
				proLists = proList.split(";");
			}

			//@RequestParam(value="", required=false) String passvirList, @RequestParam(value="", required=false) String passProList

			//@RequestParam String virList, @RequestParam String proList


			if (StringUtils.isNotBlank(passVirList)) {
				passVirLists = passVirList.split(";");
			}
			if (StringUtils.isNotBlank(passProList)) {
				passProLists = passProList.split(";");
			}

			enterprisePermissionManager.saveOrUpdateGoodsConfig(orgId, virLists, proLists, passVirLists, passProLists, isSaveGoodsRelease, companyName,type);
			return AppResultUtil.createSuccesDto();
		} catch (Exception e) {
			log.error("EnterprisePermissionController delVirPerm error==>" + e.getMessage(), e);
		}
		return AppResultUtil.createErrorDto("100", "操作失败");
	}

	/**
	 * 新增或者修改审核配置
	 *
	 * @param orgId 项目id
	 * @return
	 */
	@RequestMapping(value = "/saveOrUpdateMoreGoodsConfig")
	@ResponseBody
	public AppResultDto saveOrUpdateMoreGoodsConfig(@RequestParam Long orgId,
												@RequestParam(value = "companyName", required=false) String companyName,
												@RequestParam(value = "type", required=false) String type,
												HttpServletRequest request) {

		try {
			log.error("EnterprisePermissionController saveOrUpdateGoodsConfig companyName==>" +companyName);
			boolean isSaveGoodsRelease = true;//是否保存物品放行
			//if("1".equals(type)){
			//	isSaveGoodsRelease = true;
			//}

			//审核模式 1-单审核流程 2-多审核流程
			Integer processType = Integer.valueOf(request.getParameter("processType"));

			String    goodsConfigListJson = request.getParameter("goodsConfigListJson");
			log.error("EnterprisePermissionController saveOrUpdateGoodsConfig goodsConfigListJson==>" +goodsConfigListJson);
			List<GoodsConfigDto> goodsConfigList       = com.alibaba.fastjson.JSON.parseArray(goodsConfigListJson, GoodsConfigDto.class);



			enterprisePermissionManager.delMoreGoodsConfig(orgId,isSaveGoodsRelease);


			for(GoodsConfigDto configDto : goodsConfigList){

				String processName = configDto.getProcessName(); //流程名称

				String virList = configDto.getVirList();
				String proList = configDto.getProList();

                String virNameList = configDto.getVirNameList();
                String proNameList = configDto.getProNameList();

				//String passVirList = configDto.getPassVirList();
				//String passProList = configDto.getPassProList();


				//if (StringUtils.isNotEmpty(virList) || StringUtils.isNotEmpty(proList)) {
				//	isSaveGoodsRelease = true;
				//}

				String[] virLists = null;
				String[] proLists = null;

                String[] virNameLists = null;
                String[] proNameLists = null;

				//String[] passVirLists = null;
				//String[] passProLists = null;


				if (StringUtils.isNotBlank(virList)) {
					virLists = virList.split(";");
				}
				if (StringUtils.isNotBlank(proList)) {
					proLists = proList.split(";");
				}

                if (StringUtils.isNotBlank(virNameList)) {
                    virNameLists = virNameList.split(";");
                }
                if (StringUtils.isNotBlank(proNameList)) {
                    proNameLists = proNameList.split(";");
                }

				//if (StringUtils.isNotBlank(passVirList)) {
				//	passVirLists = passVirList.split(";");
				//}
				//if (StringUtils.isNotBlank(passProList)) {
				//	passProLists = passProList.split(";");
				//}

				//enterprisePermissionManager.saveOrUpdateGoodsConfig(orgId, virLists, proLists, passVirLists, passProLists, isSaveGoodsRelease, companyName,type);
				  enterprisePermissionManager.saveOrUpdateMoreGoodsConfig(orgId, processType,processName,virLists, proLists, virNameLists, proNameLists, isSaveGoodsRelease, companyName,type);
			}


			return AppResultUtil.createSuccesDto();

		} catch (Exception e) {
			log.error("EnterprisePermissionController delVirPerm error==>" + e.getMessage(), e);
		}
		return AppResultUtil.createErrorDto("100", "操作失败");
	}

	
	/**
	 * 新增或者修改空调审核配置
	 *
	 * @param orgId 项目id
	 * @return
	 */
	@RequestMapping(value = "/saveOrUpdateAirConfig")
	@ResponseBody
	public AppResultDto saveOrUpdateAirConfig(@RequestParam Long orgId, HttpServletRequest request) {

		try {

			String virList = request.getParameter("virList");
			String proList = request.getParameter("proList");
			
			String[] virLists = null;
			String[] proLists = null;		

			if (StringUtils.isNotBlank(virList)) {
				virLists = virList.split(";");
			}
			if (StringUtils.isNotBlank(proList)) {
				proLists = proList.split(";");
			}	

			enterprisePermissionManager.saveOrUpdateAirConfig(orgId, virLists, proLists);
			
			return AppResultUtil.createSuccesDto();
		} catch (Exception e) {
			log.error("EnterprisePermissionController delVirPerm error==>" + e.getMessage(), e);
		}
		return AppResultUtil.createErrorDto("100", "操作失败");
	}
	
	
	/**
	 * 获取审核流程
	 *
	 * @param orgId
	 * @return
	 */
	@RequestMapping(value = "/getGoodsConfig")
	@ResponseBody
	public AppResultDto getGoodsConfig(@RequestParam Long orgId,HttpServletRequest request) {
		
		User user = (User) request.getSession().getAttribute("UserCache");
		List<OrgDto> organizationList = appUserService.getUserOrgs(user.getId());
		if (organizationList.size() >= 1) {
			orgId = Long.valueOf(organizationList.get(0).getId().toString());
		}
		String  paramOrgId = request.getParameter("orgId");
		if(StringUtils.isNotEmpty(paramOrgId)){
			orgId = Long.valueOf(paramOrgId);
		}

		return AppResultUtil.createSuccesDto(enterprisePermissionManager.getGoodsConfig(orgId));
	}

	/**
	 * 获取审核流程--多级
	 *
	 * @param orgId
	 * @return
	 */
	@RequestMapping(value = "/getMoreGoodsConfig")
	@ResponseBody
	public AppResultDto getMoreGoodsConfig(@RequestParam Long orgId,HttpServletRequest request) {

		User user = (User) request.getSession().getAttribute("UserCache");
		List<OrgDto> organizationList = appUserService.getUserOrgs(user.getId());
		if (organizationList.size() >= 1) {
			orgId = Long.valueOf(organizationList.get(0).getId().toString());
		}
		String  paramOrgId = request.getParameter("orgId");
		if(StringUtils.isNotEmpty(paramOrgId)){
			orgId = Long.valueOf(paramOrgId);
		}


		List<Map<String, Object>>  listProcessName = enterprisePermissionManager.getProcessName(orgId,"1,2");

		Integer processType = 1;
		List list = new ArrayList();
		for(Map processNameMap : listProcessName){
			
			String processName = (String)processNameMap.get("processName");
			
			Map<String, Object> mapGoodsConfig  = enterprisePermissionManager.getMoreGoodsConfig(orgId,processName);
			processType = Integer.valueOf(mapGoodsConfig.get("processType").toString());
			list.add(mapGoodsConfig);
		}

		JSONObject ob = new JSONObject();
		ob.put("processType",processType);
		ob.put("configList",list);

		return AppResultUtil.createSuccesDto(ob);
	}

	/**
	 * 获取审核流程
	 *
	 * @param orgId
	 * @return
	 */
	@RequestMapping(value = "/getPermByCheckRole")
	@ResponseBody
	public AppResultDto getPermByCheckRole(@RequestParam Long orgId,@RequestParam Integer pageType,HttpServletRequest request) {

		User user = (User) request.getSession().getAttribute("UserCache");
		List<OrgDto> organizationList = appUserService.getUserOrgs(user.getId());
		if (organizationList.size() >= 1) {
			orgId = Long.valueOf(organizationList.get(0).getId().toString());
		}
		if(null == pageType){//pageType 1-物品放行 2-空调加时 
			pageType = 1;//
		}
		return AppResultUtil.createSuccesDto(enterprisePermissionManager.getPermByCheckRole(orgId));
	}
}
