package com.qiankun.controller;
 
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

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

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
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.servlet.ModelAndView;

import com.google.common.collect.Maps;
import com.qiankun.annotation.Auth;
import com.qiankun.controller.base.BaseController;
import com.qiankun.dao.core.Hints;
import com.qiankun.entity.Activity;
import com.qiankun.entity.ActivityReg;
import com.qiankun.entity.ActivityType;
import com.qiankun.pages.IPageList;
import com.qiankun.pages.PageListImpl;
import com.qiankun.service.ActivityService;
import com.qiankun.vo.ActivityRegVo;
import com.qiankun.vo.ActivityVo;
 
@Controller
public class ActivityController extends BaseController<Object>{
 
	@Autowired
	private ActivityService activityService;
	
	private ResourceBundle rb = ResourceBundle.getBundle("system");
	private String activityImagePath = File.separator + rb.getString("activityImage");
	
	@Auth(verifyLogin = false,verifyURL = false)
	@RequestMapping(value = "/wx/api/activity/list", method = RequestMethod.POST)
    public @ResponseBody Map<String, Object> listformWX(@RequestBody ActivityVo activityVo, HttpServletResponse response, HttpServletRequest request) throws Exception {
        IPageList<Activity> userPage = activityService.findByActivitys(activityVo.getSearchStr(), activityVo.getType(), activityVo.getOrder(), activityVo.getSort(), 
					new Hints(getStartRow(request), getPageCount(request)));
        Map<String, Object> map = new HashMap<>();
        map.put("activityData", userPage);
        map.put("pageCount", getPageCount(request));
        map.put("pageNumber", getPageNumber(request));
        map.put("activityVo", activityVo);
        return map;
    }
	
	@Auth(verifyLogin = false,verifyURL = false)
	@RequestMapping(value = "/wx/api/activity", method = RequestMethod.POST)
    public @ResponseBody Map<String,Object> entityformWX(@RequestBody ActivityVo activityVo, HttpServletResponse response, HttpServletRequest request) throws Exception {
        Map<String,Object> result = Maps.newHashMap();
	    Activity activity = activityService.findById(activityVo.getId());
	    result.put("status","ok");
	    result.put("activity",activity);
	    result.put("activityRegCount",activity.getActivityReg().size());
        Iterator<ActivityReg> it = activity.getActivityReg().iterator();
        boolean currentUserApplyed = false;//当前用户是否报名
        ActivityReg rtReg = null;
        while (it.hasNext()){
            ActivityReg reg = it.next();
            if (reg.getUser().getId().equals(activityVo.getUserId())){
                currentUserApplyed = true;
                rtReg = reg;
                break;
            }
        }
        result.put("currentUserApplyed",currentUserApplyed);
        result.put("activityReg",rtReg);
        return result;
    }
	
	@Auth(verifyLogin = false,verifyURL = false)
	@RequestMapping(value = "/wx/api/activity/type/list", method = RequestMethod.GET)
    public @ResponseBody List<ActivityType> typesformWX(HttpServletResponse response, HttpServletRequest request) throws Exception {  
        return activityService.findActivitysTypes();
    }
	
	
    
    @RequestMapping("/activity/list")
    public ModelAndView list(ActivityVo activityVo, HttpServletResponse response, HttpServletRequest request) throws Exception {
        ModelAndView view = new ModelAndView();
        IPageList<Activity> page = activityService.findByActivitys(activityVo.getSearchStr(), activityVo.getType(), activityVo.getOrder(), activityVo.getSort(), 
					new Hints(getStartRow(request), getPageCount(request)));
        
        IPageList<ActivityVo> activityPage = new PageListImpl<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        List<ActivityVo> records = new ArrayList<>();
        for (Activity a : page.getRecords()) {
        	ActivityVo vo = new ActivityVo();
        	vo.setAddr(a.getAddr());
        	vo.setAvailable(a.isAvailable());
        	vo.setName(a.getName());
        	vo.setContacts(a.getContacts());
        	vo.setContent(a.getContent());
        	vo.setCrowd(a.getCrowd());
        	vo.setCreateTime(a.getCreateTime());
        	vo.setDay(sdf.format(a.getDay()));
        	vo.setId(a.getId());
        	vo.setMax(a.getMax());
        	vo.setTel(a.getTel());
        	vo.setType(a.getType());
        	vo.setUploadImage(a.getUploadImage());
//        	List<ActivityReg> list = new ArrayList<>();
//        	if (a.getActivityReg()!=null) {
//        		Iterator<ActivityReg> its = a.getActivityReg().iterator();
//        		while(its.hasNext()) {
//        			ActivityReg reg = its.next();
//        			list.add(reg);
//        		}
//        	}
//        	vo.setActivityReg(list);
        	vo.setRegCount(a.getActivityReg().size());
        	records.add(vo);
        }
        activityPage.setRecords(records);
        activityPage.setRecordTotal(page.getRecordTotal());
			
		view.getModelMap().addAttribute("activityPage", activityPage);
		view.getModelMap().addAttribute("pageCount", getPageCount(request));
		view.getModelMap().addAttribute("pageNumber", getPageNumber(request));
		view.getModelMap().addAttribute("activityVo", activityVo);
		
		
        view.setViewName("activity/activitylist");
        return view;
    }
    
    
    @RequestMapping("/activity/type/list")
    public ModelAndView typelist(HttpServletResponse response, HttpServletRequest request) throws Exception {
        ModelAndView view = new ModelAndView();			
		view.getModelMap().addAttribute("typelist", activityService.findActivitysTypes());
        view.setViewName("activity/typelist");
        return view;
    }
    
    @RequestMapping("/activity/type/add")
    public ModelAndView typeAdd(String id) throws Exception {
        ModelAndView view = new ModelAndView();  
        Activity activity = new Activity();
        if(StringUtils.isNotBlank(id)) {
        	activity = activityService.findById(id);      
        }
         
        view.setViewName("activity/saveactivity");
        view.getModel().put("activity", activity);
        return view;
    }
    
    @RequestMapping("/activity/add")
    public ModelAndView activityAdd(String id) throws Exception {
        ModelAndView view = new ModelAndView();  
        Activity activity = new Activity();
        if(StringUtils.isNotBlank(id)) {
        	activity = activityService.findById(id);      
        }
         
        view.setViewName("activity/saveactivity");
        view.getModel().put("activity", activity);
        return view;
    }
    
    @RequestMapping("/api/activity/type/save")
	public void saveType(String id, String name, HttpServletResponse response, HttpServletRequest request) throws Exception {
    	ActivityType type =  new  ActivityType();
    	type.setName(name);
    	type.setId(id);
    	activityService.saveType(type);
    }
    
    
    @RequestMapping(value = "/api/activity/save", method = RequestMethod.POST)
	public Map<String, Object> save(@RequestParam(value = "file", required = false) MultipartFile file, ActivityVo activityVo, HttpServletResponse response, HttpServletRequest request) throws Exception {
	    	
	        Map<String, Object> map = new HashMap<>();
	        Activity activity = new Activity();
	    	if (StringUtils.isEmpty(activityVo.getId())) {
	    		Date date = new Date();	
	    		activity.setCreateTime(date);
	    		map.put("status", 1);
	    	} else {
	    		activity = activityService.findById(activityVo.getId());
	    		map.put("status", 2);
	    	}
	    	
	    	if (file != null) {
	        	String fileFullName = file.getOriginalFilename();
	        	String[] originalFileName = fileFullName.split("\\.");
	        	String fileName = System.currentTimeMillis() + "." + originalFileName[originalFileName.length-1];
	            String rootPath = rb.getString("file_path");
	            if (StringUtils.isNotBlank(activity.getUploadImage())) {
	            	File oldFile =  new File(rootPath + activity.getUploadImage());
	            	if (oldFile.isFile())
	            		FileUtils.forceDelete(oldFile);
	            }
	            
	            File destFile = new File(rootPath + activityImagePath,fileName);
	            FileUtils.writeByteArrayToFile(destFile,file.getBytes());
	            activity.setUploadImage(activityImagePath + File.separator + fileName);
	        }
	    	
	    	
	    	
	    	
	    	activity.setAddr(activityVo.getAddr());
	    	activity.setAvailable(activityVo.getAvailable());
	    	activity.setContacts(activityVo.getContacts());
	    	activity.setContent(activityVo.getContent());
	    	activity.setCrowd(activityVo.getCrowd());
	    	
	    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	    	activity.setDay(sdf.parse(activityVo.getDay()));
	    	activity.setMax(activityVo.getMax());
	    	activity.setName(activityVo.getName());
	    	activity.setTel(activityVo.getTel());
	    	activity.setType(activityVo.getType());
	    	
	    	Activity a = activityService.save(activity);
	    	
	    	map.put("activity", a);
	    	return map;
	    	
	}

    
    
    @RequestMapping("/api/activity/del")    
    public ModelAndView delActivity(ActivityVo activityVo,  HttpServletResponse response, HttpServletRequest request) throws Exception {
    	ModelAndView view = new ModelAndView();
    	activityService.remove(activityVo.getId());
    	return view;
    }
    
    
    
    
    @RequestMapping("/activity/reg/list")
    public ModelAndView activityReglist(ActivityRegVo vo, HttpServletResponse response, HttpServletRequest request) throws Exception {
        ModelAndView view = new ModelAndView();
        if (StringUtils.isNotBlank(vo.getActivityId())) {
        	Activity activity =  activityService.findById(vo.getActivityId());
            IPageList<ActivityReg> regPage = activityService.findActivityRegPage(vo.getSearchStr(), vo.getActivityId(), vo.getOrder(), vo.getSort(), 
    					new Hints(getStartRow(request), getPageCount(request)));
    	
    		view.getModelMap().addAttribute("regPage", regPage);
    		view.getModelMap().addAttribute("pageCount", getPageCount(request));
    		view.getModelMap().addAttribute("pageNumber", getPageNumber(request));
    		view.getModelMap().addAttribute("ActivityRegVo", vo);
    		view.getModelMap().addAttribute("activity", activity);
        }
        

        view.setViewName("activity/activityreglist");
        return view;
    }
    
    @RequestMapping("/api/activity/reg/del")    
    public ModelAndView delActivityReg(ActivityRegVo vo,  HttpServletResponse response, HttpServletRequest request) throws Exception {
    	ModelAndView view = new ModelAndView();
    	if (StringUtils.isNotBlank(vo.getId())) {
    		activityService.removeReg(vo.getId());    
    		return view;
    	} 

    	if (StringUtils.isNotBlank(vo.getActivityId())) {
    		activityService.removeRegAll(vo.getActivityId());
    		return view;
    	}
    	return view;
    }

}