package com.palmnest.webapp.controller.backstage;

import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.FileUploadUtils;
import com.palmnest.application.core.util.UUIDUitl;
import com.palmnest.application.dto.OutTreeDTO;
import com.palmnest.model.Element;
import com.palmnest.model.estateserve.ServiceProjectAllocation;
import com.palmnest.model.estateserve.ServiceTypeInfo;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.service.estateserve.ServiceProjectAllocationManager;
import com.palmnest.service.estateserve.ServiceTypeInfoManager;
import com.palmnest.service.property.PropertyManager;
import com.palmnest.webapp.controller.BaseFormController;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang.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.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Slf4j
@Controller
@RequestMapping("/service/type/*")
public class ServiceTypeInfoController extends BaseFormController {


	@Autowired
	private ServiceTypeInfoManager serviceTypeInfoManager;

	@Autowired
	private ServiceProjectAllocationManager serviceProjectAllocationManager;

	@Autowired
	private PropertyManager propertyManager;

	public void initModel(Model model) {
		model.addAttribute("jumpGroupType", this.getElementGroupManager().getElementsByGroupName("JumpGroupType"));
		model.addAttribute("serviceGroupType", this.getElementGroupManager().getElementsByGroupName("serviceGroupType"));
		model.addAttribute("registerStatusGroupType", this.getElementGroupManager().getElementsByGroupName("registerStatusGroupType"));
		model.addAttribute("DepositTypeGroup", this.getElementGroupManager().getElementsByGroupName("DepositTypeGroup"));
		model.addAttribute("isSignContractGroupType", this.getElementGroupManager().getElementsByGroupName("isSignContractGroupType"));
		model.addAttribute("visitPrefix", FileUploadUtils.getVisitPrefix());
		model.addAttribute("serviceCategory", this.getElementGroupManager().getElementsByGroupName("serviceCategory"));//服务分类
	}

	/**
	 * 查询服务内容信息列表
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/serviceTypeInfoPage")
	public ModelAndView serviceTypeInfoPage(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Model model = new ExtendedModelMap();
		try {
			initFunctionOperate(request); //初始化功能操作权限
			initModel(model);
			String pageNo = request.getParameter("pageNo");
			if (StringUtils.isEmpty(pageNo)) {
				pageNo = "1";
			}
			String paramValue  = request.getParameter("paramValue");
			String serviceType = request.getParameter("serviceType");
			String whereSql    = " where isEnabled=1 and serviceStatus=0";
			if (StringUtils.isNotBlank(paramValue)) {
				model.addAttribute("paramValue", paramValue);
				whereSql += " and serviceName like '%" + paramValue + "%'";
			}
			if (StringUtils.isBlank(serviceType)) {
				serviceType = this.getElementGroupManager().getElementsByGroupName("serviceGroupType").get(0).getItemcode();
			}
			if (StringUtils.isNotBlank(serviceType)) {
				model.addAttribute("serviceType", serviceType);
				whereSql += " and serviceType =" + serviceType;
			}
			whereSql += " order by createTime desc";
			Page                      page    = serviceTypeInfoManager.serviceTypeInfoPage(Integer.parseInt(pageNo), 10, whereSql);
			List<Element>             list    = this.getElementGroupManager().getElementsByGroupName("paymentTypeGroup");
			List<Map<String, Object>> listMap = page.getItems();
			for (int i = 0; i < listMap.size(); i++) {
				String              paymentName        = "";
				Map<String, Object> map                = listMap.get(i);
				String              paymentType        = map.get("paymentType") + "";
				String              paymentTypeArray[] = paymentType.split(",");
				for (String str : paymentTypeArray) {
					for (Element element : list) {
						if (element.getItemcode().equals(str)) {
							paymentName += element.getItemname() + ",";
						}
					}
				}
				if (StringUtils.isNotBlank(paymentName)) {
					map.put("paymentName", paymentName.substring(0, paymentName.lastIndexOf(",")));
				}
				listMap.set(i, map);
			}
			page.setItems(listMap);
			model.addAttribute("paymentTypeGroup", list);
			model.addAttribute("serviceStatus", "0");
			model.addAttribute("page", page);
			return new ModelAndView("/admin/service/serviceTypeInfoList", model.asMap());
		} catch (Exception e) {
			log.error("controller find ServiceTypeInfoPage error{}", e);
		}
		return null;
	}

	@RequestMapping(value = "/saveUpdateServiceTypeInfo", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")
	public @ResponseBody
	String saveUpdateServiceTypeInfo(HttpServletRequest request,
									 HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String id            = request.getParameter("id");
			String serviceName   = request.getParameter("serviceName");
			String serviceRemark = request.getParameter("serviceRemark");
//			String code=request.getParameter("code");// 服务编码自动生成
			String serviceIcon    = request.getParameter("serviceIcon");
			String skipAddress    = request.getParameter("skipAddress");
			String jumpAddress    = request.getParameter("jumpAddress");
			String serviceType    = request.getParameter("serviceType");
			String serviceStatus  = request.getParameter("serviceStatus");
			String linkUrlType    = request.getParameter("linkUrlType");
			String registerStatus = request.getParameter("registerStatus");
			String actype         = request.getParameter("actype");
			String organizationId = request.getParameter("organizationId");
			String roleGroup      = request.getParameter("roleGroup");
			String paymentType    = request.getParameter("paymentType");
			String depositType    = request.getParameter("depositType");
			String isSignContract = request.getParameter("isSignContract");

			String grayAppServiceIcon    = request.getParameter("grayAppServiceIcon");
			String grayWechatServiceIcon = request.getParameter("grayWechatServiceIcon");
			String serviceCategory       = request.getParameter("serviceCategory");
			String grayUrl               = request.getParameter("grayUrl");//灰度图标链接跳转路径

			ServiceTypeInfo serviceTypeInfo = new ServiceTypeInfo();
//			serviceTypeInfo.setCode(code);
			serviceTypeInfo.setIsSignContract(isSignContract);
			serviceTypeInfo.setServiceName(serviceName);
			serviceTypeInfo.setServiceRemark(serviceRemark);
			serviceTypeInfo.setSkipAddress(skipAddress);
			serviceTypeInfo.setJumpAddress(jumpAddress);
			serviceTypeInfo.setPaymentType(paymentType);
			serviceTypeInfo.setServiceType(serviceType);
			serviceTypeInfo.setDepositType(depositType);
			serviceTypeInfo.setServiceStatus(serviceStatus);
			serviceTypeInfo.setRegisterStatus(registerStatus);
			serviceTypeInfo.setServiceIcon(serviceIcon);
			serviceTypeInfo.setLinkUrlType(linkUrlType);
			serviceTypeInfo.setIsEnabled("1");
			serviceTypeInfo.setGrayUrl(grayUrl);
			serviceTypeInfo.setGrayAppServiceIcon(grayAppServiceIcon);
			serviceTypeInfo.setGrayWechatServiceIcon(grayWechatServiceIcon);
			serviceTypeInfo.setServiceCategory(serviceCategory);

			if (StringUtils.isNotBlank(id)) {
				serviceTypeInfo.setModifier(request.getRemoteUser());
				serviceTypeInfo.setModifyTime(new Date());
				serviceTypeInfo.setId(Integer.parseInt(id));
				// 修改的时候,服务编码不变
				ServiceTypeInfo serviceInfo = serviceTypeInfoManager.get(Integer.parseInt(id));
				serviceTypeInfo.setCode(serviceInfo.getCode());
			} else {
				serviceTypeInfo.setCreateTime(new Date());
				serviceTypeInfo.setCreator(request.getRemoteUser());
//				serviceTypeInfo.setCode(code);
				serviceTypeInfo.setIsEnabled("1");

				// 新增的时候自动生成服务code,格式为:FW-xxxx
				int    code = serviceTypeInfoManager.maxId() + 1;
				String str  = UUIDUitl.toFixdLengthString(code, 4);
				serviceTypeInfo.setCode("FW-" + str);

				if (StringUtils.isNotBlank(serviceIcon)) {
					serviceTypeInfo.setServiceIcon(FileUploadUtils.getBase64ImageUrl(serviceIcon));
				}
				if (StringUtils.isNotBlank(grayAppServiceIcon)) {
					serviceTypeInfo.setGrayAppServiceIcon(FileUploadUtils.getBase64ImageUrl(grayAppServiceIcon));
				}
				if (StringUtils.isNotBlank(grayWechatServiceIcon)) {
					serviceTypeInfo.setGrayWechatServiceIcon(FileUploadUtils.getBase64ImageUrl(grayWechatServiceIcon));
				}
			}
			return JSONObject.fromObject(serviceTypeInfoManager.saveUpdateServiceTypeInfo(serviceTypeInfo, actype, organizationId, roleGroup)).toString();
		} catch (Exception e) {
			log.error("controller saveUpdate saveUpdateServiceTypeInfo error{}", e);
			map.put("flag", false);
			map.put("desc", "提交失败，请检测网络！");

		}
		return JSONObject.fromObject(map).toString();
	}

	/**
	 * 查询编辑的服务内容
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getServiceTypeInfo", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")
	public @ResponseBody
	ServiceTypeInfo getServiceTypeInfo(HttpServletRequest request,
									   HttpServletResponse response) throws Exception {
		try {
			String id = request.getParameter("id");
			if (StringUtils.isNotBlank(id)) {
				return serviceTypeInfoManager.get(Integer.parseInt(id));
			}
		} catch (Exception e) {
			log.error("controller get getServiceTypeInfo error{}", e);
		}
		return null;
	}

	/**
	 * 删除服务内容信息
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/deleteServiceInfo", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")
	public @ResponseBody
	String deleteServiceInfo(HttpServletRequest request,
							 HttpServletResponse response) throws Exception {
		JSONObject jsonObject = new JSONObject();
		try {
			String id = request.getParameter("id");
			if (StringUtils.isNotBlank(id)) {
				ServiceTypeInfo serviceTypeInfo = serviceTypeInfoManager.get(Integer.parseInt(id));
				serviceTypeInfo.setIsEnabled("0");
				serviceTypeInfo.setModifier(request.getRemoteUser());
				serviceTypeInfo.setModifyTime(new Date());
				serviceTypeInfoManager.updateModel(serviceTypeInfo);
				jsonObject.put("flag", true);
				jsonObject.put("desc", serviceTypeInfo.getServiceName() + "删除成功！");
			}
		} catch (Exception e) {
			log.error("controller delete deleteServiceInfo error{}", e);
			jsonObject.put("flag", false);
			jsonObject.put("desc", "删除失败，请检测网络！");
		}
		return jsonObject.toString();
	}

	/**
	 * 服务管理
	 * 批量上架，下架
	 */
	@RequestMapping(value = "/serviceTypeManage")
	public ModelAndView serviceTypeManage(HttpServletRequest request,
										  HttpServletResponse response) throws Exception {
		Model  model   = new ExtendedModelMap();
		String actType = request.getParameter("actType");
		String status  = request.getParameter("status");
		if ("1".equals(status)) {
			model.addAttribute("title", "服务批量上架管理");
		} else {
			model.addAttribute("title", "服务批量下架管理");
		}
		model.addAttribute("status", status);

		String          serviceTypeId = request.getParameter("serviceTypeId");
		ServiceTypeInfo typeInfo      = serviceTypeInfoManager.get(Integer.parseInt(serviceTypeId));
		model.addAttribute("model", typeInfo);

		if ("save".equals(actType)) {
			String orderNo         = request.getParameter("orderNo");
			String organizationIds = request.getParameter("organizationIds");
			String roleGroups      = request.getParameter("roleGroups");
			String operateUserName = request.getRemoteUser();
			serviceProjectAllocationManager.assignBatchOnOffService(status, serviceTypeId, orderNo, organizationIds, operateUserName, roleGroups);

			model.addAttribute("errormsg", "处理成功.");
		}
		model.addAttribute("funcid", request.getParameter("funcid"));
		model.addAttribute("roleGroupType", this.getElementGroupManager().getElementsByGroupName("roleGroupType"));
		return new ModelAndView("admin/service/serviceTypeManage", model.asMap());
	}


	/**
	 * 针对于项目 批量上线 和下线服务
	 */
	@RequestMapping(value = "/serviceProjectTypeManage")
	public ModelAndView serviceProjectTypeManage(HttpServletRequest request,
												 HttpServletResponse response) throws Exception {
		Model model = new ExtendedModelMap();
		initFunctionOperate(request);
		String organizationId = request.getParameter("organizationId");
		model.addAttribute("tbOrganization", propertyManager.getTbOrganizationById(Integer.parseInt(organizationId)));
		return new ModelAndView("admin/service/serviceProjectAllocationManage", model.asMap());
	}

	/**
	 * 服务模板批量上架项目
	 */
	@RequestMapping(value = "/saveUpdateServiceProjectTypeManage")
	public ModelAndView saveUpdateServiceProjectTypeManage(HttpServletRequest request,
														   HttpServletResponse response) throws Exception {
		Model  model           = new ExtendedModelMap();
		String organizationId  = request.getParameter("organizationId");
		String organizationIds = request.getParameter("organizationIds");
		model.addAttribute("tbOrganization", propertyManager.getTbOrganizationById(Integer.parseInt(organizationId)));
		model.addAttribute("funcid", request.getParameter("funcid"));
		Map<String, Object> resultMap = serviceTypeInfoManager.saveUpdateServiceProjectTypeInfoManager(organizationId, organizationIds, request.getRemoteUser());
		model.addAttribute("errormsg", resultMap.get("desc").toString());
		return new ModelAndView("admin/service/serviceProjectAllocationManage", model.asMap());
	}

	/**
	 * 项目组织树
	 * --项目服务包
	 */
	@RequestMapping(value = "/projectOrganizationTree", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	List<OutTreeDTO> projectOrganizationTree(HttpServletRequest request,
											 HttpServletResponse response) {
		List<OutTreeDTO> trees          = new ArrayList<OutTreeDTO>();
		String           organizationId = request.getParameter("organizationId");

		List<TbOrganization> organizationList = getUserRelationOrgList(request);
		for (TbOrganization organization : organizationList) {
			if (!organization.getId().toString().equals(organizationId)) {
				OutTreeDTO obj = new OutTreeDTO();
				obj.setId(organization.getId().toString());        //当前节点ID
				obj.setName(organization.getName());    //节点名称
				obj.setpId("0");   //父节点code
				obj.setLevel("1");
				trees.add(obj);
			}
		}

		//根节点
		OutTreeDTO obj1 = new OutTreeDTO();
		obj1.setId("0");
		obj1.setName("所有项目");
		obj1.setpId("-1");
		trees.add(obj1);
		return trees;
	}

	/**
	 * 项目组织树
	 * --项目服务包
	 */
	@RequestMapping(value = "/organizationTree", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	List<OutTreeDTO> organizationTree(HttpServletRequest request,
									  HttpServletResponse response) {
		List<OutTreeDTO> trees = new ArrayList<OutTreeDTO>();

		String serviceTypeId = request.getParameter("serviceTypeId");
		String status        = request.getParameter("status");

		List<TbOrganization>           organizationList          = getUserRelationOrgList(request);
		List<ServiceProjectAllocation> serviceProjectAllocations = new ArrayList<ServiceProjectAllocation>();
		if (StringUtils.isNotEmpty(serviceTypeId)) {
			serviceProjectAllocations = serviceProjectAllocationManager.getServiceProjectAllocationList(serviceTypeId);
		}
		for (TbOrganization organization : organizationList) {
			OutTreeDTO obj = new OutTreeDTO();
			obj.setId(organization.getId().toString());        //当前节点ID
			obj.setName(organization.getName());    //节点名称
			obj.setpId("0");   //父节点code
			obj.setLevel("1");
			for (ServiceProjectAllocation serviceProjectAllocation : serviceProjectAllocations) {
				if (serviceProjectAllocation.getProjectId().intValue() == organization.getId().intValue()) {
					if (status.equals(serviceProjectAllocation.getStatus())) {
						obj.setChecked(true);
					}
				}
			}
			trees.add(obj);
		}

		//根节点
		OutTreeDTO obj1 = new OutTreeDTO();
		obj1.setId("0");
		obj1.setName("所有项目");
		obj1.setpId("-1");
		trees.add(obj1);
		return trees;
	}
}
