package com.blueland.bpm.manage.web;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.blueland.bpm.application.model.ApplicationEntity;
import com.blueland.bpm.application.service.ApplicationManager;
import com.blueland.bpm.common.base.BaseSpringController;
import com.blueland.bpm.common.page.Page;
import com.blueland.bpm.common.util.HttpUtils;
import com.blueland.bpm.engine.config.model.SmsConfig;
import com.blueland.bpm.engine.config.service.SmsConfigService;
import com.blueland.bpm.identity.UserService;
import com.blueland.bpm.identity.model.User;
/**
 * @author lw
 * @version 1.0
 * @since  
 */
 
import java.util.*;

@Controller
@RequestMapping(value = "smsConfig")
public class SmsConfigController extends BaseSpringController{
	//默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = null; 
	@Autowired
	private SmsConfigService smsConfigService;
	@Autowired
	private UserService userService;
	@Autowired
	private ApplicationManager applicationManager;
	
	private final String LIST_ACTION = "redirect:/smsConfig/list.do";
	/**
	 * 日志 服务
	 */
	protected Logger logger = LoggerFactory.getLogger(getClass());
	public SmsConfigController() {
	}
	

	/**
	 * 增加了@ModelAttribute的方法可以在本controller的方法调用前执行,可以存放一些共享变量,如枚举值
	 */
	@ModelAttribute
	public void init(ModelMap model) {
		//model.put("now", new java.sql.Timestamp(System.currentTimeMillis()));
	}
	
	/** 
	 * 执行搜索 
	 **/
	@RequestMapping(value = "list")
	public ModelAndView list(SmsConfig query,HttpServletRequest request) {
		Page page = this.smsConfigService.findPage(query);
		ModelAndView result = new ModelAndView("/smsConfig/list");
		result.addAllObjects(toModelMap(page, query));
		return result;
	}
	
	/** 
	 * 查看对象
	 **/
	@RequestMapping(value = "show")
	public ModelAndView show(String smsid,HttpServletRequest request)  {
		SmsConfig smsConfig = (SmsConfig)smsConfigService.getById(smsid);
		return new ModelAndView("/smsConfig/show","smsConfig",smsConfig);
	}
	
	/** 
	 * 进入新增页面
	 **/
	@RequestMapping(value = "create")
	public ModelAndView create(SmsConfig smsConfig,HttpServletRequest request)  {
		String userId = request.getParameter("userId");
		User user = userService.getUserByCode(userId);
		smsConfig.setMobile(user.getUserMobile());
		ApplicationEntity application = new ApplicationEntity();
		application.setAppTypes("('task')");
		List<ApplicationEntity> appList = applicationManager.findByExample(application);
		smsConfig.setAppList(appList);
		return new ModelAndView("/smsConfig/create","smsConfig",smsConfig);
	}
	/** 
	 * 进入新增页面
	 **/
	@RequestMapping(value = "backCreate")
	public ModelAndView backCreate(HttpServletRequest request,SmsConfig smsConfig,String userId){
		ModelAndView result = new ModelAndView("/smsConfig/create");
		User user = userService.getUserByCode(userId);
		smsConfig.setMobile(user.getUserMobile());
		ApplicationEntity application = new ApplicationEntity();
		application.setAppTypes("('task')");
		List<ApplicationEntity> appList = applicationManager.findByExample(application);
		smsConfig.setAppList(appList);
		List<SmsConfig> SmsConfigList = smsConfigService.findByExample(smsConfig);
		String apps = "";
		Integer existApp = 0;
		for(SmsConfig exsitSmsConfig:SmsConfigList){
			if(StringUtils.isEmpty(apps)){
				apps = exsitSmsConfig.getAppEname()+",";				
			}else{
				apps = apps+exsitSmsConfig.getAppEname()+",";
			}
			existApp++;
			smsConfig.setWeekday(exsitSmsConfig.getWeekday());
			if(StringUtils.isNotEmpty(exsitSmsConfig.getTimezone())){
				smsConfig.setTimeStart(exsitSmsConfig.getTimezone().split("-")[0]);
				smsConfig.setTimeEnd(exsitSmsConfig.getTimezone().split("-")[1]);
			}
		}
		result.addObject("apps", apps);
		result.addObject("smsConfig",smsConfig);
		result.addObject("existApp", existApp);
		return result;
	}
	/** 
	 * 保存新增对象
	 **/
	@RequestMapping(value = "save")
	@ResponseBody
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	public Map save(SmsConfig smsConfig,HttpServletRequest request,RedirectAttributes redirectAttributes)  {
		Map result = new HashMap();
		result.put("success",true);	
		List<String> appNameList = smsConfig.getAppNameList(); 
		
		if(StringUtils.isNotEmpty(smsConfig.getWeekday()) && StringUtils.isNotEmpty(smsConfig.getTimezone())
				&& appNameList.size()>0){
			SmsConfig existSmsConfig = new SmsConfig();
			existSmsConfig.setUserId(smsConfig.getUserId());
			smsConfigService.delete(existSmsConfig);	
			logger.info(String.format("删除用户的短信设置，用户：[%s]",
					existSmsConfig.getUserId()));
			for(String appName :appNameList){
				try{					
					if(StringUtils.isNotEmpty(appName)){
						smsConfig.setAppEname(appName);	
						smsConfigService.save(smsConfig);
						logger.info(String.format("开始保存短信配置，用户：[%s]，时间段:[%s]，星期几：[%s]，系统简写：[%s]，流程定义id[%s]",
								smsConfig.getUserId(),smsConfig.getTimezone(),smsConfig.getWeekday(),smsConfig.getAppEname(),
								smsConfig.getProcessDefId()));
												
					}	
				}catch(Exception e){
					logger.error(String.format("短信配置失败，用户：[%s]，时间段:[%s]，星期几：[%s]，系统简写：[%s]，流程定义id[%s]",smsConfig.getUserId(),
							smsConfig.getTimezone(),smsConfig.getWeekday(),smsConfig.getAppEname(),smsConfig.getProcessDefId()),e);
					result.put("success",false);
				}
							
			}	
			logger.info(String.format("用户[%s]的短信配置保存完毕！",smsConfig.getUserId()));
		}
		
		
		return result;
	}
	
	/**
	 * 进入更新页面
	 **/
	@RequestMapping(value = "edit")
	public ModelAndView edit(String smsid,HttpServletRequest request)  {
		SmsConfig smsConfig = (SmsConfig)smsConfigService.getById(smsid);
		return new ModelAndView("/smsConfig/edit","smsConfig",smsConfig);
	}
	
	/**
	 * 保存更新对象
	 **/
	@RequestMapping(value = "update")
	public ModelAndView update(SmsConfig smsConfig,HttpServletRequest request,RedirectAttributes redirectAttributes)  {
		String id = request.getParameter("smsid");
		smsConfigService.update(smsConfig);
		redirectAttributes.addFlashAttribute(ACTION_MESSAGE, UPDATE_SUCCESS);
		return new ModelAndView(LIST_ACTION);
	}
	
	/**
	 *删除对象
	 **/
	@RequestMapping(value = "delete")
	public ModelAndView delete(HttpServletRequest request,RedirectAttributes redirectAttributes) {
		String[] items = request.getParameterValues("items");
		for(int i = 0; i < items.length; i++) {
			Hashtable params = HttpUtils.parseQueryString(items[i]);
			String id = new String((String)params.get("smsId"));
			smsConfigService.removeById(id);
		}
		redirectAttributes.addFlashAttribute(ACTION_MESSAGE, DELETE_SUCCESS);
		return new ModelAndView(LIST_ACTION);
	}
	
}

