package com.ssm.controller.business;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

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

import com.alibaba.fastjson.JSON;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.ssm.model.business.SmsRecord;
import com.ssm.model.business.SmsSendState;
import com.ssm.model.business.SmsUpMessage;
import com.ssm.model.business.SmsUser;
import com.ssm.model.system.SysDictionary;
import com.ssm.model.system.SysUser;
import com.ssm.service.business.SmsRecordService;
import com.ssm.service.business.SmsSendStateService;
import com.ssm.service.business.SmsUpMessageService;
import com.ssm.service.business.SmsUserService;
import com.ssm.service.business.UploadService;
import com.ssm.service.system.SysDictionaryService;
import com.ssm.util.MD5Utils;
import com.ssm.util.Util;
import com.ssm.util.page.PagedResult;
import com.ssm.util.sms.SmsConst;
import com.ssm.util.sms.SmsUtil;
import com.ssm.util.sms.UploadProcess;
import com.ssm.util.sms.excel.exception.ExcelParseException;
import com.ssm.util.sms.excel.parser.ExcelParserImpl;
import com.ssm.util.sms.excel.validation.rule.ValidationRule;
import com.ssm.web.Const;
import com.ssm.web.RoleLimit;
import com.ssm.web.WithoutUserLogin;

@RequestMapping("sms")
@Controller
public class SendMessageContorller {
	
	static Logger logger = Logger.getLogger(SendMessageContorller.class);
	
	@Autowired
	private SmsUserService smsUserService;
	@Autowired
	private SmsRecordService smsRecordService;
	@Autowired
	private SmsSendStateService smsSendStateService;
	
	@Autowired 
	private SysDictionaryService sysDictionaryService;
	@Autowired
	private SmsUpMessageService smsUpMessageService;
	
	@Autowired
	private UploadService uploadService;
	/**
	 * 进入发送信息主页面
	 * @param model
	 * @return
	 */
	@RoleLimit(pid = "sms", mid = "sendSmsList")
	@RequestMapping(value="sendSmsList")
	public String sendSmsListMessage(Model model){
		List<SysDictionary> constList =  sysDictionaryService.selectByEnabledNamespace(SmsConst.SMS_DEPARTMENT);
		model.addAttribute("constList", constList);
		return "sms/sendSmsList";
	}
	
	/**
	 * 加载用户数据
	 * @param request
	 * @param model
	 * @param smsUser
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@RequestMapping(value="initDataList")
	public String initDataList(HttpServletRequest request, Model model,SmsUser smsUser, Integer pageNo, Integer pageSize){
		PagedResult<SmsUser> smsUserList = smsUserService.selectSmsUser(smsUser,pageNo,pageSize);
		model.addAttribute("list", smsUserList);
		return "sms/dataList";
	}
	
	
	
	/**
	 * 发送短信
	 *
	 * @param request
	 * @return
	 */
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@Transactional(value = "txManager")
	@RequestMapping(value = "sendMessage")
	public Map<String, Object> sendMessage(HttpServletRequest request) {
		SysUser sysuser = Util.getUserSession(request);
		Map<String, Object> map = new HashMap<String, Object>();
		if (sysuser != null) {
			try {
				request.setCharacterEncoding("utf-8");
				String smsUserPhoens = request.getParameter("smsUserPhoens");
				String content = request.getParameter("content");
				String res = SmsUtil.sendNewSmsPost(smsUserPhoens, content);
				Map mapObj = JSON.parseObject(res, Map.class);
				String msgNo = mapObj.get("msg_no").toString();
				int code = (int) map.get("code");
				//将短信记录保存进数据库
				SmsRecord smsRecord = new SmsRecord();
				smsRecord.setContent(content);
				smsRecord.setCreateDate(new Date());
				smsRecord.setPhoens(smsUserPhoens);
				smsRecord.setMsgid(msgNo);
				smsRecordService.insertSelective(smsRecord);
				if (code == 0) {// 提交供应商成功,查询发送是否成功
					SmsSendState sss = new SmsSendState();
					sss.setMsgid(msgNo);
					sss.setCreateDate(new Date());
					sss.setContents(res);
					smsSendStateService.insertSelective(sss);
					map.put("status", SmsConst.SUCCESS);
					map.put("message", "发送成功");
				}
			} catch (Exception e) {
				map.put("status", SmsConst.ERROR);
				map.put("message", e.getMessage());
//				System.err.println(e.getMessage());
				e.printStackTrace();
			}
		} else {
			map.put("status", SmsConst.FAILURE);
			map.put("message", "请登录以后再执行此操作");
		}
		return map;
	}
	
	/**
	 * 接口发送短信
	 * @param phones 手机号码
	 * @param Contents 发送内容
	 * @param md5 加密
	 * @return
	 */
	@WithoutUserLogin
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@Transactional(value="txManager")
	@RequestMapping(value="sendSms")
	public void sendSms(HttpServletRequest request,HttpServletResponse response){
		JSONObject json = new JSONObject();
		try {
			request.setCharacterEncoding("utf-8");
			String phones = request.getParameter("phones");
			String contents = request.getParameter("contents");
			String md5 = request.getParameter("md5");
			if( phones == null || phones == "" ){
				json.element("status", "1");
				json.element("message", "参数缺失");
			}else if( contents == null || contents == "" ){
				json.element("status", "1");
				json.element("message", "参数缺失");
			}else if( md5 == null || md5 == "" ){
				json.element("status", "1");
				json.element("message", "参数缺失");
			}else{
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
				String date = sdf.format(new Date());
				String md = "phones="+phones+"&key=dgtissms&date="+date;
				logger.info("md5 before ----" + md);
				logger.info("md5 before request----" + md5);
				md = MD5Utils.getMD5(md);
				if(md.equalsIgnoreCase(md5)){
					String[] phonesArray = phones.split(",");
					//发送短信
					String msgid = SmsUtil.SendSmsPost(phones, contents,phonesArray.length);
					//将短信记录保存进数据库
					SmsRecord smsRecord = new SmsRecord();
					smsRecord.setContent(contents);
					smsRecord.setCreateDate(new Date());
					smsRecord.setPhoens(phones);
					smsRecord.setMsgid(msgid);
					smsRecordService.insertSelective(smsRecord);
					
					//查询返回值状态
					String result = SmsUtil.StatusReportPost(msgid);
					SmsSendState sss = new SmsSendState();
					sss.setMsgid(msgid);
					sss.setCreateDate(new Date());
					sss.setContents(result);
					smsSendStateService.insertSelective(sss);
					
					json.element("status", "0");
					json.element("message", "发送成功");
				}else {
					json.element("status", "3");
					json.element("message", "校验失败");
				}
			}
		} catch (Exception e) {
			json.element("status", SmsConst.ERROR);
			json.element("message", "发送异常");
			e.printStackTrace();
		}
		Util.json(response, json.toString());
	}

	/**
	 * 添加用户
	 */
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@RequestMapping(value="addSmsUserGet")
	public String addSmsUserGet(Model model){
		List<SysDictionary> constList =  sysDictionaryService.selectByEnabledNamespace(SmsConst.SMS_DEPARTMENT);
		model.addAttribute("constList", constList);
		if(!model.containsAttribute("smsUser"))
			model.addAttribute("smsUser", new SmsUser());
		return "sms/addSmsUserList";
	}
	
	/**
	 * 将用户信息保存入数据库
	 * 
	 */
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@Transactional(value="txManager")
	@RequestMapping(value="addSmsUser" , method = RequestMethod.POST)
	public String addSmsUser(@Validated @ModelAttribute("smsUser") SmsUser smsUser,BindingResult result,
			Model model,HttpServletRequest request){
		String phoen = smsUser.getPhoen();
		//查询号码是否已经存在
		int count = smsUserService.selectSmsUserCountByPhoen(phoen);
		if(count > 0){
			result.addError(new FieldError("smsUser", "phoen","该"+ phoen+" 号码已存在"));
			return addSmsUserGet(model);
		}
		SysUser sysUser = Util.getUserSession(request);
		smsUser.setCreateDate(new Date());
		smsUser.setUserid(sysUser.getUserid());
		smsUserService.insertSelective(smsUser);
		 
		return "redirect:/sms/sendSmsList";
	}
	
	/**
	 * 编辑用户
	 * @param request
	 * @param model
	 * @return
	 */
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@RequestMapping(value="updateSmsUser")
	public String updateSmsUser(HttpServletRequest request,Model model){
		List<SysDictionary> constList =  sysDictionaryService.selectByEnabledNamespace(SmsConst.SMS_DEPARTMENT);
		String smsUserId= request.getParameter("smsuserId");
		SmsUser smsUser = smsUserService.selectSmsUserByUserId(Integer.valueOf(smsUserId));
		model.addAttribute("constList", constList);
		model.addAttribute("SmsUser", smsUser);
		return "sms/updateSmsUser";
	}
	/**
	 * 编辑信息，保存到数据库
	 * @param smsUser
	 * @param result
	 * @param request
	 * @return
	 */
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@RequestMapping(value="updateSmsUserSave")
	public String updateSmsUserSave(@Validated @ModelAttribute("smsUser") SmsUser smsUser,BindingResult result,
			HttpServletRequest request){
		SysUser sysUser = Util.getUserSession(request);
		smsUser.setCreateDate(new Date());
		smsUser.setUserid(sysUser.getUserid());
		smsUserService.updateSmsUserSave(smsUser);
		return "redirect:/sms/sendSmsList";
	}
	/**
	 * 删除用户
	 * @param smsuserIds
	 * @return
	 */
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@Transactional(value="txManager")
	@RequestMapping(value="deleteSmsUser")
	public Map<String,Object> deleteSmsUser(@RequestParam("smsuserIds") String smsuserIds){
		Map<String,Object> map = new HashMap<String, Object>();
		String[] suIds = smsuserIds.split(",");
		for (String suId : suIds) {
			int count = smsUserService.deleteByPrimaryKey(Integer.valueOf(suId));
			if(count == 1){
				map.put("status", SmsConst.SUCCESS);
				map.put("message", "删除成功");
			}else{
				map.put("status", SmsConst.FAILURE);
				map.put("message", "删除失败");
			}
		}
		return map;
	}
	

	/**
	 * 进入导入用户页面
	 * @param model
	 * @return
	 */
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@RequestMapping(value="smsUserImport", method = RequestMethod.GET)
	public String smsUserImport(Model model){
		List<SysDictionary> constList =  sysDictionaryService.selectByEnabledNamespace(SmsConst.SMS_DEPARTMENT);
		model.addAttribute("constList", constList);
		return "sms/smsUserImport";
	}
	/**
	 * 解析用户
	 * @return
	 * @throws IOException 
	 */
	@ResponseBody
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@RequestMapping(value="upload", method = RequestMethod.POST)
	public Map<String, Object> upload(MultipartHttpServletRequest request, HttpSession session) throws IOException{
		//获取部门分组
		final String classify = request.getParameter("classify");
		final SysUser user = Util.getUserSession(request);
		@SuppressWarnings("deprecation")
		String path = request.getRealPath("/upload");
		File dir = new File(path);
		if (!dir.exists())
			dir.mkdirs();
		
		UploadProcess process = new UploadProcess() {
			@Override
			public int doProcess(UploadService service,
					ExcelParserImpl excelParser) throws Exception {
				if (excelParser.getRow() < 2) {
					throw new Exception("表格为空！");
				}
				//验证规则
				//姓名不等于null
				ValidationRule rule1 = new ValidationRule("not null", new Integer[]{0,1});
				//电话号码必须是数字							
				//RegexValidation regex2 = new RegexValidation("^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$", "“手机号码”列格式填写错误！");
				//ValidationRule rule2 = new ValidationRule("not null", new Integer[]{1});
				
				List<List<String>> buildList = excelParser.build(rule1);
				if(excelParser.getBuildMessage().length() != 0) {
					return 0;
				}
				int count = 0;
				for(int i =0;i<buildList.size();i++){
					List<String> list = buildList.get(i);
					SmsUser smsUser = new SmsUser();
					smsUser.setName(list.get(0).toString());
					smsUser.setPhoen(list.get(1).toString());
					smsUser.setClassify(classify);
					smsUser.setCreateDate(new Date());
					smsUser.setUserid(user.getUserid());
					
					count += service.addsmsUser(smsUser);
				}
				return count;
			}
		};
		Iterator<String> itr = request.getFileNames();
		MultipartFile mpf = null;
		while (itr.hasNext()) {
			mpf = request.getFile(itr.next());
			String fileName = mpf.getOriginalFilename();
			String suffix = fileName.substring(fileName.lastIndexOf("."));
			long time = new Date().getTime();
			File file = new File(path, time+suffix);
			mpf.transferTo(file);
			return this.uploadExcel(file, process);
		}
		return null;
	}
	
	public Map<String, Object> uploadExcel(File upload, UploadProcess process){
		return this.uploadExcel(upload, 0, process);
	}
	
	public Map<String, Object> uploadExcel(File upload, int index, UploadProcess process){
		Map<String, Object> map = new HashMap<String, Object>();
		ExcelParserImpl excelParser = new ExcelParserImpl(upload);
		try {
			excelParser.parse(index);
		} catch (ExcelParseException e) {
			e.printStackTrace();
			map.put("status", SmsConst.FAILURE);
			map.put("message", "表格读取异常");
			return map;
		}
		try {
			int count = process.doProcess(uploadService, excelParser);
			if(excelParser.getBuildMessage().length() != 0) {
				map.put("status", SmsConst.FAILURE);
				map.put("message", excelParser.getBuildMessage().toString());
				return map;
			} else {
				map.put("status", SmsConst.SUCCESS);
				map.put("message", "成功导入" + count + "条信息！");
				return map;
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("status", SmsConst.FAILURE);
			map.put("message", e.getMessage());
			return map;
		}
	}
	 
	/**
	 * 进入历史记录页
	 * @param model
	 * @return
	 */
	@RoleLimit(pid = "sms", mid = "sendHistoryList")
	@RequestMapping(value="sendHistoryList")
	public String sendHistory(Model model){
		return "sms/sendHistoryList";
	}
	
	/**
	 * 加载历史记录数据
	 * @param request
	 * @param model
	 * @param smsUser
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@RequestMapping(value="HistoryInItDataList")
	public String HistoryInItDataList(Model model,SmsRecord smsRecord, Integer pageNo, Integer pageSize){
		PagedResult<SmsRecord> smsRecordList = smsRecordService.selectSmsRecord(smsRecord,pageNo,pageSize);
		model.addAttribute("list", smsRecordList);
		return "sms/historyDataList";
	}
	
	/**
	 * 查询上行数据，进入上行信息记录页
	 * @param model
	 * @return
	 */
	@RoleLimit(pid="sms" , mid = "upMessageList")
	@RequestMapping(value="upMessageList")
	public String upMessage(Model model){
		//查询上行数据，并写入数据库
		try {
			List<String> list = SmsUtil.MongateCsGetSmsExExPost();
			SmsUpMessage smsUpMessage = null;
			for (String string : list) {
				 String[] resuleArray = string.split(",");
				 smsUpMessage = new SmsUpMessage();
				 smsUpMessage.setDateTime(resuleArray[0]+" "+resuleArray[1]);
				 smsUpMessage.setPhoen(resuleArray[2]);
				 smsUpMessage.setUpGallery(resuleArray[3]);
				 smsUpMessage.setUpGalleryChild(resuleArray[4]);
				 smsUpMessage.setContent(resuleArray[5]);
				 smsUpMessageService.insertSelective(smsUpMessage);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "sms/upMessageList";
	}
	
	/**
	 * 加载上行信息记录
	 * @param model
	 * @param smsRecord
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID , mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@RequestMapping(value="upMessageInItDataList")
	public String upMessageInItDataList(Model model,SmsUpMessage smsUpMessage, Integer pageNo, Integer pageSize){
		PagedResult<SmsUpMessage> smsUpMessageList = smsUpMessageService.selectsmsUpMessage(smsUpMessage,pageNo,pageSize);
		model.addAttribute("list", smsUpMessageList);
		return "sms/upMessageDataList";
	}
	
}
