package com.palmnest.webapp.controller.backstage;

import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.LogExceptionStackUtil;
import com.palmnest.model.ContractIinformation;
import com.palmnest.model.Element;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.model.property.VirtualArchitecture;
import com.palmnest.service.estateserve.ContractIinformationOrderManager;
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.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 签约信息 控制层
 *
 * @author HJY
 */
@Slf4j
@Controller
@RequestMapping(value = "/admin/contract/*")
public class ContractInformationController extends BaseFormController {


	@Autowired
	private ContractIinformationOrderManager contractIinformationOrderManager;

	@Autowired
	private PropertyManager propertyManager;

	/**
	 * 初始化信息
	 *
	 * @param model
	 */
	public void initModel(Model model) {
		model.addAttribute("contractStatusGroup", this.getElementGroupManager().getElementsByGroupName("contractStatusGroup"));
		model.addAttribute("signingServiceGroup", this.getElementGroupManager().getElementsByGroupName("signingServiceGroup"));
	}


	/**
	 * 查询签约的信息
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "page")
	public ModelAndView page(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Model model = new ExtendedModelMap();
		try {
			initFunctionOperate(request); // 初始化功能操作权限
			String pageNo = request.getParameter("pageNo");
			if (StringUtils.isBlank(pageNo)) {
				pageNo = "1";
			}
			initModel(model);
			String virtualArchitectureId = request.getParameter("virtualArchitectureId");
			if (StringUtils.isNotBlank(virtualArchitectureId)) {
				model.addAttribute("virtualArchitectureId", virtualArchitectureId);
			}
			List<TbOrganization> organizationList = getUserRelationOrgList(request);
			String               orgId            = getUserRelationOrganizationStr(organizationList);
			String               organizationId   = request.getParameter("organizationId");
			if (StringUtils.isNotBlank(organizationId)) {
				model.addAttribute("organizationId", organizationId);
				orgId = organizationId;
			}
			Page page = contractIinformationOrderManager.ContractIinformationOrderPage(10, Integer.parseInt(pageNo),
					orgId, virtualArchitectureId);
			List<Map<String, Object>> list        = page.getItems();
			List<Element>             elementList = this.getElementGroupManager().getElementsByGroupName("signingServiceGroup");
			for (int i = 0; i < list.size(); i++) {
				StringBuffer        str = new StringBuffer();
				Map<String, Object> map = list.get(i);
				if (map.get("type") != null && !"".equals(map.get("type") + "")) {
					String type   = map.get("type") + "";
					String strs[] = type.split(",");
					for (String s : strs) {
						for (Element element : elementList) {
							if (s.equals(element.getItemcode())) {
								str.append(element.getItemname() + ",");
							}
						}
					}
					if (StringUtils.isNotBlank(str.toString())) {
						map.put("typeName", str.toString().substring(0, str.toString().lastIndexOf(",")));
					}
					list.set(i, map);
				}
				str = new StringBuffer();
				if (map.get("userId") != null && !"".equals(map.get("userId") + "")) {
					String                    userId   = map.get("userId") + "";
					List<Map<String, Object>> userlist = contractIinformationOrderManager.getBusinessRecordBuyUser(userId);
					for (Map<String, Object> maps : userlist) {
						for (Element element : elementList) {
							if ((maps.get("orderType") + "").equals(element.getItemcode())) {
								str.append(element.getItemname() + ",");
							}
						}
						if (StringUtils.isNotBlank(str.toString())) {
							map.put("userTypeName", str.toString().substring(0, str.toString().lastIndexOf(",")));
						}
					}
					list.set(i, map);
				}
			}
			page.setItems(list);
			model.addAttribute("page", page);
			model.addAttribute("organizationList", organizationList);
			return new ModelAndView("admin/contract/contractInformationOrder", model.asMap());
		} catch (Exception e) {
			log.error(LogExceptionStackUtil.LogExceptionStack(e));
		}
		return null;
	}

	/**
	 * 更新完善的用户记录信息
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "saveUpdateContart", method = {RequestMethod.POST}, produces = "application/json;charset=utf-8")
	public @ResponseBody
	String saveUpdateContart(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject jsonObject = new JSONObject();
		try {
			String userId                = request.getParameter("userId");
			String organizationId        = request.getParameter("organizationId");
			String virtualArchitectureId = request.getParameter("virtualArchitectureId");

			jsonObject.put("code", contractIinformationOrderManager.saveUpdateContart(userId, organizationId, virtualArchitectureId, request.getRemoteUser()));
			return jsonObject.toString();
		} catch (Exception e) {
			log.error(LogExceptionStackUtil.LogExceptionStack(e));
		}
		jsonObject.put("code", "error");
		return jsonObject.toString();
	}

	/**
	 * 查询企业签约记录信息
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "businessRecordPage")
	public ModelAndView businessRecordPage(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Model model = new ExtendedModelMap();
		try {
			initFunctionOperate(request); // 初始化功能操作权限
			initModel(model);//初始化数据
			String pageNo = request.getParameter("pageNo");
			if (StringUtils.isBlank(pageNo)) {
				pageNo = "1";
			}
			String virtualArchitectureId = request.getParameter("virtualId");
			if (StringUtils.isNotBlank(virtualArchitectureId)) {
				model.addAttribute("virtualArchitectureId", virtualArchitectureId);
			}
			List<TbOrganization> organizationList = getUserRelationOrgList(request);
			String               orgId            = getUserRelationOrganizationStr(organizationList);
			String               organizationId   = request.getParameter("organizationId");
			if (StringUtils.isNotBlank(organizationId)) {
				model.addAttribute("organizationId", organizationId);
				orgId = organizationId;
			}
			Page page = contractIinformationOrderManager.ContractIinformationPage(10,
					Integer.parseInt(pageNo), orgId, virtualArchitectureId);
			if (page != null && page.getItems() != null) {
				List<Map<String, Object>> list        = page.getItems();
				List<Element>             elementList = this.getElementGroupManager().getElementsByGroupName("signingServiceGroup");
				for (int i = 0; i < list.size(); i++) {
					StringBuffer        str = new StringBuffer();
					Map<String, Object> map = list.get(i);
					if (map.get("type") != null && !"".equals(map.get("type") + "")) {
						String type   = map.get("type") + "";
						String strs[] = type.split(",");
						for (String s : strs) {
							for (Element element : elementList) {
								if (s.equals(element.getItemcode())) {
									str.append(element.getItemname() + ",");
								}
							}
						}
						map.put("typeName", str.toString().substring(0, str.toString().lastIndexOf(",")));
						list.set(i, map);
					}
				}
				page.setItems(list);
				model.addAttribute("page", page);
			}
			model.addAttribute("organizationList", organizationList);
			return new ModelAndView("admin/contract/contractInformation", model.asMap());
		} catch (Exception e) {
			log.error(LogExceptionStackUtil.LogExceptionStack(e));
		}
		return null;
	}

	/**
	 * 保存企业签约信息记录
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "saveUpdateBusinessRecord", method = {RequestMethod.POST}, produces = "application/json;charset=utf-8")
	public @ResponseBody
	String saveUpdateBusinessRecord(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String              organizationId        = request.getParameter("organizationId");
		String              virtualArchitectureId = request.getParameter("virtualArchitectureId");
		String              type                  = request.getParameter("type");
		String              id                    = request.getParameter("id");
		String              status                = request.getParameter("status");
		Map<String, Object> map                   = null;
		VirtualArchitecture virtual               = propertyManager.getVirtualArchitectureById(Integer.parseInt(virtualArchitectureId));
		if (virtual != null) {
			if (StringUtils.isNotBlank(virtual.getPhone()) && StringUtils.isNotBlank(virtual.getCustomerNumber())) {
				try {
					ContractIinformation contractIinformation = new ContractIinformation();
					contractIinformation.setOrganizationId(Integer.parseInt(organizationId));
					contractIinformation.setVirtualArchitectureId(Integer.parseInt(virtualArchitectureId));
					contractIinformation.setType(type);
					contractIinformation.setStatus(status);
					contractIinformation.setIsEnabled("1");
					if (StringUtils.isNotBlank(id)) {
						contractIinformation.setId(Integer.parseInt(id));
						contractIinformation.setModifyTime(new Date());
						contractIinformation.setModifier(request.getRemoteUser());
					} else {
						contractIinformation.setCreateTime(new Date());
						contractIinformation.setCreator(request.getRemoteUser());
					}
					map = contractIinformationOrderManager.saveUpdateBusinessRecord(contractIinformation);
				} catch (Exception e) {
					map = new HashMap<String, Object>();
					log.error(LogExceptionStackUtil.LogExceptionStack(e));
					map.put("desc", "操作失败，程序异常！");
					map.put("flag", false);
				}
			} else {
				map = new HashMap<String, Object>();
				map.put("flag", false);
				map.put("desc", "企业信息资料不完整，请检查企业客户编码和电话号码.");
			}
		} else {
			map = new HashMap<String, Object>();
			map.put("flag", false);
			map.put("desc", "企业信息不存在，请检查！");
		}
		return JSONObject.fromObject(map).toString();
	}

	/**
	 * 保存企业签约信息记录
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "deleteBusinessRecord", method = {RequestMethod.POST}, produces = "application/json;charset=utf-8")
	public @ResponseBody
	String deleteBusinessRecord(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String              id  = request.getParameter("id");
		Map<String, Object> map = null;
		try {
			map = contractIinformationOrderManager.deleteBusinessRecord(Integer.parseInt(id));
		} catch (Exception e) {
			map = new HashMap<String, Object>();
			log.error(LogExceptionStackUtil.LogExceptionStack(e));
			map.put("desc", "操作失败，程序异常！");
			map.put("flag", false);
		}
		return JSONObject.fromObject(map).toString();
	}

	/**
	 * 查询企业签约记录信息详情
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "businessRecordDetails", method = {RequestMethod.POST}, produces = "application/json;charset=utf-8")
	public @ResponseBody
	String businessRecordDetails(HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			String              id          = request.getParameter("id");
			Map<String, Object> map         = contractIinformationOrderManager.businessRecordDetails(Integer.parseInt(id));
			List<Element>       elementList = this.getElementGroupManager().getElementsByGroupName("signingServiceGroup");
			StringBuffer        str         = new StringBuffer();
			if (map.get("type") != null && !"".equals(map.get("type") + "")) {
				String type   = map.get("type") + "";
				String strs[] = type.split(",");
				for (String s : strs) {
					for (Element element : elementList) {
						if (s.equals(element.getItemcode())) {
							str.append(element.getItemname() + ",");
						}
					}
				}
				map.put("typeName", str.toString().substring(0, str.toString().lastIndexOf(",")));
			}
			return JSONObject.fromObject(map).toString();
		} catch (Exception e) {
			log.error(LogExceptionStackUtil.LogExceptionStack(e));
		}
		return null;
	}

	/**
	 * 异步 获取虚拟组织架构
	 */
	@RequestMapping(value = "/getSignVirtualArchitectureList", method = {RequestMethod.POST, RequestMethod.GET}, produces = "application/json")
	public @ResponseBody
	List<VirtualArchitecture> getvirtualArchTypeOne(HttpServletRequest request, HttpServletResponse response) {
		String                    organizationId = request.getParameter("organizationId");
		List<VirtualArchitecture> list           = contractIinformationOrderManager.getSignVirtualArchitectureList(organizationId);
		return list;
	}
}
