package com.palmnest.webapp.controller.notice;

import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.CodeConstants;
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.MD5;
import com.palmnest.application.core.util.PropertiesKit;
import com.palmnest.application.core.util.StringUtil;
import com.palmnest.application.dto.DeptGroupDto;
import com.palmnest.application.dto.output.AuditDto;
import com.palmnest.application.dto.output.AuditInfoDto;
import com.palmnest.model.User;
import com.palmnest.model.notice.MobileConfigModel;
import com.palmnest.model.notice.NoticeApprovalTypeModel;
import com.palmnest.model.notice.PhoneMessageModel;
import com.palmnest.service.UserManager;
import com.palmnest.service.estateserve.SmsAuthCodeManager;
import com.palmnest.service.notice.AppNoticeManager;
import com.palmnest.service.notice.EmailSendManager;
import com.palmnest.service.notice.MobileConfigManager;
import com.palmnest.service.notice.NoticeApprovalsetManager;
import com.palmnest.service.notice.NoticeSubGroupManager;
import com.palmnest.service.notice.PhoneMessageManager;
import com.palmnest.service.notice.service.NoticePublicnoService;
import com.palmnest.service.notice.service.PushSendService;
import com.palmnest.webapp.controller.BaseFormController;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
@RequestMapping("notice/phoneMessage*")
public class PhoneMessageController extends BaseFormController {

	@Autowired
	private PhoneMessageManager phoneMessageManager;
	@Autowired
	private SmsAuthCodeManager  smsAuthCodeManager;
	@Autowired
	private AppNoticeManager    appNoticeManager;
	@Autowired
	private EmailSendManager    emailSendManager;
	@Autowired
	private UserManager         userManager;
	@Autowired
	private PushSendService     pushSendService;
	@Autowired
	private MobileConfigManager mobileConfigManager;
	@Autowired
	private NoticeApprovalsetManager noticeApprovalsetManager;
	
	@Autowired
	private NoticePublicnoService noticePublicnoService;
	
	@Autowired
	private NoticeSubGroupManager noticeSubGroupManager;

	private String smsServer     = PropertiesKit.readPropertiesValue("sms_server", "wechat.properties");
	private String hostUrl       = PropertiesKit.readPropertiesValue("hostUrl", "wechat.properties");
	private String wxMsgUrl      = PropertiesKit.readPropertiesValue("wxMsgUrl", "wechat.properties");
	private String wxMsgAuditUrl = PropertiesKit.readPropertiesValue("wxMsgAuditUrl", "wechat.properties");

	/**
	 * 获取短信消息列表
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getList")
	public void getList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject json = new JSONObject();
		//获取当前登录用户所管辖项目
		User   user        = (User) request.getSession().getAttribute("UserCache");
		String orgIds      = getUserManageOrgIds(user);//例如:1,25,2
		String c_beginTime = request.getParameter("c_beginTime");
		String c_endTime   = request.getParameter("c_endTime");
		String a_beginTime = request.getParameter("a_beginTime");
		String a_endTime   = request.getParameter("a_endTime");
		String state       = request.getParameter("state");
		String pageNo      = request.getParameter("page");
		String orgId       = request.getParameter("orgId");

		if (StringUtils.isNotBlank(orgId)) {
			orgIds = orgId;
		}
		if (StringUtils.isEmpty(pageNo)) {
			pageNo = "1";
		}
		String pageSize = request.getParameter("limit");
		if (StringUtils.isEmpty(pageSize)) {
			pageSize = "10";
		}
		HashMap<String, Object> map = new HashMap<String, Object>();
		if (!StringUtils.isEmpty(c_beginTime)) {
			map.put("c_beginTime", c_beginTime);
		}
		if (!StringUtils.isEmpty(c_endTime)) {
			map.put("c_endTime", c_endTime);
		}
		if (!StringUtils.isEmpty(a_beginTime)) {
			map.put("a_beginTime", a_beginTime);
		}
		if (!StringUtils.isEmpty(a_endTime)) {
			map.put("a_endTime", a_endTime);
		}
		if (!StringUtils.isEmpty(state)) {
			map.put("state", state);
		}
		if(StringUtils.isNotEmpty(orgIds)){
			map.put("orgIds", orgIds);
		}
		
		if (!StringUtils.isEmpty(orgId)) {
			map.put("orgId", orgId);
		}
		
		//当前登录的人的角色id
		String roleIds       = request.getParameter("roleIds");
		if(StringUtils.isNotBlank(roleIds)){
			map.put("roleIds", roleIds);
		}else{
			roleIds=getRoleIds(user);
			map.put("roleIds", roleIds);
		}
		String approvalType       = request.getParameter("approvalType");
		if (!StringUtils.isEmpty(approvalType)) {
			map.put("approvalType", approvalType);
		}

		try {
			Page page = phoneMessageManager.getDataList(map, Integer.parseInt(pageNo), Integer.parseInt(pageSize));
			json.put("code", "200");
			json.put("data", page.getItems());
			json.put("msg", "");
			json.put("count", page.getTotalCount());
			StringUtil.charSet(json, request, response);
		} catch (Exception e) {
			json.put("code", "1");
			json.put("data", "");
			json.put("msg", e.getMessage());
			StringUtil.charSet(json, request, response);
			log.error(e.getMessage());
			throw new Exception(e);
		}

	}

	/**
	 * 获取短信消息详情
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getDetail")
	public void getDetail(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject json = new JSONObject();
		String     id   = request.getParameter("id");
		List<AuditDto> auditList=new ArrayList<AuditDto>();
		try {
			PhoneMessageModel model = phoneMessageManager.get(Integer.parseInt(id));
			if(null != model && null != model.getApprovalType() && 0 != model.getApprovalType().intValue()){
				auditList=noticeApprovalsetManager.getAuditList(model.getOrgId(), CodeConstants.ORDER_TYPE_MESSAGE, model.getId());
			}
			
			String approvalTypeName="";
			if(null != model.getApprovalType() && 0 != model.getApprovalType().intValue()){
				NoticeApprovalTypeModel typeModel=noticeApprovalsetManager.findById(model.getApprovalType());
				if(null != typeModel){
					approvalTypeName=typeModel.getName();
				}
			}
			
			json.put("approvalTypeName", approvalTypeName);
			
			json.put("auditList", auditList);
			json.put("code", "200");
			json.put("data", model);
			json.put("msg", "");
			StringUtil.charSet(json, request, response);
		} catch (Exception e) {
			json.put("code", "1");
			json.put("auditList", auditList);
			json.put("data", "");
			json.put("msg", e.getMessage());
			StringUtil.charSet(json, request, response);
			log.error(e.getMessage());
			throw new Exception(e);
		}

	}


	/**
	 * 新增修改短信消息
	 *
	 * @param phoneMessage
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/saveOrUpdate")
	@ResponseBody
	public AppResultDto saveOrUpdate(@ModelAttribute("phoneMessageModel") PhoneMessageModel phoneMessage,
							 HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			User user = (User) request.getSession().getAttribute("UserCache");
			
			Integer createBy=null;
			if(null != user){
				createBy=Integer.parseInt(user.getId().toString());
			}

			SimpleDateFormat sif     = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String           phones  = request.getParameter("phones");
			String           content = request.getParameter("content");
			String           id      = request.getParameter("id");
			String           orgId   = request.getParameter("orgId");
			String           approvalType   = request.getParameter("approvalType");
			
			String           receiveType   = request.getParameter("receiveType");
			String           deptGroupJson   = request.getParameter("deptGroupJson");//部门或分组
			int recType=Integer.parseInt(receiveType);
			if (StringUtils.isNotEmpty(id)) {// 修改
				phoneMessage = phoneMessageManager.get(Integer.parseInt(id));
				phoneMessage.setOrgId(Integer.parseInt(orgId));
				phoneMessage.setPhones(phones);
				if(StringUtils.isNotEmpty(phones)){
					phoneMessage.setPhones_quantity(phones.split(",").length);
				}
				phoneMessage.setContent(content);
				phoneMessage.setModifier(createBy.toString());
				phoneMessage.setModifyTime((new Date()));
//				if(StringUtils.isBlank(approvalType)){
//					phoneMessage.setApprovalType(0);
//				}else{
//					phoneMessage.setApprovalType(Integer.parseInt(approvalType));
//				}

			} else {//新增
				phoneMessage.setOrgId(Integer.parseInt(orgId));
				phoneMessage.setPhones(phones);
				if(StringUtils.isNotEmpty(phones)){
					phoneMessage.setPhones_quantity(phones.split(",").length);
				}
				phoneMessage.setContent(content);
				phoneMessage.setCreator(createBy.toString());
				phoneMessage.setState(0);
				phoneMessage.setCreateTime(new Date());
				phoneMessage.setIsEnabled("1");
				if(StringUtils.isBlank(approvalType)){
					phoneMessage.setApprovalType(0);
				}else{
					phoneMessage.setApprovalType(Integer.parseInt(approvalType));
				}
			}

			PhoneMessageModel model = phoneMessageManager.saveOrUpdatePhoneMessageModel(phoneMessage);
			if(2 == recType && null != model && null != model.getId() && StringUtils.isNotEmpty(deptGroupJson)){
				//发送方式:1-按邮箱发送；2-按部门/分组发送
				List<DeptGroupDto> dtoList=JSONObject.parseArray(deptGroupJson,DeptGroupDto.class);
				if(!CollectionUtils.isEmpty(dtoList)){
					//类型：1-公告;2-微信模板;3-短信;4-邮件;
					noticeSubGroupManager.saveByDeptGroup(3, model.getId(), dtoList, createBy);
					//保存完了之后把用户信息查出来，然后保存到相应的数据里面去
					AppResultDto dto=appNoticeManager.setUserInfo(orgId, dtoList, 2);
					if("200".equals(dto.getCode())){
						model.setPhones(dto.getMsg());
						phoneMessageManager.saveOrUpdatePhoneMessageModel(model);
					}
				}else{
					return AppResultUtil.createErrorDto("1", "保存邮件消息失败:未选择部门或分组");
				}
			}
			if(StringUtils.isBlank(id)){
				String     pathUrl = hostUrl + wxMsgAuditUrl.replace("@id", model.getId().toString())+ "&isApproval=1&approvalType="+model.getApprovalType();
				if(null != model.getApprovalType() && 0 != model.getApprovalType().intValue()){
					//推送消息
					List<User> users=noticePublicnoService.getPushMsgUserById(model.getApprovalType(), model.getOrgId(), CodeConstants.ORDER_TYPE_MESSAGE, model.getId());
					if(!CollectionUtils.isEmpty(users)){
						appNoticeManager.pushMessage(Long.parseLong(model.getId().toString()), CodeConstants.MESSAGE_PUSH_CODE, pathUrl, "您有新的待审核短信消息，请及时审核！", "有新邮件消息待审核", users);
					}
				}else{
					//推送消息
					List<User> users   = userManager.findByFunction(model.getOrgId(), CodeConstants.AUDIT_NOTICE_PERMISSION);
					appNoticeManager.pushMessage(Long.parseLong(model.getId().toString()), CodeConstants.MESSAGE_PUSH_CODE, pathUrl, "有新公告通知待审核", "有新短信消息待审核", users);
				}
			}
			return AppResultUtil.createCommonDto("200", "success", "success");
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto("1", "保存短信消息失败:"+e.getMessage());
		}

	}
	
	/**
	 * 审核短信消息
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/approval")
	public void approval(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject json = new JSONObject();
		try {
			User user = (User) request.getSession().getAttribute("UserCache");

			String id    = request.getParameter("id");
			String state = request.getParameter("state");// 未审核-0、已发布-1、已驳回-2
			if (StringUtils.isNotEmpty(id)) {
				PhoneMessageModel phoneMessage = phoneMessageManager.get(Integer.parseInt(id));
				String            userId       = phoneMessage.getCreator();

				List<User> userList = new ArrayList<User>();
				User       user2    = userManager.get(Long.parseLong(userId));
				userList.add(user2);
				String pathUrl = hostUrl + wxMsgUrl.replace("@id", id.toString());

				phoneMessage.setApproval_user(user.getFullName());//审核人
				phoneMessage.setApproval_time((new Date()));//审核时间
				phoneMessage.setModifyTime((new Date()));//修改时间
				phoneMessage.setState(Integer.parseInt(state));//短信状态
				String[] phones = phoneMessage.getPhones().split(",");//推送号码
				phoneMessage.setTotal(phones.length);//推送条数

				if (phoneMessage.getState() == 1) {//审核通过操作
					//异步发送短信
					Integer orgId = phoneMessage.getOrgId();
					if (null != orgId) {
						List<MobileConfigModel> list = mobileConfigManager.getMobileConfigList(orgId + "");
						if (null != list && list.size() > 0) {
							//获取当前项目配置的短信账号信息
							MobileConfigModel model             = list.get(0);
							String            username_platform = model.getMobileNum();
							String            password_platform = model.getPassword();
							//密码加密
							String md5temp = MD5.sign(password_platform, "", "utf-8");
							password_platform = MD5.sign(username_platform + md5temp, "", "utf-8");
							//发布短信
							smsAuthCodeManager.smsSend(username_platform, password_platform, phoneMessage.getContent(), phoneMessage.getPhones());
						}
					}
					phoneMessage.setSend_time(new Date());//发送时间
					phoneMessageManager.updateModel(phoneMessage);

					json.put("code", "200");
					json.put("msg", "success");
					StringUtil.charSet(json, request, response);
					appNoticeManager.pushMessage(Long.parseLong(id), CodeConstants.MESSAGE_PUSH_CODE, pathUrl, "您发起的短信消息已审核通过", "已审核通过", userList);
				} else if (phoneMessage.getState() == 0) {
					phoneMessage.setState(0);
					phoneMessageManager.updateModel(phoneMessage);

					json.put("code", "200");
					json.put("msg", "success");
					json.put("data", "未通过审核");
					StringUtil.charSet(json, request, response);
				} else if (phoneMessage.getState() == 2) {
					phoneMessage.setState(2);
					phoneMessageManager.updateModel(phoneMessage);

					json.put("code", "200");
					json.put("msg", "success");
					json.put("data", "已驳回");
//					emailSendManager.sendMesseg(id, userId, "3", "被驳回");
					appNoticeManager.pushMessage(Long.parseLong(id), CodeConstants.MESSAGE_PUSH_CODE, pathUrl, "您发起的短信消息已被驳回", "未审核通过", userList);
					StringUtil.charSet(json, request, response);
				} else {
					json.put("code", "1");
					json.put("msg", "fail");
					json.put("data", "参数错误");
					StringUtil.charSet(json, request, response);
				}
			} else {
				json.put("code", "1");
				json.put("msg", "fail");
				json.put("data", "参数错误");
				StringUtil.charSet(json, request, response);
			}


		} catch (Exception e) {
			json.put("code", "1");
			json.put("msg", "fail");
			json.put("data", e.getMessage());

			StringUtil.charSet(json, request, response);
			log.error(e.getMessage());
			e.printStackTrace();
			throw new Exception(e);
		}

	}

	/**
	 * 新增时导入的接口
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/txtToPhone")
	@ResponseBody
	public void txtToPhone(@RequestParam(value = "uploadfile", required = false) CommonsMultipartFile uploadFy,
						   HttpServletRequest request, HttpServletResponse response) {
		JSONObject  json = new JSONObject();
		InputStream in   = null;
		if (uploadFy == null) {

			json.put("code", "1");
			json.put("msg", "fail");
			json.put("data", "上传文件为空");

			StringUtil.charSet(json, request, response);
		}
		try {
			// 使用Apache文件上传组件处理文件上传步骤：
			// 1、创建一个DiskFileItemFactory工厂
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// 2、创建一个文件上传解析器
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 解决上传文件名的中文乱码
			upload.setHeaderEncoding("UTF-8");
			// 3、判断提交上来的数据是否是上传表单的数据
			if (!ServletFileUpload.isMultipartContent(request)) {
				// 按照传统方式获取数据
				json.put("code", "1");
				json.put("msg", "fail");
				json.put("data", "没有文件上传");
				StringUtil.charSet(json, request, response);
			}
			in = uploadFy.getInputStream();
			InputStreamReader  inputStreamReader = new InputStreamReader(in);
			BufferedReader     br                = new BufferedReader(inputStreamReader);
			Pattern            pattern           = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$");
			ArrayList<String>  emailList         = new ArrayList<String>();
			String             temp              = null;
			ArrayList<Integer> errorLine         = new ArrayList<Integer>();
			for (int i = 1; (temp = br.readLine()) != null; i++) {
				temp.trim();
				Matcher matcher = pattern.matcher(temp);
				if (matcher.matches()) {
					emailList.add(temp);
				} else {
					errorLine.add(i);
				}
			}
			StringBuffer errorLineBuffer = new StringBuffer();
			errorLineBuffer.append("上传成功,第");
			for (Integer integer : errorLine) {
				errorLineBuffer.append(integer + ",");
			}
			if (errorLineBuffer.toString().equals("上传成功,第") && !emailList.isEmpty()) {
				json.put("code", "200");
				json.put("msg", "success");
				json.put("data", emailList);
			} else if (errorLineBuffer.toString().equals("上传成功,第") && emailList.isEmpty()) {
				json.put("code", "1");
				json.put("msg", "导入失败,文件为空!");
			} else {
				errorLineBuffer.append("行数据格式有错误");
				json.put("code", "1");
				json.put("msg", errorLineBuffer.toString());
				json.put("data", emailList);
			}

			StringUtil.charSet(json, request, response);
		} catch (Exception e) {
			// message= "文件上传失败！";
			json.put("code", "1");
			json.put("msg", "fail");
			json.put("data", "文件上传失败！");
			StringUtil.charSet(json, request, response);
			log.error(e.getMessage());
			e.printStackTrace();
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}


	/**
	 * 发送短信
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/sendMsg")
	public void sendMsg(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject json       = new JSONObject();
		String     userMobile = request.getParameter("userMobile");
		String     content    = request.getParameter("content");

		try {
//			StringBuffer params=new StringBuffer();
//			params.append("phones="+userMobile);
//			params.append("&content="+content);
//			params.append("&smstype=1");
//			params.append("&APPID=e7e0e8b007f2fa5e8de4afccfefc649703d67d4568eab5839b86b3d58163d472");// SHA256
			String result = smsAuthCodeManager.smsSend(userMobile, content);


			json.put("code", "200");
			json.put("msg", "success");
			json.put("data", result);
		} catch (Exception e) {
			json.put("code", "1");
			json.put("msg", "发送失败");
			json.put("data", "");

			StringUtil.charSet(json, request, response);
			log.error(e.getMessage());
			throw new Exception(e);
		}


	}

//	/**
//	 * 跳转到界面
//	 * 
//	 * @param request
//	 * @param response
//	 */
//	@RequestMapping(value = "/noticeMsgSend*")
//	public ModelAndView noticeMsgSend(HttpServletRequest request, HttpServletResponse response) {
//		return new ModelAndView("admin/notice/noticeMsgSend");
//	}
//
//	/**
//	 * 跳转到界面-发布
//	 * 
//	 * @param request
//	 * @param response
//	 */
//	@RequestMapping(value = "/noticeMsgPublish*")
//	public ModelAndView noticeMsgPublish(HttpServletRequest request, HttpServletResponse response) {
//		return new ModelAndView("admin/notice/noticeMsgPublish");
//	}
//
//	/**
//	 * 跳转到界面-审核
//	 * 
//	 * @param request
//	 * @param response
//	 */
//	@RequestMapping(value = "/noticeMsgVerify*")
//	public ModelAndView noticeMsgVerify(HttpServletRequest request, HttpServletResponse response) {
//		return new ModelAndView("admin/notice/noticeMsgVerify");
//	}

	/**
	 * 删除短息公告
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/deleteNotice")
	@ResponseBody
	public void deleteNotice(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		phoneMessageManager.remove(Integer.parseInt(id));
		JSONObject json = new JSONObject();
		json.put("code", "200");
		json.put("msg", "success");
		StringUtil.charSet(json, request, response);
	}
}
