package com.palmnest.webapp.controller.backstage;

import com.palmnest.application.Constants;
import com.palmnest.application.bean.Page;
import com.palmnest.application.dto.OutRetMsg;
import com.palmnest.model.User;
import com.palmnest.model.estateserve.Picandtextdetailstemp;
import com.palmnest.model.estateserve.Replykeywords;
import com.palmnest.model.estateserve.Textpicvoicetemp;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.service.estateserve.PublicNoManager;
import com.palmnest.service.estateserve.ScPicandtextdetailstempManager;
import com.palmnest.service.estateserve.ScReplykeywordsManager;
import com.palmnest.service.estateserve.ScTextpicvoicetempManager;
import com.palmnest.webapp.controller.BaseFormController;
import lombok.extern.slf4j.Slf4j;
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.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
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.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 消息模板前端控制器
 *
 * @author xguo
 */
@Slf4j
@Controller
@RequestMapping("/estate/msgTemplate*")
public class ScMsgTemplateController extends BaseFormController {

	@Autowired
	private PublicNoManager                pubicNoManager;
	@Autowired
	private ScReplykeywordsManager         scReplykeywordsManager;
	@Autowired
	private ScTextpicvoicetempManager      scTextpicvoicetempManager;
	@Autowired
	private ScPicandtextdetailstempManager scPicandtextdetailstempManager;

	/**
	 * 查询消息模板列表
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "query")
	public ModelAndView query(HttpServletRequest request,
							  HttpServletResponse response) {
		initFunctionOperate(request); // 初始化功能操作权限
		Model model = new ExtendedModelMap();
		try {
			//查看当前管理员的项目管理权限
			List<TbOrganization>      organizationList = getUserRelationOrgList(request);
			List<Map<String, Object>> publicnos        = pubicNoManager.getAllWxPublicno(getUserRelationOrganizationStr(organizationList));

			int    pageNo    = StringUtils.isNotEmpty(request.getParameter("pageNo")) ? Integer.valueOf(request.getParameter("pageNo")) : 1;
			String developId = request.getParameter("developId");
			String name      = request.getParameter("name");
			String state     = request.getParameter("state");
			if (StringUtils.isNotEmpty(developId)) {
				model.addAttribute("developId", developId);
			} else {
				if (!CollectionUtils.isEmpty(publicnos)) {
					developId = (String) publicnos.get(0).get("developId");
					model.addAttribute("developId", developId);
				}
			}
			if (StringUtils.isNotEmpty(name)) {
				model.addAttribute("name", name);
			}
			if (StringUtils.isNotEmpty(state)) {
				model.addAttribute("state", state);
			}
			Page page = scReplykeywordsManager.getReplykeywords(pageNo, 10, developId, name, state);
			model.addAttribute("publicnos", publicnos);
			model.addAttribute("page", page);
		} catch (Exception e) {
			log.error("ScMsgTemplateAction query error{}", e, e.getStackTrace());
		}
		return new ModelAndView("msgtemplate/msgTemplateList", model.asMap());
	}

	/**
	 * 删除模板
	 */
	@RequestMapping(value = "detele", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	OutRetMsg deleteTemplate(HttpServletRequest request, HttpServletResponse response) {
		OutRetMsg outmsg = new OutRetMsg();
		try {
			String   item  = request.getParameter("dataAreaIds");
			String[] items = item.split(";");
			if (!ArrayUtils.isEmpty(items)) {
				Integer[] ids = new Integer[items.length];
				for (int i = 0; i < items.length; i++)
					ids[i] = Integer.parseInt(items[i]);

				scReplykeywordsManager.deleteTemplate(ids);
			}
			outmsg.setErrcode("200");
			outmsg.setErrmsg("success");
		} catch (Exception e) {
			log.error("deleteTemplate  error.{}", e,
					e.getMessage());
			outmsg.setErrcode("500");
			outmsg.setErrmsg("fail");
		}
		return outmsg;
	}

	/**
	 * 查询消息模板列表
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "preAdd")
	public ModelAndView preAdd(HttpServletRequest request,
							   HttpServletResponse response) {
		Model model = new ExtendedModelMap();
		try {
			//查看当前管理员的项目管理权限
			List<TbOrganization>      organizationList = getUserRelationOrgList(request);
			List<Map<String, Object>> publicnos        = pubicNoManager.getAllWxPublicno(getUserRelationOrganizationStr(organizationList));

			model.addAttribute("publicnos", publicnos);
			model.addAttribute("DevelopType", this.getElementGroupManager().getElementsByGroupName(Constants.DevelopType));
			model.addAttribute("IMAGE_SERVER", Constants.IMAGE_SERVER);//文件服务器访问路径
		} catch (Exception e) {
			log.error("ScMsgTemplateAction preAdd error{}", e, e.getStackTrace());
		}
		return new ModelAndView("msgtemplate/msgTemplateForm", model.asMap());
	}

	/**
	 * 新增 保存模板
	 */
	@RequestMapping(value = "save")
	public String save(@ModelAttribute("replykeywords") Replykeywords replykeywords, HttpServletRequest request,
					   HttpServletResponse response) {
		User user = (User) request.getSession().getAttribute("UserCache");
		replykeywords.setCreateTime(new Date());
		replykeywords.setCreatePerson(user.getUsername());
		if (StringUtils.equals(replykeywords.getReplyContentType(), Constants.PIC_TEXT_VOICE_TYPE)) {//单条
			String text = request.getParameter("text");
			scReplykeywordsManager.saveScTextpicvoicetemp(replykeywords, text);
		} else if (StringUtils.equals(replykeywords.getReplyContentType(), Constants.PIC_AND_WORD)) {//图文
			List<Picandtextdetailstemp> ls                 = new ArrayList<Picandtextdetailstemp>();
			String[]                    metaFileUrls       = request.getParameterValues("metaFileUrls");
			String[]                    metaFileRemarks    = request.getParameterValues("metaFileRemarks");
			String[]                    metaFileSeqs       = request.getParameterValues("metaFileSeqs");
			String[]                    metaFileTitles     = request.getParameterValues("metaFileTitles");
			String[]                    metaFileTargetUrls = request.getParameterValues("metaFileTargetUrls");
			if (metaFileUrls != null) {
				for (int i = 0; i < metaFileUrls.length; i++) {
					Picandtextdetailstemp temp = new Picandtextdetailstemp();
					temp.setDescription(metaFileRemarks[i]);
					temp.setPicUrl(metaFileUrls[i]);
					temp.setSequence(metaFileSeqs[i]);
					temp.setTitle(metaFileTitles[i]);
					temp.setUrl(metaFileTargetUrls[i]);
					ls.add(temp);
				}
			}
			scReplykeywordsManager.saveScPicandtexttemp(replykeywords, ls);
		}
		return "redirect:/estate/msgTemplate/query";
	}

	/**
	 * 跳转到修改界面
	 */
	@RequestMapping(value = "preModify")
	public ModelAndView preModify(HttpServletRequest request,
								  HttpServletResponse response) {
		Model model = new ExtendedModelMap();
		try {


			String _id = request.getParameter("id");
			if (StringUtils.isEmpty(_id))
				throw new IllegalArgumentException("参数错误！");
			int id = 0;
			try {
				id = Integer.parseInt(_id);
			} catch (NumberFormatException e) {
				log.error("客户端输入数据无效。输入参数为{}，此处只接受正整数", _id);
				throw new IllegalArgumentException("输入数据错误");
			}
			model.addAttribute("IMAGE_SERVER", Constants.IMAGE_SERVER);//文件服务器访问路径

			//查看当前管理员的项目管理权限
			List<TbOrganization>      organizationList = getUserRelationOrgList(request);
			List<Map<String, Object>> publicnos        = pubicNoManager.getAllWxPublicno(getUserRelationOrganizationStr(organizationList));

			model.addAttribute("publicnos", publicnos);
			model.addAttribute("DevelopType", this.getElementGroupManager().getElementsByGroupName(Constants.DevelopType));

			Replykeywords keyword = scReplykeywordsManager.getReplykeywordsById(id);
			model.addAttribute("keyword", keyword);

			if (StringUtils.equals(keyword.getReplyContentType(), "1")) {
				Textpicvoicetemp detail = scTextpicvoicetempManager.gettextpicvoicetemp(id);
				model.addAttribute("scTextpicvoicetemp", detail);
			} else if (StringUtils.equals(keyword.getReplyContentType(), "2")) {
				List<Picandtextdetailstemp> detail = scPicandtextdetailstempManager.getScPicandtextdetailstemps(id);
				model.addAttribute("scPicandtextdetailstemps", detail);
			}
		} catch (Exception e) {
			log.error("ScMsgTemplateAction preModify error{}", e, e.getStackTrace());
		}

		return new ModelAndView("msgtemplate/msgTemplateForm", model.asMap());
	}

	/**
	 * 删除图文详情一条
	 */
	@RequestMapping(value = "removeScPicandtextdetailstemp", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	OutRetMsg removeScPicandtextdetailstemp(HttpServletRequest request, HttpServletResponse response) {
		OutRetMsg outmsg = new OutRetMsg();
		try {
			String detailId = request.getParameter("detailId");
			if (StringUtils.isNotEmpty(detailId)) {
				scPicandtextdetailstempManager.removeScPicandtextdetailstemp(Integer.parseInt(detailId));
			}
			outmsg.setErrcode("200");
			outmsg.setErrmsg("success");
		} catch (Exception e) {
			log.error("deleteTemplate  error.{}", e,
					e.getMessage());
			outmsg.setErrcode("500");
			outmsg.setErrmsg("fail");
		}
		return outmsg;
	}
}
