/**
 * Description: CmLotteryRule控制器
 * Copyright:   Copyright (c)2015
 * Company:     江苏三六五网络股份有限公司
 * @author:     江苏三六五网络股份有限公司
 * @version:    1.0
 * Create at:   2015-08-19 上午 11:24:24
 *  
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2015-08-19   江苏三六五网络股份有限公司   1.0         Initial
 */
package com.house365.web.controller;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import com.house365.beans.entity.CmLotteryRuleEntity;
import com.house365.beans.system.Page;
import com.house365.beans.vo.CmLotteryRuleVo;
import com.house365.rest.context.CmConstant;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.StringUtils;
import com.house365.ws.beans.request.CmLotteryRuleListRequest;
import com.house365.ws.beans.request.CmLotteryRuleRequest;
import com.house365.ws.beans.response.CmLotteryRuleListResponse;
import com.house365.ws.beans.response.CmLotteryRuleResponse;
import com.house365.ws.interfaces.server.ICmLotteryRule;

/**
 * CmLotteryRule控制器<br>
 * 
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2015-08-19
 * @see
 * @since 1.0
 */
@Controller
@RequestMapping("/cmlotteryrule")
public class CmLotteryRuleController extends BaseController {

	/**
	 * 自动注入CmLotteryRuleWS实现
	 */
	@Autowired
	private ICmLotteryRule cmLotteryRule;

	/**
	 * 去新增CmLotteryRule
	 * 
	 * @return 结果视图
	 */
	@RequestMapping(value = "", params = "action=create")
	public String createForm(Model model){
		model.addAttribute("action", "create");
		return getAutoUrl("form");
	}

	/**
	 * 新增CmLotteryRule
	 * 
	 * @param cmLotteryRule CmLotteryRule页面表单对象
	 * @param result 表单验证数据
	 * @param page 分页配置
	 * @param request 请求对象
	 * @return 结果视图
	 */
	@RequestMapping(value = "", method = { RequestMethod.POST})
	public String createCmLotteryRule(@Valid CmLotteryRuleVo vo, BindingResult result, RedirectAttributes redirectAttributes, Model model, HttpSession session){
		CmLotteryRuleEntity entity = vo.getEntity();
		String cityKey = String.valueOf(session.getAttribute(CmConstant.CITY_KEY));
		String cityName = String.valueOf(session.getAttribute(CmConstant.CITY_NAME));
		//entity.setCityId(Integer.parseInt(cityKey));
		entity.setCityKey(cityKey);
		entity.setCityName(cityName);
		entity.setCreateTime(new Date());
		entity.setUpdateTime(new Date());
		model.addAttribute("entity", entity);
		// subValidation(result, entity);
		// 表单验证无误,进行提交
		if (result.hasErrors()) {
		    model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
		} else {
		    try {
                CmLotteryRuleRequest request = new CmLotteryRuleRequest();
                request.setEntity(entity);
                CmLotteryRuleResponse response = cmLotteryRule
                        .addCmLotteryRule(request);
                Integer id = response.getEntity().getId();
                return "redirect:/cmlotteryrule/" + id;
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "create");
                return getAutoUrl("form");
            }
		}
	}

	/**
	 * 删除CmLotteryRule
	 * 
	 * @param id CmLotteryRule页面表单对象唯一标识
	 * @param page 分页配置
	 * @param request 请求对象
	 * @return 结果视图
	 */
	@RequestMapping(value = "/{id}", method = { RequestMethod.DELETE })
	@ResponseStatus(HttpStatus.OK)
	public void delete(@PathVariable String id){
	    if(!StringUtils.isEmpty(id))
        {
            if(id.contains(","))
            {
                String[] ids = id.split(",");
                for (int i = 0; i < ids.length; i++) {
                    CmLotteryRuleResponse response = cmLotteryRule.deleteCmLotteryRuleById(Integer.valueOf(ids[i]));
                }
            }
            else
            {
                CmLotteryRuleResponse response = cmLotteryRule.deleteCmLotteryRuleById(Integer.valueOf(id));
            }
        }
	}

	/**
	 * 去查看CmLotteryRule
	 * 
	 * @param id
	 *            CmLotteryRule页面表单对象唯一标识
	 * @param request
	 *            请求对象
	 * @return 结果视图
	 */
	@RequestMapping(value = "/{id}", method = { RequestMethod.GET })
	public String showForm(@PathVariable(value = "id") Integer id, Model model) {
        CmLotteryRuleResponse response = cmLotteryRule
                .getCmLotteryRuleById(id);
        model.addAttribute("entity", response.getEntity());
        return getAutoUrl("form");
	}

	/**
	 * 去修改CmLotteryRule
	 * 
	 * @param id CmLotteryRule页面表单对象唯一标识
	 * @param request 请求对象
	 * @return 结果视图
	 */
	@RequestMapping(value = "/{id}", method = { RequestMethod.GET}, params = "action=edit")
	public String updateForm(@PathVariable(value = "id") Integer id, Model model){
        CmLotteryRuleResponse response = cmLotteryRule.getCmLotteryRuleById(id);
        
        model.addAttribute("entity", response.getEntity());
		model.addAttribute("action", "edit");
		return getAutoUrl("form");
	}

	/**
	 * 修改CmLotteryRule
	 * 
	 * @param cmLotteryRule CmLotteryRule页面表单对象
	 * @param result 表单验证数据
	 * @param page 分页配置
	 * @param request 请求对象
	 * @return 结果视图
	 */
	@RequestMapping(value = "/{id}", method = { RequestMethod.POST})
	public String updateCmLotteryRule(@Valid CmLotteryRuleVo vo, BindingResult result, @PathVariable Integer id, RedirectAttributes redirectAttributes, Model model){
		CmLotteryRuleEntity entity = vo.getEntity();
		model.addAttribute("entity", entity);
		CmLotteryRuleResponse response = cmLotteryRule.getCmLotteryRuleById(entity.getId());
		CmLotteryRuleEntity oldEntity = response.getEntity();
		Integer oldOrderNumber = oldEntity.getOrderNumber();
		
		oldEntity.setUpdateTime(new Date());
		oldEntity.setProbability(entity.getProbability());
		oldEntity.setCredits(entity.getCredits());
		oldEntity.setOrderNumber(entity.getOrderNumber());
		oldEntity.setCreditRuleName(entity.getCreditRuleName());
		if(oldOrderNumber!=entity.getOrderNumber()){
    		Page page = new Page(999999);
            page.setCurrentPage(0);
            CmLotteryRuleListRequest listRequest = new CmLotteryRuleListRequest();
            listRequest.setPaging(page);
            CmLotteryRuleListResponse responseList = cmLotteryRule.getCmLotteryRuleList(listRequest);
            for(CmLotteryRuleEntity aentity:responseList.getObjectList()){
                 if(oldEntity.getOrderNumber() == aentity.getOrderNumber()){
                     addErrorMessage(model, "排序序号重复，请更换！");
                     model.addAttribute("action", "edit");
                     return getAutoUrl("form");
                 }
            }
		}
		
		// subValidation(result, entity);
		// 表单验证无误,进行提交
		if (result.hasErrors()) {
		    model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
		} else {
            try {
                CmLotteryRuleRequest request = new CmLotteryRuleRequest();
                request.setEntity(oldEntity);
                @SuppressWarnings("unused")
                CmLotteryRuleResponse rersponse = cmLotteryRule
                        .updateCmLotteryRule(request);
                redirectAttributes.addAttribute("message", "更新成功");
                return "redirect:/cmlotteryrule/" + entity.getId();
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "edit");
                return getAutoUrl("form");
            }
		}
	}

	/**
	 * 查询CmLotteryRule
	 * 
	 * @param cmLotteryRule CmLotteryRule页面表单对象
	 * @param page 分页配置
	 * @param request 请求对象
	 * @return 结果视图
	 */
	@RequestMapping(value = "", method = RequestMethod.GET)
	public String list (Integer number, Model model, HttpServletRequest request) {
		// 获取查询条件
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(
				request, "search_");
		Page page = new Page(Page.TWENTY_PAGE_SIZE);
		if (null != number) {
			page.setCurrentPage(number);
		}
		CmLotteryRuleListRequest listRequest = new CmLotteryRuleListRequest();
        listRequest.setPaging(page);
        //listRequest.setSearchParams(searchParams);
        CmLotteryRuleListResponse response = cmLotteryRule.getCmLotteryRuleList(listRequest);
        model.addAttribute("page", response.getPaging());
        model.addAttribute("cmLotteryRules", response.getObjectList());
        model.addAttribute("searchParams", Servlets
                .encodeParameterStringWithPrefix(searchParams, "search_"));
		return getAutoUrl();
	}
}
