package com.palmnest.webapp.controller.backstage;

import com.palmnest.application.AppConstants;
import com.palmnest.application.ElementConstant;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.PropertiesKit;
import com.palmnest.application.dto.OrgDto;
import com.palmnest.application.dto.OutTreeDTO;
import com.palmnest.application.dto.WebPageResultDto;
import com.palmnest.model.Element;
import com.palmnest.model.User;
import com.palmnest.model.estateserve.WxPublicno;
import com.palmnest.model.estateserve.WxPublicnoOrgRelation;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.service.AppUserService;
import com.palmnest.service.estateserve.PublicNoManager;
import com.palmnest.service.property.PropertyManager;
import com.palmnest.webapp.controller.BaseFormController;
import org.apache.commons.lang.ArrayUtils;
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.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/pblic/no/*")
public class PublicNoController extends BaseFormController {

	@Autowired
	private PublicNoManager pubicNoManager;
	@Autowired
	private PropertyManager propertyManager;
	@Autowired
	private AppUserService  appUserService;

	/**
	 * 列表页面跳转
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/list")
	public ModelAndView handleRequest(HttpServletRequest request,
									  HttpServletResponse response) throws Exception {
		initFunctionOperate(request); // 初始化功能操作权限
		Model        model = new ExtendedModelMap();
		User         user  = (User) request.getSession().getAttribute("UserCache");
		List<OrgDto> dtos  = appUserService.getUserOrgs(user.getId());
		model.addAttribute("organizationList", dtos);
		model.addAttribute("imageServer", PropertiesKit.readPropertiesValue("image_server", "wechat.properties"));
		return new ModelAndView("publicno/publicNoList", model.asMap());
	}

	/**
	 * longmeizhen
	 * 获取微信公众号列表
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getPubList")
	@ResponseBody
	public WebPageResultDto getPubList(HttpServletRequest request) {

		initFunctionOperate(request); // 初始化功能操作权限
		List<TbOrganization> organizationList = getUserRelationOrgList(request);

		String       pageNo         = request.getParameter("pageNo");
		String       name           = request.getParameter("name");
		String       organizationId = request.getParameter("organizationId");
		StringBuffer strSQL         = new StringBuffer("SELECT t1.ID,t1.`name`,t1.developType,t1.url,t1.creator,t1.createTime,group_concat(t3.`name`) as organizationName");
		strSQL.append(" from tb_wxpublicno t1");
		strSQL.append(" INNER JOIN tr_wxpublicno_org t2 ON t1.ID = t2.publicNoId");
		strSQL.append(" INNER JOIN tb_organization t3 on t2.organizationId=t3.ID");
		strSQL.append(" where 1=1");
		if (StringUtils.isEmpty(pageNo)) {
			pageNo = "1";
		}
		if (StringUtils.isNotBlank(name)) {
			strSQL.append(" and t1.`name` like '%" + name + "%'");
		}
		if (StringUtils.isNotBlank(organizationId)) {
			strSQL.append(" and t2.organizationId=" + organizationId);
		} else {
			strSQL.append(" and t2.organizationId in(" + getUserRelationOrganizationStr(organizationList) + ")");
		}
		strSQL.append(" and t1.isEnabled='" + ElementConstant.YESORNO_1 + "'");
		strSQL.append(" GROUP BY t1.id");
		Page             page   = pubicNoManager.queryPublicNoPage(Integer.parseInt(pageNo), strSQL.toString());
		WebPageResultDto webDto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "", page.getItems());
		webDto.setCount(page.getTotalCount());
		return webDto;
	}


	@RequestMapping(value = "/form")
	public ModelAndView formRequest(@ModelAttribute("publicno") WxPublicno publicno,
									HttpServletRequest request, HttpServletResponse response) throws Exception {
		Model  model      = new ExtendedModelMap();
		String actType    = request.getParameter("actType");
		String publicnoId = request.getParameter("publicnoId");
		if (publicno.getGetAccessTokenUrl() == null || publicno.getGetAccessTokenUrl().trim().length() == 0) {
			publicno.setGetAccessTokenUrl(null);
		}
		if (StringUtils.isNotBlank(publicnoId)) {
			publicno = pubicNoManager.getWxPublicnoById(Integer.parseInt(publicnoId));
			model.addAttribute("publicno", publicno);
		}
		// 新增或者更新
		if ("save".equals(actType)) {
			publicno.setCreateTime(new Date());
			publicno.setCreator(request.getRemoteUser());
			publicno.setIsEnabled(ElementConstant.YESORNO_1);

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

			String retCode = pubicNoManager.saveOrUpdatePublicno(publicno, organizationIds.split(";"));
			if ("2".equals(retCode)) {
				model.addAttribute("errormsg", "更新成功");
			} else {
				model.addAttribute("errormsg", "新增成功");
			}
		}
		List<Element> publicnoServiceGroup = this.getElementGroupManager().getElementsByGroupName("publicnoServiceGroup");
		List<Element> publicnoTypeGroup    = this.getElementGroupManager().getElementsByGroupName("publicnoTypeGroup");
		model.addAttribute("publicnoServiceGroup", publicnoServiceGroup);
		model.addAttribute("publicnoTypeGroup", publicnoTypeGroup);
		model.addAttribute("funcid", request.getParameter("funcid"));
		model.addAttribute("imageServer", PropertiesKit.readPropertiesValue("image_server", "wechat.properties"));
		return new ModelAndView("publicno/publicNoForm", model.asMap());
	}

	/**
	 * 删除
	 */
	@RequestMapping(value = "/deleteGroup*", method = RequestMethod.POST)
	public void deleteElement(HttpServletRequest request,
							  HttpServletResponse response) {
		String[] items = request.getParameterValues("id");
		if (!ArrayUtils.isEmpty(items)) {
			Long[] ids = new Long[items.length];
			for (int i = 0; i < items.length; i++) {
				ids[i] = Long.valueOf(items[i]);
				WxPublicno scPublicno = pubicNoManager.getWxPublicnoById(ids[i].intValue());
				scPublicno.setModifier(request.getRemoteUser());
				scPublicno.setModifyTime(new Date());
				scPublicno.setIsEnabled(ElementConstant.YESORNO_0);
				pubicNoManager.updateModel(scPublicno);
			}
		}
	}

	/**
	 * 删除部门，逻辑删除
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/delete/{id}&{funcid}")
	public String delete(@PathVariable int id, @PathVariable long funcid, HttpServletRequest request) {
		WxPublicno publicno = pubicNoManager.getWxPublicnoById(id);
		publicno.setModifier(request.getRemoteUser());
		publicno.setModifyTime(new Date());
		publicno.setIsEnabled(ElementConstant.YESORNO_0);
		pubicNoManager.updateModel(publicno);
		return "redirect:/pblic/no/list?funcid=" + funcid;
	}

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

		List<TbOrganization>        organizationList      = getUserRelationOrgList(request);
		List<WxPublicnoOrgRelation> organizationRelations = new ArrayList<WxPublicnoOrgRelation>();
		String                      publicnoId            = request.getParameter("publicnoId");
		if (StringUtils.isNotEmpty(publicnoId)) {
			organizationRelations = pubicNoManager.getWxPublicnoOrgRelations(Integer.parseInt(publicnoId));
		}
		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 (WxPublicnoOrgRelation wxPublicnoOrgRelation : organizationRelations) {
				if (wxPublicnoOrgRelation.getOrganizationId().intValue() == organization.getId().intValue()) {
					obj.setChecked(true);
				}
			}
			trees.add(obj);
		}
		//根节点
		OutTreeDTO obj1 = new OutTreeDTO();
		obj1.setId("0");
		obj1.setName("所有项目");
		obj1.setpId("-1");
		trees.add(obj1);
		return trees;
	}
}
