package com.palmnest.webapp.controller.backstage;

import com.alibaba.fastjson.JSON;
import com.palmnest.application.AppConstants;
import com.palmnest.application.CodeConstants;
import com.palmnest.application.Constants;
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.DateHelper;
import com.palmnest.application.core.util.FileUploadUtils;
import com.palmnest.application.dto.WebPageResultDto;
import com.palmnest.application.dto.output.ServiceProjectAllocationOutDto;
import com.palmnest.model.estateserve.ServiceProjectAllocation;
import com.palmnest.model.estateserve.ServiceTypeInfo;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.model.property.TbOrganizationConfig;
import com.palmnest.service.OrganizationManager;
import com.palmnest.service.estateserve.ServiceProjectAllocationManager;
import com.palmnest.service.estateserve.ServiceTypeInfoManager;
import com.palmnest.service.org.OrganizationService;
import com.palmnest.service.redis.BaseRedisService;
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.util.CollectionUtils;
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.Calendar;
import java.util.Date;
import java.util.List;

@Slf4j
@Controller
@RequestMapping("/service/allocation/*")
public class ServiceProjectAllocationController extends BaseFormController {


	@Autowired
	private ServiceProjectAllocationManager serviceProjectAllocationManager;
	@Autowired
	private OrganizationService             organizationService;
	@Autowired
	private ServiceTypeInfoManager          serviceTypeInfoManager;
	@Autowired
	private BaseRedisService                baseRedisService;
	@Autowired
	private OrganizationManager             organizationManager;

	public void initModel(Model model) {
		model.addAttribute("serviceStatusGropType", this.getElementGroupManager().getElementsByGroupName("serviceStatusGropType"));
		model.addAttribute("roleGroupType", this.getElementGroupManager().getElementsByGroupName("roleGroupType"));
		model.addAttribute("jumpGroupType", this.getElementGroupManager().getElementsByGroupName("JumpGroupType"));
		model.addAttribute("serviceGroupType", this.getElementGroupManager().getElementsByGroupName("serviceGroupType"));
		model.addAttribute("registerStatusGroupType", this.getElementGroupManager().getElementsByGroupName("registerStatusGroupType"));
		model.addAttribute("isSignContractGroupType", this.getElementGroupManager().getElementsByGroupName("isSignContractGroupType"));
		model.addAttribute("visitPrefix", FileUploadUtils.getVisitPrefix());
		model.addAttribute("serviceCategory", this.getElementGroupManager().getElementsByGroupName("serviceCategory"));
		model.addAttribute("discoverCategory", this.getElementGroupManager().getElementsByGroupName("discoverCategory"));
		model.addAttribute("serviceIndate", this.getElementGroupManager().getElementsByGroupName("serviceIndate"));
		String serviceCategoryJson       = JSON.toJSONString(this.getElementGroupManager().getElementsByGroupName("serviceCategory"));
		String serviceStatusGropTypeJson = JSON.toJSONString(this.getElementGroupManager().getElementsByGroupName("serviceStatusGropType"));
		model.addAttribute("serviceCategoryJson", serviceCategoryJson);
		model.addAttribute("serviceStatusGropTypeJson", serviceStatusGropTypeJson);
	}

	/**
	 * 获取项目主页配置列表
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getServiceProject")
	@ResponseBody
	public WebPageResultDto getServiceProject(HttpServletRequest request) {
		try {
			initFunctionOperate(request); //初始化功能操作权限
			String pageNo = request.getParameter("pageNo");
			if (StringUtils.isEmpty(pageNo)) {
				pageNo = "1";
			}
			String               orgIds           = "";
			List<TbOrganization> organizationList = getUserRelationOrgList(request);
			if (!CollectionUtils.isEmpty(organizationList)) {
				orgIds = organizationList.get(0).getId() + "";
			}
			String organizationId = request.getParameter("organizationId");
			if (StringUtils.isNotBlank(organizationId)) {
				orgIds = organizationId;
			}
			String serviceType = request.getParameter("serviceType");
			String whereSql    = " where t3.isEnabled=" + Constants.RESULT_SUCC + " and (t3.projectId is NULL or t3.projectId IN(" + orgIds + "))";
			String paramValue  = request.getParameter("paramValue");
			if (StringUtils.isNotBlank(paramValue)) {
				whereSql += " and t3.serviceName like '%" + paramValue + "%'";
			}
			if (StringUtils.isBlank(serviceType)) {
				serviceType = this.getElementGroupManager().getElementsByGroupName("serviceGroupType").get(0).getItemcode();
			}
			if (StringUtils.isNotBlank(serviceType)) {
				whereSql += " and t3.serviceType =" + serviceType;
			}
			whereSql += " order by t3.serviceallcationStatus desc,t3.orderNo+0 ASC";
			Page             page   = serviceProjectAllocationManager.serviceProjectAllocationPage(Integer.parseInt(pageNo), 10, whereSql, orgIds);
			WebPageResultDto webDto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "", page.getItems());
			webDto.setCount(page.getTotalCount());
			return webDto;
		} catch (Exception e) {
			log.error("controller find ServiceTypeInfoPage error{}", e);
			e.printStackTrace();
		}
		return new WebPageResultDto("100", "获取列表失败", null);
	}

	/**
	 * 项目主页信息列表
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/serviceProjectAllocationPage")
	public ModelAndView serviceProjectAllocationPage(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Model model = new ExtendedModelMap();
		try {
			initFunctionOperate(request); //初始化功能操作权限
			initModel(model);
			String               orgIds           = "";
			List<TbOrganization> organizationList = getUserRelationOrgList(request);
			if (!CollectionUtils.isEmpty(organizationList)) {
				model.addAttribute("organizationId", organizationList.get(0).getId());
				orgIds = organizationList.get(0).getId() + "";
			}
			String organizationId = request.getParameter("organizationId");
			if (StringUtils.isNotBlank(organizationId)) {
				orgIds = organizationId;
				model.addAttribute("organizationId", organizationId);
			}
			String serviceType = request.getParameter("serviceType");
			String paramValue  = request.getParameter("paramValue");
			if (StringUtils.isNotBlank(paramValue)) {
				model.addAttribute("paramValue", paramValue);
			}
			if (StringUtils.isBlank(serviceType)) {
				serviceType = this.getElementGroupManager().getElementsByGroupName("serviceGroupType").get(0).getItemcode();
			}
			if (StringUtils.isNotBlank(serviceType)) {
				model.addAttribute("serviceType", serviceType);
			}
			model.addAttribute("organizationList", organizationList);
			model.addAttribute("serviceStatus", "1");
			return new ModelAndView("/admin/service/serviceProjectAllocationList", model.asMap());
		} catch (Exception e) {
			log.error("controller find ServiceTypeInfoPage error{}", e);
		}
		return null;
	}

	/**
	 * 查询项目服务配置信息
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/findServiceProjectAllocation", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")
	public @ResponseBody
	ServiceProjectAllocationOutDto findServiceProjectAllocation(HttpServletRequest request,
																HttpServletResponse response) throws Exception {
		try {
			String id = request.getParameter("id");
			if (StringUtils.isNotBlank(id)) {
				ServiceProjectAllocation serviceProjectAllocation = serviceProjectAllocationManager.get(Integer.parseInt(id));

				ServiceProjectAllocationOutDto dto = new ServiceProjectAllocationOutDto();
				dto.setId(serviceProjectAllocation.getId());
				dto.setCreator(serviceProjectAllocation.getCreator());
				dto.setIsEnabled(serviceProjectAllocation.getIsEnabled());
				dto.setModifier(serviceProjectAllocation.getModifier());
				dto.setOrderNo(serviceProjectAllocation.getOrderNo());
				dto.setProjectId(serviceProjectAllocation.getProjectId());
				dto.setRoleGroup(serviceProjectAllocation.getRoleGroup());
				dto.setPermission(serviceProjectAllocation.getPermission());
				//如果自定义图标未设置,则返回服务默认图标
				if (StringUtils.isNotBlank(serviceProjectAllocation.getServiceIcon())) {
					dto.setServiceIcon(serviceProjectAllocation.getServiceIcon());
				} else {
					ServiceTypeInfo serviceTypeInfo = serviceTypeInfoManager.get(serviceProjectAllocation.getServiceTypeId());
					dto.setServiceIcon(serviceTypeInfo.getServiceIcon());
				}

				dto.setServiceTypeId(serviceProjectAllocation.getServiceTypeId());
				dto.setStatus(serviceProjectAllocation.getStatus());
				dto.setType(serviceProjectAllocation.getType());
				if (null != serviceProjectAllocation.getCreateTime()) {
					dto.setCreateTime(DateHelper.formatDate(serviceProjectAllocation.getCreateTime(), DateHelper.DATE_STRING));
				}
				if (null != serviceProjectAllocation.getIndate()) {
					dto.setIndate(DateHelper.formatDate(serviceProjectAllocation.getIndate(), DateHelper.CURRENT_DATE));
				}
				if (null != serviceProjectAllocation.getModifyTime()) {
					dto.setModifyTime(DateHelper.formatDate(serviceProjectAllocation.getModifyTime(), DateHelper.DATE_STRING));
				}
				if (null != serviceProjectAllocation.getProjectId()) {
					TbOrganization organization = organizationManager.getOrganizationById(serviceProjectAllocation.getProjectId());
					dto.setOrgName(organization.getName());
				}

				return dto;
			}
		} catch (Exception e) {
			log.error("controller find findServiceProjectAllocation error{}", e);
		}
		return null;
	}

	/**
	 * 项目服务配置新增和修改
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/saveUpdateServiceProject", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")
	public @ResponseBody
	String saveUpdateServiceProject(HttpServletRequest request,
									HttpServletResponse response) throws Exception {
		JSONObject jsonObject = new JSONObject();

		try {
			String id        = request.getParameter("id");
			String serviceId = request.getParameter("serviceId");
			String status    = request.getParameter("status");//0-下线 1-上线 2-灰度
			String orderNo   = request.getParameter("orderNo");
//			String roleGroup=request.getParameter("roleGroup");
			String organizationId = request.getParameter("organizationId");

			String serviceIndate = request.getParameter("serviceIndate");
			String serviceIcon   = request.getParameter("serviceIcon");
			String permission    = request.getParameter("permission"); // 是否开启了权限设置(1-是 0-否)

			ServiceProjectAllocation serviceProjectAllocation = null;

			if (StringUtils.isBlank(organizationId)) {
				jsonObject.put("flag", false);
				jsonObject.put("desc", "请选择项目");
				return jsonObject.toString();
			}

			if (StringUtils.isBlank(permission) || !permission.equals("1")) {
				permission = "0";
			}

			if (StringUtils.isNotBlank(id)) {
				serviceProjectAllocation = serviceProjectAllocationManager.get(Integer.parseInt(id));
				serviceProjectAllocation.setModifier(request.getRemoteUser());
				serviceProjectAllocation.setModifyTime(new Date());
//				serviceProjectAllocation.setRoleGroup(roleGroup);
				//上线 灰度 服务
				if (status.equals("1") || "2".equals(status)) {
					organizationService.updateOrgServiceRoleFuction(Integer.parseInt(organizationId), Integer.parseInt(serviceId), 1);
				} else if (status.equals("0")) {
					//下线
					organizationService.updateOrgServiceRoleFuction(Integer.parseInt(organizationId), Integer.parseInt(serviceId), 2);
				}
				serviceProjectAllocation.setStatus(status);
				serviceProjectAllocation.setOrderNo(orderNo);

				if (StringUtils.isNotBlank(serviceIcon) && !serviceIcon.endsWith(".jpeg")) {
					String delUrl = Constants.IMAGE_ROOT + serviceProjectAllocation.getServiceIcon();
					serviceProjectAllocation.setServiceIcon(FileUploadUtils.getBase64ImageUrl(serviceIcon));
					//删除服务器上原有图片
					FileUploadUtils.deleteFileByPath(delUrl);
				}

				if (StringUtils.isNotBlank(serviceIndate)) {
					serviceProjectAllocation.setIndate(fmtDate(serviceIndate));
				} else {
					serviceProjectAllocation.setIndate(null);
				}

				serviceProjectAllocation.setPermission(Integer.parseInt(permission));
				serviceProjectAllocationManager.updateModel(serviceProjectAllocation);
				jsonObject.put("flag", true);
				jsonObject.put("desc", "操作成功！");
			} else {
				serviceProjectAllocation = new ServiceProjectAllocation();
				serviceProjectAllocation.setCreator(request.getRemoteUser());
				serviceProjectAllocation.setCreateTime(new Date());
				serviceProjectAllocation.setIsEnabled("1");
				serviceProjectAllocation.setOrderNo(orderNo);
//				serviceProjectAllocation.setRoleGroup(roleGroup);
				serviceProjectAllocation.setStatus(status);
				serviceProjectAllocation.setType("0");
				serviceProjectAllocation.setServiceTypeId(Integer.parseInt(serviceId));
				serviceProjectAllocation.setProjectId(Integer.parseInt(organizationId));

				if (StringUtils.isNotBlank(serviceIcon)) {
					serviceProjectAllocation.setServiceIcon(FileUploadUtils.getBase64ImageUrl(serviceIcon));
				}

				if (StringUtils.isNotBlank(serviceIndate)) {
					serviceProjectAllocation.setIndate(fmtDate(serviceIndate));
				} else {
					serviceProjectAllocation.setIndate(null);
				}
				serviceProjectAllocation.setPermission(Integer.parseInt(permission));
				serviceProjectAllocationManager.save(serviceProjectAllocation);
				//上线服务
				if (status.equals("1")) {
					organizationService.updateOrgServiceRoleFuction(Integer.parseInt(organizationId), Integer.parseInt(serviceId), 1);
				}
				jsonObject.put("flag", true);
				jsonObject.put("desc", "操作成功！");
			}
			//缓存清掉
			baseRedisService.dele(CodeConstants.ORG_SERVICE_LIST_KEY + organizationId);
			baseRedisService.dele(CodeConstants.ORG_SERVICE_CATEGORY_KEY + organizationId);
		} catch (Exception e) {
			log.error("controller saveUpdate saveUpdateServiceProject error{}", e);
			jsonObject.put("flag", false);
			jsonObject.put("desc", "操作失败！");
		}
		return jsonObject.toString();
	}

	public Date fmtDate(String fmtDate) {
		Date     date = DateHelper.parseToDate(fmtDate, DateHelper.CURRENT_DATE);
		Calendar cal  = Calendar.getInstance();
		cal.setTime(date);//设置起始时间
		//将时间调整为当天23:59:59
		cal.set(Calendar.HOUR_OF_DAY, 23);
		cal.set(Calendar.MINUTE, 59);
		cal.set(Calendar.SECOND, 59);
		return cal.getTime();
	}

	/**
	 * 保存/修改 项目商圈配置
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "saveDiscoverConfig")
	@ResponseBody
	public WebPageResultDto saveDiscoverConfig(HttpServletRequest request) {
		String id               = request.getParameter("id");//项目id
		String orgId            = request.getParameter("orgId");//项目id
		String isEnabled        = request.getParameter("isEnabled");//是否启用
		String discoverCategory = request.getParameter("discoverCategory");//类别名称 0-商圈 1-发现

		TbOrganizationConfig config = new TbOrganizationConfig();
		if (StringUtils.isNotBlank(id)) {
			//修改
			config = organizationService.getObj(id);
		}

		config.setOrgId(Integer.parseInt(orgId));
		config.setDiscoverIsEnabled(isEnabled);
		config.setDiscoverCategory(discoverCategory);
		organizationService.saveOrUpdateTbOrgConfig(config);
//		organizationService.
		return new WebPageResultDto("200", "成功", null);
	}

	/**
	 * 获取项目配置对象
	 *
	 * @return
	 */
	@RequestMapping(value = "getDiscoverConfig")
	@ResponseBody
	public WebPageResultDto getDiscoverConfig(HttpServletRequest request) {
		String               orgId  = request.getParameter("orgId");//项目id
		TbOrganizationConfig config = organizationService.getDiscoverConfigByOrgId(orgId);
		return new WebPageResultDto("200", "成功", config);
	}

	/**
	 * 获取指定时间 n天/月/年 后的日期
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("getIndate")
	@ResponseBody
	public AppResultDto getIndate(HttpServletRequest request) {
		String type      = request.getParameter("type");// DAY日-MONTH月-YEAR年
		String amount    = request.getParameter("amount");// 数量
		String startTime = request.getParameter("startTime");// 起始时间
		if (StringUtils.isBlank(type) || StringUtils.isBlank(amount)) {
			return AppResultUtil.createErrorDto("100", "获取数据失败");
		}

		Date date = new Date();
		if (StringUtils.isNotBlank(startTime)) {
			date = DateHelper.parseToDate(startTime, DateHelper.CURRENT_DATE);
		}

		Calendar cal = Calendar.getInstance();
		cal.setTime(date);//设置起始时间
		//将时间调整为当天23:59:59
		cal.set(Calendar.HOUR_OF_DAY, 23);
		cal.set(Calendar.MINUTE, 59);
		cal.set(Calendar.SECOND, 59);

		if (type.equals("DAY")) {
			cal.add(Calendar.DATE, Integer.parseInt(amount));
		} else if (type.equals("MONTH")) {
			cal.add(Calendar.MONTH, Integer.parseInt(amount));
		} else if (type.equals("YEAR")) {
			cal.add(Calendar.YEAR, Integer.parseInt(amount));
		}

		String fmtDate = DateHelper.formatDate(cal.getTime(), DateHelper.CURRENT_DATE);
		return AppResultUtil.createSuccesDto("200", fmtDate);
	}
}
