package com.palmnest.webapp.controller.backstage;

import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.Constants;
import com.palmnest.application.ElementConstant;
import com.palmnest.application.bean.Page;
import com.palmnest.application.bean.Pagenation;
import com.palmnest.application.core.util.*;
import com.palmnest.model.User;
import com.palmnest.model.estateserve.ProductCategories;
import com.palmnest.model.estateserve.ServiceTypeInfo;
import com.palmnest.service.estateserve.AppUserManager;
import com.palmnest.service.estateserve.ServicePackManager;
import com.palmnest.service.estateserve.ServiceTypeInfoManager;
import com.palmnest.webapp.controller.BaseFormController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.ParseException;
import org.json.JSONException;
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.ui.ModelMap;
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.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * 服务项控制类
 *
 * @author xiemin
 * @created
 */
@Slf4j
@Controller
@RequestMapping("/admin/servicePack*")
public class ServicePackController extends BaseFormController {

	@Autowired
	private ServicePackManager     servicePackManager;
	@Autowired
	private AppUserManager         appUserManager;
	@Autowired
	private ServiceTypeInfoManager serviceTypeInfoManager;

	/**
	 * 查询服务项列表
	 *
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value = "/list")
	public String list(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {

		String name          = request.getParameter("name");
		String isDeposit     = request.getParameter("isDeposit");
		String paymentMethod = request.getParameter("paymentMethod");
		String type          = request.getParameter("type");
		String startTime     = request.getParameter("startTime");
		String endTime       = request.getParameter("endTime");
		String pageNo        = request.getParameter("pageNo");

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

		User user = getUserManager().getUserByUsername(request.getRemoteUser());

		modelMap.put("adminName", user.getUsername());
		modelMap.put("name", name);
		modelMap.put("isDeposit", isDeposit);
		modelMap.put("startTime", startTime);
		modelMap.put("endTime", endTime);
		modelMap.put("paymentMethod", paymentMethod);
		modelMap.put("pageNo", pageNo);
		modelMap.put("type", type);

		Pagenation<Map<String, String>> page = servicePackManager.queryServicePackList(modelMap);

//		modelMap.remove("pageNo");
		modelMap.put("page", page);
		modelMap.put("visitPrefix", FileUploadUtils.getVisitPrefix());

		return "admin/servicePack/servicePackList";
	}

	/**
	 * 查询服务项列表
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/queryServiceList")
	public String queryServiceList(HttpServletRequest request, HttpServletResponse response) {

		JSONObject json = new JSONObject();

		List<Map<String, String>> list = servicePackManager.queryServiceList();

		json.put("list", list);

		StringUtil.charSet(json, request, response);

		return null;
	}

	/**
	 * 跳转服务项新增页面
	 *
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value = "toAddServicePack")
	public String toAddServicePack(HttpServletRequest request, HttpServletResponse response, HttpSession session) {

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

		try {
			request.setAttribute("uuid", UUID.randomUUID());
			request.setAttribute("sessionId", session.getId());
			request.setAttribute("id", id);

			FileUploadUtils fileUploadUtils = new FileUploadUtils();

			fileUploadUtils.init();

			request.setAttribute("visitPrefix", fileUploadUtils.fullVisitPath(""));
		} catch (Exception e) {
			e.printStackTrace();
			log.error(LogExceptionStackUtil.LogExceptionStack(e));
		}

		return "admin/servicePack/addServicePack";
	}

	/**
	 * 删除服务项
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "deleteServicePack")
	public String deleteServicePack(HttpServletRequest request, HttpServletResponse response) {

		JSONObject json = new JSONObject();

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

		try {
			//删除
			json = servicePackManager.deleteServicePack(id, ElementConstant.YESORNO_0);

			StringUtil.charSet(json, request, response);

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

		json.put("code", -1);
		json.put("msg", "系统异常，操作失败");

		StringUtil.charSet(json, request, response);

		return null;
	}

	/**
	 * 删除图片
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "deletePicture")
	public String deletePicture(HttpServletRequest request, HttpServletResponse response) {

		JSONObject json = new JSONObject();

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

		try {
			//删除
			json = servicePackManager.deletePicture(id);
			StringUtil.charSet(json, request, response);
			return null;
		} catch (Exception e) {
			e.printStackTrace();
		}

		json.put("code", -1);
		json.put("msg", "系统异常，操作失败");

		StringUtil.charSet(json, request, response);

		return null;
	}

	/**
	 * 查询商品分类类型列表--初始
	 *
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value = "/productCategoriesList")
	public ModelAndView productCategoriesList(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws Exception {

		Model        model    = new ExtendedModelMap();
		StringBuffer whereSql = new StringBuffer();

		String pageNo    = request.getParameter("pageNo");
		String paramName = request.getParameter("paramName");
		String serviceId = request.getParameter("serviceId");

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

		whereSql.append(" where t1.parentCode='0' and t1.isEnabled='1'");

		if (StringUtils.isNotEmpty(paramName)) {
			model.addAttribute("paramName", paramName);
			whereSql.append(" and (t1.name like '%" + paramName + "%' or t1.serviceCode like '%" + paramName + "%')");
		}

		if (StringUtils.isNotEmpty(serviceId)) {
			model.addAttribute("serviceId", serviceId);
			whereSql.append(" and t1.serviceId=" + serviceId);
		}

		whereSql.append(" order by t1.createTime desc");

		Page page = servicePackManager.getProductCategoriesPage(whereSql.toString(), 10, Integer.parseInt(pageNo));

		model.addAttribute("page", page);
		model.addAttribute("visitPrefix", FileUploadUtils.getVisitPrefix());
		model.addAttribute("serviceGroupType", this.getElementGroupManager().getElementsByGroupName("signingServiceGroup"));

		return new ModelAndView("admin/categories/productCategoriesList", model.asMap());
	}

	/**
	 * 查询商品分类类型列表
	 *
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value = "/productCategoriesListInfo")
	public String productCategoriesListInfo(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {

		String name      = request.getParameter("name");
		String serviceId = request.getParameter("serviceId");
		String startTime = request.getParameter("startTime");
		String endTime   = request.getParameter("endTime");
		String typeCode  = request.getParameter("typeCode");
		String pageNo    = request.getParameter("pageNo");

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

		modelMap.put("name", name);
		modelMap.put("serviceId", serviceId);
		modelMap.put("startTime", startTime);
		modelMap.put("endTime", endTime);
		modelMap.put("pageNo", pageNo);
		modelMap.put("typeCode", typeCode);

		Pages<Map<String, String>> page = servicePackManager.queryProductCategoriesList(modelMap);

		modelMap.put("page", page);
		modelMap.put("visitPrefix", FileUploadUtils.getVisitPrefix());

		return "admin/servicePack/productCategoriesListInfo";
	}

	/**
	 * 查询服务项商品列表--初始
	 *
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value = "/listDetails")
	public String listDetails(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		String name      = request.getParameter("name");
		String typeId    = request.getParameter("typeId");
		String typeCode  = request.getParameter("typeCode");
		String startTime = request.getParameter("startTime");
		String endTime   = request.getParameter("endTime");
		String pageNo    = request.getParameter("pageNo");
		if (StringUtils.isEmpty(pageNo)) {
			pageNo = "1";
		}
		modelMap.put("name", name);
		modelMap.put("typeId", typeId);
		modelMap.put("typeCode", typeCode);
		modelMap.put("startTime", startTime);
		modelMap.put("endTime", endTime);
		modelMap.put("pageNo", pageNo);
		return "admin/servicePack/servicePackDetailsList";
	}

	/**
	 * 查询服务项商品列表
	 *
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value = "/listDetailsInfo")
	public String listDetailsInfo(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {

		String name                = request.getParameter("name");
		String servicePackId       = request.getParameter("servicePackId");
		String serviceCategoriesId = request.getParameter("serviceCategoriesId");
		String startTime           = request.getParameter("startTime");
		String endTime             = request.getParameter("endTime");
		String pageNo              = request.getParameter("pageNo");

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

		modelMap.put("name", name);
		modelMap.put("servicePackId", servicePackId);
		modelMap.put("serviceCategoriesId", serviceCategoriesId);
		modelMap.put("startTime", startTime);
		modelMap.put("endTime", endTime);
		modelMap.put("pageNo", pageNo);

		Pages<Map<String, String>> page = servicePackManager.queryServicePackDetailsList(modelMap);

		modelMap.put("page", page);
		modelMap.put("visitPrefix", FileUploadUtils.getVisitPrefix());

		return "admin/servicePack/servicePackDetailsListInfo";
	}

	/**
	 * 跳转服务项商品新增页面
	 *
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value = "toAddServicePackDetails")
	public String toAddServicePackDetails(HttpServletRequest request, HttpServletResponse response, HttpSession session) {

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

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

		try {
			if (StringUtils.isNotEmpty(id)) {
				map = servicePackManager.queryServicePackDetails(id);
			}
			request.setAttribute("sessionId", session.getId());
			request.setAttribute("map", map);
			FileUploadUtils fileUploadUtils = new FileUploadUtils();
			fileUploadUtils.init();
			request.setAttribute("visitPrefix", fileUploadUtils.fullVisitPath(""));
		} catch (Exception e) {
			log.error(LogExceptionStackUtil.LogExceptionStack(e));
		}

		return "admin/servicePack/addServicePackDetails";
	}

	@RequestMapping(value = "addServicePackDetails")
	public String addServicePackDetails(HttpServletRequest request, HttpServletResponse response) {

		JSONObject json = new JSONObject();

		String id       = request.getParameter("id");
		String name     = request.getParameter("name");
		String logoPath = request.getParameter("logoPath");
		String typeId   = request.getParameter("typeId");
		String price    = request.getParameter("price");
		String typeCode = request.getParameter("typeCode");

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

		map.put("id", id);
		map.put("name", name);
		map.put("logoPath", logoPath);
		map.put("typeId", typeId);
		map.put("typeCode", typeCode);
		map.put("price", price);

		try {
			User user = getUserManager().getUserByUsername(request.getRemoteUser());

			map.put("adminName", user.getUsername());

			//添加
			json = servicePackManager.addServicePackDetails(map);
			StringUtil.charSet(json, request, response);

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

		json.put("code", -1);
		json.put("msg", "系统异常，操作失败");

		StringUtil.charSet(json, request, response);
		return null;
	}

	/**
	 * 删除服务商品
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "deleteServicePackDetails")
	public String deleteServicePackDetails(HttpServletRequest request, HttpServletResponse response) {

		JSONObject json = new JSONObject();

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

		try {

			// 删除
			json = servicePackManager.deleteServicePack(id, ElementConstant.YESORNO_0);
			StringUtil.charSet(json, request, response);
			return null;
		} catch (Exception e) {
			e.printStackTrace();
		}

		json.put("code", -1);
		json.put("msg", "系统异常，操作失败");
		StringUtil.charSet(json, request, response);
		return null;
	}

	/**
	 * 跳转商品分类新增页面
	 *
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value = "toAddProductCategories")
	public String toAddProductCategories(HttpServletRequest request, HttpServletResponse response, HttpSession session) {

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

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

		try {

			if (StringUtils.isNotEmpty(id)) {
				map = servicePackManager.queryProductCategories(id);
			}
			request.setAttribute("map", map);
		} catch (Exception e) {
			log.error(LogExceptionStackUtil.LogExceptionStack(e));
		}

		return "admin/servicePack/addProductCategories";
	}

	/**
	 * 新增服务项商品分类
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "addProductCategories")
	public String addProductCategories(HttpServletRequest request, HttpServletResponse response) {
		JSONObject json = new JSONObject();

		String id        = request.getParameter("id");
		String name      = request.getParameter("name");
		String serviceId = request.getParameter("serviceId");
		String typeCode  = request.getParameter("typeCode");

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

		map.put("id", id);
		map.put("name", name);
		map.put("serviceId", serviceId);
//    	String code = (int) (Math.random() * 9000 + 1000) + "";
		map.put("typeCode", typeCode);

		try {

			User user = getUserManager().getUserByUsername(request.getRemoteUser());

			map.put("adminName", user.getUsername());

			//添加
			json = servicePackManager.addProductCategories(map);
			StringUtil.charSet(json, request, response);
			return null;

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

		json.put("code", -1);
		json.put("msg", "系统异常，操作失败");

		StringUtil.charSet(json, request, response);
		return null;
	}

	/**
	 * 根据服务项id查询商品分类列表
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "queryCategoriesList")
	public String queryCategoriesList(HttpServletRequest request, HttpServletResponse response) {

		JSONObject json = new JSONObject();

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

		List<Map<String, String>> list = servicePackManager.queryCategoriesList(serviceId);

		json.put("list", list);

		StringUtil.charSet(json, request, response);

		return null;
	}

	/**
	 * 删除服务分类
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "deleteProductCategories")
	public String deleteProductCategories(HttpServletRequest request, HttpServletResponse response) {
		JSONObject json = new JSONObject();

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

		try {
			//删除
			json = servicePackManager.deleteProductCategories(id, ElementConstant.YESORNO_0);
			StringUtil.charSet(json, request, response);
			return null;

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

		json.put("code", -1);
		json.put("msg", "系统异常，操作失败");

		StringUtil.charSet(json, request, response);
		return null;
	}

	/**
	 * 多图片上传
	 *
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings("static-access")
	@RequestMapping(value = "/uploadImgageList")
	public String uploadImgageList(HttpServletRequest request, HttpServletResponse response) throws IOException {

		JSONObject json = new JSONObject();

		try {
        	
        	/*
        	String servicePackId = request.getParameter("servicePackId");
            if(StringUtils.isNotEmpty(servicePackId)){
            	ServicePack sp = servicePackManager.findDetils(Integer.valueOf(servicePackId));
            	if(null != sp && null != sp.getServiceImg() && !sp.getServiceImg().equals("")){
            		json.put("code", "-1");
                    json.put("msg", "请先删除图片再上传！");
                    StringUtil.charSet(json,request,response);
                    return null;
            	}
            }
            */

			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			Iterator<String>            fileNames        = multipartRequest.getFileNames();
			MultipartFile               multipartFile    = multipartRequest.getFile(fileNames.next());

			//获得文件原始名称
			InputStream stream   = null;
			String      fileExt  = null;
			String      fileName = "";

			if (multipartFile != null) {
				stream = multipartFile.getInputStream();
				fileName = multipartFile.getOriginalFilename();
				fileName = new String(fileName.getBytes(), "utf-8");
				fileExt = StringUtils.isNotEmpty(fileName) ? fileName
						.substring(fileName.lastIndexOf("."))
						: StringUtils.EMPTY;
			}

			FileUploadUtils fileUploadUtils = new FileUploadUtils();
			fileUploadUtils.init();
			String url = fileUploadUtils.uploadFile(stream, fileExt);

			json.put("url", url);
			json.put("filePath", fileUploadUtils.fullVisitPath(url));

			json.put("code", "0");
			json.put("msg", "上传成功");
			StringUtil.charSet(json, request, response);
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", "-1");
			json.put("msg", "上传失败");
			StringUtil.charSet(json, request, response);
		}
		return null;
	}

	/**
	 * 根据服务项id查询服务详情
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "queryServiceTypeInfo")
	public String queryServiceTypeInfo(HttpServletRequest request, HttpServletResponse response) {
		JSONObject      json      = new JSONObject();
		String          serviceId = request.getParameter("serviceId");
		ServiceTypeInfo stf       = serviceTypeInfoManager.get(Integer.valueOf(serviceId));
		json.put("stf", stf);
		StringUtil.charSet(json, request, response);
		return null;
	}

	/**
	 * 根据父级分类查询子级列表
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "getProductCategoriesNodes")
	public @ResponseBody
	List<Map<String, Object>> getProductCategoriesNodes(HttpServletRequest request) throws Exception {
		try {
			// 父级节点Code
			String parentCode = request.getParameter("parentCode");

			List<Map<String, Object>> listMap = servicePackManager.getProductCategoriesNodes(parentCode);

			return listMap;
		} catch (Exception e) {

			log.error("getProductCategoriesNodes error {}" + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return null;
	}

	/**
	 * 新增或修改父级子级分类
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/saveUpdateProductCategories", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")
	public @ResponseBody
	String saveUpdateProductCategoriesParent(HttpServletRequest request) throws Exception {

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

		try {
			String id          = request.getParameter("id");
			String serviceId   = request.getParameter("serviceId");
			String name        = request.getParameter("name");
			String serviceCode = request.getParameter("serviceCode");
			String description = request.getParameter("description");
			String iconUrl     = request.getParameter("iconUrl");
			String parentCode  = request.getParameter("parentCode");

			ProductCategories productCategories = new ProductCategories();

			if (StringUtils.isNotBlank(id)) {

				productCategories.setId(Integer.parseInt(id));
				productCategories = servicePackManager.querProductCategoriesById(productCategories.getId());
				productCategories.setName(name);
				productCategories.setServiceCode(serviceCode);
				productCategories.setDescription(description);
				productCategories.setIconUrl(iconUrl);
				productCategories.setModifyTime(DateUtils.formatDate(new Date()));
				productCategories.setModifier(request.getRemoteUser());

			} else {

				productCategories.setCreateTime(DateUtils.formatDate(new Date()));
				productCategories.setCreator(request.getRemoteUser());
				productCategories.setName(name);
				productCategories.setServiceCode(serviceCode);
				productCategories.setDescription(description);
				productCategories.setIconUrl(iconUrl);
				productCategories.setIsEnabled("1");

			}
			if (StringUtils.isNotBlank(serviceId)) {
				productCategories.setServiceId(Integer.parseInt(serviceId));
			} else {
				productCategories.setServiceId(null);
			}

			if ("0".equals(parentCode)) {
				productCategories.setParentCode("0");
			} else {
				String orderNo = request.getParameter("orderNo");
				productCategories.setParentCode(parentCode);
				productCategories.setOrderNo(orderNo);
			}

			resultMap = servicePackManager.saveUpdateProductCategories(productCategories);
		} catch (Exception e) {
			resultMap.put("flag", false);
			resultMap.put("desc", "系统异常！");
			log.error("saveUpdateProductCategories error{}" + LogExceptionStackUtil.LogExceptionStack(e));
		}

		return net.sf.json.JSONObject.fromObject(resultMap).toString();
	}

	@RequestMapping(value = "/uploadImage", method = {RequestMethod.GET, RequestMethod.POST})
	public @ResponseBody
	String uploadImage(HttpServletRequest request) throws IOException, ParseException, JSONException {

		String imageUrl     = request.getParameter("imageUrl");
		String relativePath = "";

		try {
			relativePath = FileUploadUtils.getBase64ImageUrl(imageUrl);
			return relativePath;

		} catch (Exception e) {
			FileUploadUtils.deleteFileByPath(Constants.IMAGE_ROOT + relativePath);
			log.error("检测图片接口错误:" + e.getMessage());
		}
		return "";
	}

	/**
	 * 删除父级子级分类
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/delProductCategories", method = {RequestMethod.GET, RequestMethod.POST})
	public @ResponseBody
	String delProductCategories(HttpServletRequest request) throws Exception {
		String id = request.getParameter("id");
		try {
			ProductCategories productCategories = servicePackManager.querProductCategoriesById(Integer.parseInt(id));
			productCategories.setModifyTime(DateUtils.formatDate(new Date()));
			productCategories.setModifier(request.getRemoteUser());
			return servicePackManager.delProductCategories(productCategories);
		} catch (Exception e) {
			log.error("delProductCategories error{}" + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return "error";
	}
}
