package cn.com.liandisys.ycjt.ggcx.busline.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Maps;

import cn.com.liandisys.ycjt.ggcx.admin.utils.DynamicSpecifications;
import cn.com.liandisys.ycjt.ggcx.admin.utils.SearchFilter;
import cn.com.liandisys.ycjt.ggcx.admin.utils.SearchFilter.Operator;
import cn.com.liandisys.ycjt.ggcx.busline.model.BusLineEntity;
import cn.com.liandisys.ycjt.ggcx.busline.service.BusLineService;
import cn.com.liandisys.ycjt.ggcx.common.controller.BaseController;
import cn.com.liandisys.ycjt.ggcx.common.util.MessageUtil;

/**
 * 
 * 项目名称：ycjt-ggcx    
 * 类名称：BusLineController    
 * 类描述：   公交线路
 * 创建人：yangd    
 * 创建时间：2016年11月23日 下午2:23:40    
 * 修改人：yangd    
 * 修改时间：2016年11月23日 下午2:23:40    
 * 修改备注：    
 * @version     
 *
 */
@Controller
@RequestMapping(value = "/table")
public class BusLineController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(BusLineController.class);

    @Autowired
    private BusLineService busLineService;

    //查询公交线路
    @RequestMapping(value = "initLineData")
    public String initLineData(Model model, @ModelAttribute("pageRequest") PageRequest pageRequest,
            @RequestParam(value = "LINE_NAME", required = false, defaultValue = "") String lineName,
            @RequestParam(value = "SITE", required = false, defaultValue = "") String site, String message) {

        // 查询条件
        Map<String, SearchFilter> filters = Maps.newHashMap();

        if (!lineName.equals("")) {
            filters.put("LINE_NAME", new SearchFilter("LINE_NAME", Operator.LIKE, lineName));
            model.addAttribute("lineName", lineName);
        }
        if (!site.equals("")) {
            filters.put("SITE", new SearchFilter("SITE", Operator.LIKE, site));
            model.addAttribute("site", site);
        }

        Specification<BusLineEntity> spec = DynamicSpecifications.bySearchFilter(filters.values(), BusLineEntity.class);
        Page<BusLineEntity> jpaPage = busLineService.findAll(spec, pageRequest);

        cn.com.liandisys.ycjt.ggcx.admin.model.Page<BusLineEntity> page =
                new cn.com.liandisys.ycjt.ggcx.admin.model.Page<BusLineEntity>(jpaPage.getNumber() + 1,
                        jpaPage.getSize(), jpaPage.getTotalElements());
        //当分页页码超过查询上限，则重置为最后一页，再查询一遍
        int lastPage = jpaPage.getTotalPages();
        if (lastPage > 0) {
            if (lastPage < pageRequest.getPageNumber() + 1) {
                pageRequest = new PageRequest(lastPage - 1, pageRequest.getPageSize(), pageRequest.getSort());
                jpaPage = busLineService.findAll(spec, pageRequest);
            }
        }
        List<BusLineEntity> pageList = jpaPage.getContent();
        if (!site.equals("")) {
            for (BusLineEntity bus : pageList) {
                bus.setSITE(bus.getSITE().replaceAll(site, "<font style='color:red'>" + site + "</font>"));
            }
        }
        page.setList(pageList);
        model.addAttribute("page", page);
        model.addAttribute("message", message);
        model.addAttribute("bl", new BusLineEntity());
        return "table/busline";
    }

    //查询首页的途经公交线路
    @RequestMapping(value = "getBusLineName.do")
    @ResponseBody
    public Map<String, Object> getBusLineName(HttpServletRequest request) {

        String site = request.getParameter("linename");

        site = site.replace("（", "(").replace("）", ")");
        Map<String, Object> retMap = new HashMap<String, Object>();
        try {
            List<BusLineEntity> list = busLineService.getBusLineName(site);
            retMap.put("result", list);
            return MessageUtil.buildResponseMap(true, retMap);

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return MessageUtil.buildResponseMap(false, MessageUtil.buildSystemErrorMessage(e), retMap);
        }

    }

    /**
     * 分页信息获取
     * 
     */
    @ModelAttribute("pageRequest")
    public PageRequest getPageRequest(@RequestParam(value = "pageNo", required = false, defaultValue = "1") String page,
            @RequestParam(value = "pageSize", required = false, defaultValue = "4") String size) {

        Sort sort = new Sort(Direction.DESC, new String[] { "ID" });
        if (org.springframework.util.StringUtils.hasText(page) && org.springframework.util.StringUtils.hasText(size)
                && null != sort) {
            // 页码从0开始
            PageRequest pageable = new PageRequest(Integer.parseInt(page) - 1, Integer.parseInt(size), sort);
            return pageable;
        }
        return null;
    }
}
