package com.palmnest.webapp.controller.api;

import com.palmnest.application.AppConstants;
import com.palmnest.application.CodeConstants;
import com.palmnest.application.GoodsCodeConstants;
import com.palmnest.application.bean.AppCommonResultDto;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.AppResultUtil;
import com.palmnest.application.core.util.LogExceptionStackUtil;
import com.palmnest.application.dto.OrgDto;
import com.palmnest.application.dto.input.GoodsReleaseBillInputDto;
import com.palmnest.application.dto.input.GoodsReleaseOpRecorInputDto;
import com.palmnest.application.dto.output.GoodsReleaseOutDto;
import com.palmnest.model.User;
import com.palmnest.service.ElementGroupManager;
import com.palmnest.service.RoleManager;
import com.palmnest.service.UserManager;
import com.palmnest.service.estateserve.EnterprisePermissionManager;
import com.palmnest.service.estateserve.ScWxuserManager;
import com.palmnest.service.estateserve.release.GoodsReleaseService;
import com.palmnest.service.redis.BaseRedisService;
import com.palmnest.webapp.controller.BaseFormController;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
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.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;

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


/**
 * 标记 电子放行条 ? 电子通行证
 */
@Slf4j
@Controller
@RequestMapping(value = "/api/release")
public class ApiGoodsReleaseController extends BaseFormController {


	@Autowired
	private GoodsReleaseService goodsReleaseService;
	@Autowired
	private ScWxuserManager     scWxuserManager;
	@Autowired
	private UserManager         userManager;
	@Autowired
	private ElementGroupManager elementGroupManager;
	@Autowired
	private BaseRedisService    baseRedisService;
	
	@Autowired
	private EnterprisePermissionManager enterprisePermissionManager;
	
	@Autowired
	private RoleManager           roleManager;


	/**
	 * 提交物品放行申请
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/apply")
	@ResponseBody
	public AppResultDto apply(@ModelAttribute("goodsReleaseBillInputDto") GoodsReleaseBillInputDto dto, MultipartHttpServletRequest request) {

		log.info("ApiGoodsReleaseController apply======");

		return goodsReleaseService.apply(dto, request);
	}

	/**
	 * 同意放行
	 */
	@RequestMapping(value = "/agree")
	@ResponseBody
	public AppResultDto agree(@ModelAttribute("goodsReleaseBillInputDto") GoodsReleaseBillInputDto dto, MultipartHttpServletRequest request) {

		log.info("ApiGoodsReleaseController agree======");

		dto.setBillFrom(CodeConstants.ANDROID);

		AppResultDto rdto = goodsReleaseService.agree(dto, request);

		try {

			GoodsReleaseOutDto gDto = (GoodsReleaseOutDto) ((AppCommonResultDto) rdto).getData();
			goodsReleaseService.push(gDto.getId());

		} catch (Exception e) {
			e.printStackTrace();
		}

		return rdto;
	}

	/**
	 * 拒绝放行
	 */
	@RequestMapping(value = "/refuse")
	@ResponseBody
	public AppResultDto refuse(@ModelAttribute("goodsReleaseBillInputDto") GoodsReleaseBillInputDto dto, HttpServletRequest request) {

		log.info("ApiGoodsReleaseController refuse======");

		dto.setBillFrom(CodeConstants.ANDROID);

		return goodsReleaseService.refuse(dto, request);
	}


	/**
	 * 安保扫描后-填写温度-准予通行或拒绝通行
	 */
	@RequestMapping(value = "/releaseOperation")
	@ResponseBody
	public AppResultDto releaseOperation(@ModelAttribute("goodsReleaseOpRecorInputDto") GoodsReleaseOpRecorInputDto dto, HttpServletRequest request) {

		log.info("ApiGoodsReleaseController releaseOperation======");

		return goodsReleaseService.releaseOperation(dto, request);
	}


	/**
	 * @return 查找维修单详情
	 */
	@RequestMapping(value = "/getDetail")
	@ResponseBody
	public AppResultDto getDetail(@RequestParam("id") String id, HttpServletRequest request) {

		log.info("ApiGoodsReleaseController getDetail======");

		return AppResultUtil.createSuccesDto(goodsReleaseService.findById(id));
	}


	/**
	 * 客服首页脚标数量
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/indexTotal")
	@ResponseBody
	public AppResultDto indexTotal(HttpServletRequest request) {

		log.info("ApiGoodsReleaseController indexTotal======");

		String userName = baseRedisService.get(request.getHeader("token"));

		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}

		//客服审批权限
		try {
			Map<String, Object> params = new HashMap<String, Object>();

//			//放行类型
//			String releaseType="279";
//			List<Element> releaseTypeGroup = elementGroupManager.getElementsByGroupName("releaseTypeGroup");
//			for(Element e : releaseTypeGroup) {
//				if(StringUtils.isNotEmpty(e.getItemcode()) && GoodsCodeConstants.RELEASETYPE_J.equals(e.getItemcode())){
//					releaseType=e.getId().toString();
//				}
//			}

			//params.put("releaseType", releaseType);//用数据字典 家电类
			params.put("companyHeadUser", "companyHeadUser");//企业审批过的
			params.put("releaseStatus", GoodsCodeConstants.ST_AUDITING);//状态：审批中

			Integer num = goodsReleaseService.findCountBy(params);

			Map returnMap = new HashMap();

			returnMap.put("auditNum", num + "");

			return AppResultUtil.createSuccesDto(returnMap);

		} catch (Exception e) {
			e.printStackTrace();
			return AppResultUtil.createErrorDto(AppConstants.REPAIR_BILL_LIST_ERROR, "查询首页脚标数量失败");
		}
	}

	/**
	 * @param request
	 * @return 物品放行列表
	 */
	@RequestMapping(value = "/auditList")
	@ResponseBody
	public AppResultDto auditList(HttpServletRequest request) {

		log.info("ApiGoodsReleaseController auditList======");

		try {

			int pageSize = Integer.parseInt(request.getParameter("pageSize"));
			int pageNo   = Integer.parseInt(request.getParameter("pageNo"));

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

			String releaseStatus = request.getParameter("releaseStatus");
			String roleType      = request.getParameter("roleType");
			String applyType     = request.getParameter("applyType");

			//String openId = request.getParameter("openId");		
			//WxUser wxUser = scWxuserManager.getScWxuserByOpenId(openId);
			
			
			/*String userName = baseRedisService.get(request.getHeader("token"));
			if(userName == null) {
				return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
			}*/
			//User user = userManager.getUserByUsername2(userName);	


			//客服物品放行审批列表(包括放行历史接口 已放行5 已拒绝15
			//params.put("creatorBillId", user.getId());
			params.put("releaseStatus", releaseStatus);
			params.put("applyType", applyType);

			//params.put("companyHeadUser", "companyHeadUser");

			//过滤安保自己的记录
			//2018.10.18 改为安保可看到所有人的放行历史(服务之窗基于中航中心需求改动)
//			if(StringUtils.isNotEmpty(roleType)&&"5".equals(roleType)){//角色类型(1客服 5安保
//				String userName = baseRedisService.get(request.getHeader("token"));
//				if(userName == null) {
//					return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
//				}
//				User user = userManager.getUserByUsername2(userName);
//				params.put("releaseUser", user.getId()+"");
//			}
			String orgIds = getAppUserManageOrgIds(request);
			params.put("orgIds", orgIds);
			//企业处理过，才显示

			Page page = goodsReleaseService.findPageBy(params, pageSize, pageNo);

			return AppResultUtil.createSuccesDto(page);

		} catch (Exception e) {
			e.printStackTrace();
			return AppResultUtil.createErrorDto(AppConstants.REPAIR_BILL_LIST_ERROR, "查询列表失败" + LogExceptionStackUtil.LogExceptionStack(e));
		}
	}

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

		log.info("ApiGoodsReleaseController getGoodsConfig======");

		String applyType = request.getParameter("applyType");

		Integer type = 0;
		if (StringUtils.isNotEmpty(applyType) && applyType.equals("1")) {
			type = 1;
		}

		boolean flag = goodsReleaseService.getGoodsConfig(orgId, type);

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

		if (flag) {
			map.put("config", 1);
			return AppResultUtil.createSuccesDto(map);
		}

		map.put("config", 0);

		return AppResultUtil.createSuccesDto("该项目没有配置审核流程", map);
	}
	
	/**
	 * 获取审核流程
	 *
	 * @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));
	}
	
	/**
	 * 根据 SysCode 和 OrgId 查询角色列表
	 *
	 * @param orgId
	 * @return
	 */
	@RequestMapping(value = "/getRoleByOrgAndSysCode")
	@ResponseBody
	public AppResultDto getRoleByOrgAndSysCode(@RequestParam Integer orgId,@RequestParam Integer pageType,HttpServletRequest request) {

		try {
			/*User user = (User) request.getSession().getAttribute("UserCache");
			List<OrgDto> organizationList = appUserService.getUserOrgs(user.getId());
			if (organizationList.size() >= 1) {
				orgId = organizationList.get(0).getId();
			}*/
			if(null == pageType){//pageType 1-物品放行 2-空调加时 
				pageType = 1;//
			}
			return AppResultUtil.createSuccesDto(roleManager.getRoleByOrgAndSysCode(orgId,pageType));
		} catch (Exception e) {
			log.error("查询角色列表失败 getRoleByOrgAndSysCode ===>" + e.getMessage(), e);
		}

		return AppResultUtil.createErrorDto("100", "查询角色列表失败");
	}
	
	/**
	 * 获取审核流程
	 *
	 * @param orgId
	 * @return
	 */
	@RequestMapping(value = "/getApiGoodsConfig")
	@ResponseBody
	public AppResultDto getApiGoodsConfig(@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());
		}*/
		return AppResultUtil.createSuccesDto(enterprisePermissionManager.getGoodsConfig(orgId));
	}

}
