/**
 * Company Name : 中贸促信息技术有限责任公司
 * Project Name:memberManageSys
 * File Name:RegisterController.java
 * Package Name:org.ccpit.business.registerManage
 * Date:2015年11月10日上午10:15:16
 * Copyright (c) 2015, dingwei@ccpit.org All Rights Reserved.
 */

package org.ccpit.business.registerManage;

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

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

import org.apache.commons.lang.StringUtils;
import org.ccpit.base.controller.BaseController;
import org.ccpit.base.controller.Page;
import org.ccpit.base.controller.PageRequest;
import org.ccpit.base.metadataManage.MetadataService;
import org.ccpit.base.user.User;
import org.ccpit.business.phase.Phase;
import org.ccpit.business.phase.PhaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;

/**
 * ClassName:RegisterController <br/>
 * Function: TODO 报名信息. <br/>
 * Reason:	 TODO ADD REASON. <br/>
 * Date:     2015年11月10日 上午10:15:16 <br/>
 *
 * @author sunqipeng
 * @see
 * @since JDK 1.6
 */
@RestController
@RequestMapping("/admin/business/registerManage")
public class RegisterController extends BaseController {

    @Autowired
    private RegisterService registerService;
    @Autowired
    private MetadataService metadataService;
    @Autowired
    private PhaseService phaseService;
    @Autowired
    private SubjectInfoService subjectInfoService;

    /*
     *
     */
    @RequestMapping("/goinRegisterInfoListPage")
    public Object goinNewsListPage() {
        ModelAndView mv = new ModelAndView("business/registerInfoListPage");
        mv.addObject("status", JSON.toJSON(metadataService.getMetadatasByType2("status")));
        mv.addObject("subject", JSON.toJSON(metadataService.getMetadatasByType2("subject")));
        mv.addObject("phases", JSON.toJSON(phaseService.queryAll()));
        return mv;
    }				  
    @RequestMapping("/goinRegisterInfoExtListPage")
    public Object goinRegisterInfoExtListPage() {
        ModelAndView mv = new ModelAndView("business/registerInfoListExtPage");
        mv.addObject("subject2", JSON.toJSON(metadataService.getMetadatasByType2("subject2")));
        mv.addObject("status2", JSON.toJSON(metadataService.getMetadatasByType2("status2")));
        mv.addObject("phases", JSON.toJSON(phaseService.queryAll()));
        return mv;
    }

    @RequestMapping("/addOrUpdateRegisterInfo")
    public Object addOrUpdateRegisterInfo(HttpServletRequest request,RegisterInfo registerInfo,String operate,HttpServletResponse response) {
        boolean success = false;
        if (StringUtils.isNotEmpty(operate)&&operate.equals("add")){
            registerInfo.setCreator(getUserSession(request));
            String flagExt = request.getParameter("flagExt");
            if (flagExt!=null&&flagExt.equals("0"))//如果是延考则在新增数据时把regType设为false表示延考或恢复
            	registerInfo.setRegType(false);
            registerInfo.setPhase(phaseService.getActivePhase());
            success = registerService.addRegisterInfo(registerInfo);
        }else if (StringUtils.isNotEmpty(operate)&&operate.equals("edit")){
            RegisterInfo reg = registerService.queryRegisterById(registerInfo.getId());
            if (reg!=null){
                String password = reg.getPassword();
                long id = reg.getId();
                Date submitTime = reg.getSubmitTime();
                boolean regType = reg.isRegType();
                User user = reg.getCreator();
                Phase phase = reg.getPhase();
                try {
                    org.springframework.beans.BeanUtils.copyProperties(registerInfo, reg);
                } catch (Exception e) {
                }
                reg.setId(id);
                reg.setPassword(password);
                reg.setCreator(user);
                reg.setSubmitTime(submitTime);
                reg.setRegType(regType);
                reg.setPhase(phase);
                success = registerService.updateRegisterInfo(reg);
            }
        }
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("flag",success);
        map.put("info",success?"保存成功":"保存失败");
        try {
            response.getWriter().print("{flag:" + success + ",info:'" + (success?"保存成功":"保存失败")+"'}");
        } catch (IOException e) {

        }
        return null;
    }

    @RequestMapping("/updateSubject")
    public Object updateSubject(HttpServletRequest request,SubjectInfo subjectInfo,HttpServletResponse response,Long id) {
        boolean success = false;
        SubjectInfo old_subjectInfo = subjectInfoService.querySubjectInfoById(id);
        if (old_subjectInfo!=null){
            old_subjectInfo.setAddressName(subjectInfo.getAddressName());
            old_subjectInfo.setAppreciationTaxType(subjectInfo.getAppreciationTaxType());
            old_subjectInfo.setBankAccount(subjectInfo.getBankAccount());
            old_subjectInfo.setBankAddress(subjectInfo.getBankAddress());
            old_subjectInfo.setInvoiceType(subjectInfo.getInvoiceType());
            old_subjectInfo.setInvoiceTitle(subjectInfo.getInvoiceTitle());
            old_subjectInfo.setModifyTime(new Date());
            old_subjectInfo.setPayTime(subjectInfo.getPayTime());
            old_subjectInfo.setRegisterStatus(subjectInfo.getRegisterStatus());
            old_subjectInfo.setRemark(subjectInfo.getRemark());
            old_subjectInfo.setSubject(subjectInfo.getSubject());
            old_subjectInfo.setTaxIssue(subjectInfo.getTaxIssue());
            old_subjectInfo.setTaxpayerNum(subjectInfo.getTaxpayerNum());
            old_subjectInfo.setTelephone(subjectInfo.getTelephone());
            success = subjectInfoService.updateSubjectInfo(old_subjectInfo);
        }
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("flag",success);
        map.put("info",success?"保存成功":"保存失败");
        try {
            response.getWriter().print("{flag:" + success + ",info:'" + (success?"保存成功":"保存失败")+"'}");
        } catch (IOException e) {

        }
        return null;
    }


    @RequestMapping("/queryAllRegisterInfo")
    public Object queryAllRegisterInfo(HttpServletRequest request,String name,String status,String status2,String subject,String subject2,Long phase) {
        PageRequest pageRequest = getPage(request);
        StringBuilder sb = new StringBuilder("from RegisterInfo where 1=1 ");
        Object p = request.getParameter("phase");
        if (StringUtils.isNotBlank(name)){
            sb.append(" and name like '%"+name+"%'");
        }
        if (StringUtils.isNotBlank(status)){
            sb.append(" and registerStatus='"+status+"'");
        }
        if (StringUtils.isNotBlank(status2)){
            sb.append(" and registerStatus2='"+status2+"'");
        }
        if (StringUtils.isNotBlank(subject)){
            sb.append(" and subject = "+subject);
        }
        if (StringUtils.isNotBlank(subject2)){
            sb.append(" and subject2 = "+subject2);
        }
        if (phase!=null &&phase!=0){
            sb.append(" and phase.id = '"+phase+"'");
        }
        String flagExt = request.getParameter("flagExt");
        if(flagExt!=null&&flagExt.equals("0")){//表示为延考或恢复状态,作为查找条件
        	sb.append(" and regType = '0' ");
        }else{
        	sb.append(" and regType = '1' ");
        }
        pageRequest.setOrderBy("submitTime desc ");
        StringBuffer hql = new StringBuffer(sb.toString());
        Page<RegisterInfo> infoPage = registerService.queryRegisterInfos(pageRequest, hql.toString());
        return infoPage;
    }

    @RequestMapping("/queryAllSubject")
    public Object queryAllSubject(HttpServletRequest request,long id) {
        PageRequest pageRequest = getPage(request);
        StringBuilder sb = new StringBuilder("from SubjectInfo where registerInfo_id =" + id);
        pageRequest.setOrderBy("submitTime desc ");
        StringBuffer hql = new StringBuffer(sb.toString());
        Page<SubjectInfo> infoPage = subjectInfoService.querySubjectInfos(pageRequest, hql.toString());
        return infoPage;
    }

    @RequestMapping("/queryRegisterInfoById")
    public RegisterInfo queryRegisterInfoById(HttpServletRequest request,HttpServletResponse response) {
        String registerInfoId = request.getParameter("registerInfo");
        response.setHeader("expires","0");
        response.setHeader("cache-control","max-age=0");
        response.setHeader("Pragma","no-cache");
        return registerService.queryRegisterById(Long.valueOf(registerInfoId));
    }

    @RequestMapping("/querySubjectById")
    public SubjectInfo query_subject_by_id(HttpServletRequest request,HttpServletResponse response,long id) {
        response.setHeader("expires","0");
        response.setHeader("cache-control","max-age=0");
        response.setHeader("Pragma","no-cache");
        return subjectInfoService.querySubjectInfoById(id);
    }

    @RequestMapping("/deleteByIds")
    public Object deleteRegisters(HttpServletRequest request){
        String ids = request.getParameter("ids");
        List<Long> list = JSON.parseArray(ids, Long.class);
        boolean success = registerService.deleteRegisterInfos(list);
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("flag",success);
        return map;
    }

    @RequestMapping("/delete_subject_ById")
    public Object delete_subject_ById(HttpServletRequest request){
        String id = request.getParameter("id");
        boolean success = subjectInfoService.deleteSubjectInfos(Long.valueOf(id));
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("flag",success);
        return map;
    }

    @RequestMapping("/updateStatus")
    public Object updateStatus(HttpServletRequest request){
    	Map<String,Object> map = new HashMap<String, Object>();
    	String ids = request.getParameter("ids");
    	int registerStatus = Integer.parseInt(request.getParameter("registerStatus"));
    	List<Long> list = JSON.parseArray(ids, Long.class);
    	if (list != null && !list.isEmpty()) {
    		for (long id : list) {
    			RegisterInfo reg = registerService.queryRegisterById(id);
    			if (reg != null) {
    				reg.setRegisterStatus(registerStatus);
    				registerService.updateRegisterInfo(reg);
    			}
    		}
    		map.put("flag",true);
    	}else{
    		map.put("flag",false);
    	}
    	return map;
    }
    
    @RequestMapping("/updateStatus2")
    public Object updateStatus2(HttpServletRequest request){
    	Map<String,Object> map = new HashMap<String, Object>();
    	String ids = request.getParameter("ids");
    	int registerStatus = Integer.parseInt(request.getParameter("registerStatus"));
    	List<Long> list = JSON.parseArray(ids, Long.class);
    	if (list != null && !list.isEmpty()) {
    		for (long id : list) {
    			RegisterInfo reg = registerService.queryRegisterById(id);
    			if (reg != null) {
    				reg.setRegisterStatus2(registerStatus);
    				registerService.updateRegisterInfo(reg);
    			}
    		}
    		map.put("flag",true);
    	}else{
    		map.put("flag",false);
    	}
    	return map;
    }
    /**
     * 导出excel
     */
    @RequestMapping("/exporgExcel2")
    public void exporgExcel2(HttpServletResponse response,
                             String name,String status,String status2,String subject,String subject2,Long phase,String fields,String flagExt,Long bigger) {

        StringBuilder sb = new StringBuilder("from RegisterInfo where 1=1 ");
        if (StringUtils.isNotBlank(name)){
            sb.append(" and name like '%"+name+"%'");
        }
        if (StringUtils.isNotBlank(status)){
            sb.append(" and registerStatus='"+status+"'");
        }
        if (StringUtils.isNotBlank(status2)){
            sb.append(" and registerStatus2='"+status2+"'");
        }
        if (StringUtils.isNotBlank(subject)){
            sb.append(" and subject = "+subject);
        }
        if (StringUtils.isNotBlank(subject2)){
            sb.append(" and subject2 = "+subject2);
        }
        if (phase!=null &&phase!=0){
            sb.append(" and phase.id = '"+phase+"'");
        }
        if (bigger!=null && bigger>0){
            sb.append(" and registerStatus>="+bigger);
        }
        if(flagExt!=null&&flagExt.equals("0")){//表示为延考或恢复状态,作为查找条件
            sb.append(" and regType = '0' ");
        }else{
            sb.append(" and regType = '1' ");
        }
        sb.append(" order by submitTime desc");
        List<RegisterInfo> results = registerService.queryList(sb.toString());
        String[] props = StringUtils.split(fields, ",");


        //文件导出路径
        String excelName = "报名信息表"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        //转码防止乱码
        try {
            response.reset();
            response.setContentType("application/vnd.ms-excel; charset=utf-8");
            response.setContentType("application/force-download");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(excelName.getBytes("GB2312"), "ISO8859-1") + ".xls");
            registerService.outProperties(results, props, response.getOutputStream());
            response.flushBuffer();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }
    
    
}

