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

import java.util.ArrayList;
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.servlet.ModelAndView;

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.common.constant.PageUrl;
import cn.com.liandisys.ycjt.ggcx.common.constant.SystemConstant;
import cn.com.liandisys.ycjt.ggcx.common.controller.BaseController;
import cn.com.liandisys.ycjt.ggcx.common.service.DataDicService;
import cn.com.liandisys.ycjt.ggcx.common.util.JacksonUtil;
import cn.com.liandisys.ycjt.ggcx.taximan.dao.TaxiManDao;
import cn.com.liandisys.ycjt.ggcx.taximan.model.TaxiMan;
import cn.com.liandisys.ycjt.ggcx.taximan.service.TaxiManService;

@Controller
@RequestMapping("/table")
public class TaxiManController extends BaseController {

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

    @Autowired
    private TaxiManService taxiManService;

    @Autowired
    private TaxiManDao taxiManDao;

    @Autowired
    private DataDicService dataDicService;

    @RequestMapping("/taxiinfo")
    public ModelAndView showQbRunView(HttpServletRequest request) throws Exception {

        ModelAndView mv = new ModelAndView(PageUrl.TAXIINFO_VIEW);

        try {
            // 设备状态
            mv.addObject("companyList",
                    JacksonUtil.toJsonNode(dataDicService.getDataDicInfo(SystemConstant.TAXI_COMPANY)));

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
        return mv;
    }

    /*
     * 初始化数据列表
     * 2016.11.24
     * by b_zhaosheng
     **/
    @RequestMapping(value = "getTaxiManGridData")
    public String getTaxiManGridData(Model model, @ModelAttribute("pageRequest") PageRequest pageRequest,
            @RequestParam(value = "id", required = false, defaultValue = "") String id,
            @RequestParam(value = "taxiCompany", required = false, defaultValue = "") String taxiCompany,
            String message) throws Exception {

        model.addAttribute("companyList", dataDicService.getDataDicInfo(SystemConstant.TAXI_COMPANY));
        // 查询条件
        Map<String, SearchFilter> filters = Maps.newHashMap();

        if (!id.equals("")) {
            filters.put("id", new SearchFilter("id", Operator.LIKE, id));
            model.addAttribute("id", id);
        }
        if (!taxiCompany.equals("")) {
            filters.put("taxiCompany", new SearchFilter("taxiCompany", Operator.EQ, taxiCompany));
            model.addAttribute("taxiCompany", taxiCompany);
        }

        Specification<TaxiMan> spec = DynamicSpecifications.bySearchFilter(filters.values(), TaxiMan.class);

        Page<TaxiMan> jpaPage = taxiManService.findAll(spec, pageRequest);

        cn.com.liandisys.ycjt.ggcx.admin.model.Page<TaxiMan> page =
                new cn.com.liandisys.ycjt.ggcx.admin.model.Page<TaxiMan>(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 = taxiManService.findAll(spec, pageRequest);
            }
        }
        page.setList(jpaPage.getContent());
        List<TaxiMan> tempList = page.getList();
        List<TaxiMan> resultList = new ArrayList<TaxiMan>();
        try {
            for (TaxiMan d : tempList) {
                if (d.getSex().equals("0")) {
                    d.setSex("男");
                } else {
                    d.setSex("女");
                }
                d.setTaxiCompany(dataDicService.getDataDicName(SystemConstant.TAXI_COMPANY, d.getTaxiCompany()));
                resultList.add(d);
            }
        } catch (Exception e) {
            model.addAttribute("message", e.getMessage());
        }
        page.setList(resultList);
        model.addAttribute("page", page);
        model.addAttribute("message", message);
        model.addAttribute("td", new TaxiMan());
        return "table/taxiinfo";
    }

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

        Sort sort = new Sort(Direction.DESC, new String[] { "insertTime" });
        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;
    }
}
