package com.xintong.visualinspection.service.impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

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

import com.xintong.visualinspection.bean.FeeStation;
import com.xintong.visualinspection.bean.Organ;
import com.xintong.visualinspection.dao.cluster.DepartmentDao;
import com.xintong.visualinspection.dao.master.CheckItemDao;
import com.xintong.visualinspection.dao.master.CheckRuleDao;
import com.xintong.visualinspection.pojo.OtherCheckStatistics;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.druid.util.Utils;
import com.xintong.visualinspection.bean.CheckOther;
import com.xintong.visualinspection.dao.master.CheckOtherDao;
import com.xintong.visualinspection.service.BaseService;
import com.xintong.visualinspection.service.CheckOtherService;
import com.xintong.visualinspection.util.CodeUtil;
import com.xintong.visualinspection.util.DateUtil;

/**
 * 文件名：CheckOtherServiceImpl
 * 版本信息：日期：2017/8/11 Copyright 江苏省交通规划设计院 Corporation 2017 版权所有.
 */
@Service
public class CheckOtherServiceImpl  extends BaseService implements CheckOtherService{

	private static final org.slf4j.Logger logger = LoggerFactory.getLogger(CheckOtherServiceImpl.class);

	@Autowired
	private CheckOtherDao checkOtherDao;
    @Autowired
    private DepartmentDao departmentDao;



	@Override
	public void insert(CheckOther checkOther) {
		checkOtherDao.insert(checkOther);
	}
	@Override
	public List<CheckOther> getCheckByDeptId(CheckOther checkOther) {
		List<CheckOther> checkOtherList = checkOtherDao.getCheckByDeptId(checkOther);
		return checkOtherList;
	}
	
	@Override
	public void getOtherCheckExcel(CheckOther checkOther, HttpServletRequest req, HttpServletResponse resp) {
		List<CheckOther> checkOtherList = getCheckByDeptId(checkOther);
		Long id = 1L ;
    	for(CheckOther co : checkOtherList){
    		co.setId(id++);
    		if(co.getWrecker_check_type()!=null){
    			co.setWrecker_check_type_name(CodeUtil.getCodeNameByFlagAndValue("wrecker_group_check_type", co.getWrecker_check_type()+""));
    		}
    		if(co.getSpecial_check_type()!=null){
    			co.setSpecial_check_type_name(CodeUtil.getCodeNameByFlagAndValue("special_check_type", co.getSpecial_check_type()+""));
    		}
    		co.setCheck_time_name(DateUtil.DateFormatStr(co.getCheck_time()));
    		if( co.getUsername() == null || "".equals(co.getUsername()) ){
    			co.setUsername("站部");
    		}
    	}
    	Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", checkOtherList);
		if(checkOther.getCheck_type() == 1){
			exportExcel("第三方暗访稽查" , "third_check", map, resp);
		}else if(checkOther.getCheck_type() == 2){
			exportExcel("特情稽查" , "special_check", map, resp);
		}else if(checkOther.getCheck_type() == 3){
			exportExcel("现场稽查" , "duty_check", map, resp);
		}else if(checkOther.getCheck_type() == 4){
			exportExcel("数据平台应用稽查" , "data_platform", map, resp);
		}else if(checkOther.getCheck_type() == 5){
			exportExcel("清排障稽查" , "solve_traffic", map, resp);
		}
	}
	
	private void exportExcel(String fileName, String excelTemplateName, Map<String, Object> map,
			HttpServletResponse resp) {
		String path = "./" + fileName + ".xls";
		try (InputStream is = this.getClass().getResourceAsStream("/" + excelTemplateName + ".xls")) {
			try (OutputStream os = new FileOutputStream(path)) {
				Context context = new Context();
				// context.putVar("list", map.get("list"));
				// context.putVar("totalMan", map.get("totalMan"));
				for (String key : map.keySet()) {
					context.putVar(key, map.get(key));
				}
				JxlsHelper.getInstance().processTemplate(is, os, context);
			}
			Thread.sleep(1000);
			// path是指欲下载的文件的路径。
			File file = new File(path);
			// 取得文件名。
			String filename = file.getName();
			// 以流的形式下载文件。
			InputStream bis = new BufferedInputStream(new FileInputStream(file));
			byte[] buffer = new byte[bis.available()];
			bis.read(buffer);
			bis.close();
			// 清空response
			resp.reset();
			// 设置response的Header
			resp.addHeader("Content-Disposition",
					"attachment;filename=" + new String(filename.getBytes("gb2312"), "ISO8859-1"));
			resp.addHeader("Content-Length", "" + file.length());
			OutputStream toClient = new BufferedOutputStream(resp.getOutputStream());
			resp.setContentType("application/vnd.ms-excel;charset=gb2312");
			toClient.write(buffer);
			toClient.flush();
			toClient.close();
			// 删除生成的临时文件
			if (file.exists()) {
				file.delete();
			}

		} catch (Exception e) {
			logger.error(e.toString());
		}
	}
	
	
	@Override
	public void delete(Long id) {
		checkOtherDao.delete(id);
	}
	@Override
	public CheckOther getCheckById(Long id) {
		CheckOther checkOther = checkOtherDao.getCheckById(id);
		return checkOther;
	}
	@Override
	public void update(CheckOther checkOther) {
		checkOtherDao.update(checkOther);
	}

    @Override
    public Map<String,Object> getOtherCheckStatistics(String checktime, int checktype,Integer type) {

	    Map<String,Object> datas = new HashMap<>();

        List<OtherCheckStatistics> otherCheckStatistics = new ArrayList<>();

        List<FeeStation> liststation = departmentDao.getAllFS();
        List<FeeStation> list = departmentDao.getAllRM();


        CheckOther checkOther = new CheckOther();
        checkOther.setCheck_time_name(checktime);
        checkOther.setCheck_type(checktype);
        if(type!=null){checkOther.setSpecial_check_type(type);}
        List<CheckOther> checkOthers =  checkOtherDao.getCheckByDeptId(checkOther);

        if(checktype==2&&type==null){
            List<String> itemname =  checkOtherDao.getcheckitemnames(22L);

            for (FeeStation station:liststation
                    ) {
                OtherCheckStatistics otherCheckStatistics1 = new OtherCheckStatistics();
                otherCheckStatistics1.setDeptid(station.getDeptid());
                otherCheckStatistics1.setDeptname(station.getName().replaceAll("收费站",""));
                otherCheckStatistics1.setPdeptid(station.getParentid());
//                otherCheckStatistics1.setPdeptname(pstation.getName());
                HashMap<String,Integer> s1 = new HashMap<>();
                for (String i:itemname
                        ) {
                    s1.put(i,0);
                }
                HashMap<String,Integer> s2 = new HashMap<>();
                for (String i:itemname
                        ) {
                    s2.put(i,0);
                }
                int totalcheck=0;
                int totalscore=0;

                for (CheckOther c :checkOthers){
                    if((c.getDept_id()+"").equals(station.getDeptid())){
                        if(c.getSpecial_check_type()!=null && c.getSpecial_check_type().intValue()==1){
                            Integer i = s1.get(c.getPcheckname());
                            if(i==null){i=0;}
                            s1.put(c.getPcheckname(), Integer.valueOf((int) (i+c.getCheck_score())));
                            totalcheck+=1;
                            totalscore+=c.getCheck_score();
                        }
                        if(c.getSpecial_check_type()!=null && c.getSpecial_check_type().intValue()==2){
                            Integer i = s2.get(c.getPcheckname());
                            if(i==null){i=0;}
                            s2.put(c.getPcheckname(), Integer.valueOf((int) (i+c.getCheck_score())));
                            totalcheck+=1;
                            totalscore+=c.getCheck_score();
                        }
                    }
                }
                HashMap<String,HashMap<String,Integer>> map = new HashMap<>();
                map.put("2",s2);
                map.put("1",s1);

                otherCheckStatistics1.setScoretypemap(map);
                otherCheckStatistics1.setTotalScore(totalscore);
                otherCheckStatistics1.setTotalcheck(totalcheck);
                otherCheckStatistics.add(otherCheckStatistics1);
            }


            for (FeeStation a:list
                    ) {
                List<OtherCheckStatistics> s=new ArrayList<>();
                for (OtherCheckStatistics o:otherCheckStatistics
                        ) {
                    if(o.getPdeptid().equals(a.getDeptid())){
                        o.setPdeptname(a.getName());
                        s.add(o);
                    }
                }

                datas.put(a.getName().replaceAll("道管中心",""),s);
            }

        }

	    if(checktype==1||checktype==4||checktype == 3 ||(type!=null&&checktype == 2)){

	        Long id = 21L;
	        if(checktype==1){id = 21L;}
            if(checktype==3){id = 23L;}
            if(checktype==4){id = 24L;}
            if(checktype==2){id = 22L;}
	        //获取考核办法对应的考核项
           List<String> itemname =  checkOtherDao.getcheckitemnames(id);
            for (CheckOther c :checkOthers){
                if(!itemname.contains(c.getPcheckname())){
                    itemname.add(c.getPcheckname());
                }
            }

            for (FeeStation station:liststation
                 ) {
                OtherCheckStatistics otherCheckStatistics1 = new OtherCheckStatistics();
                otherCheckStatistics1.setDeptid(station.getDeptid());
                otherCheckStatistics1.setDeptname(station.getName().replaceAll("收费站",""));
                otherCheckStatistics1.setPdeptid(station.getParentid());
//                otherCheckStatistics1.setPdeptname(pstation.getName());
                HashMap<String,Integer> s = new HashMap<>();
                for (String i:itemname
                     ) {
                    s.put(i,0);
                }
                for (CheckOther c :checkOthers){
                    if((c.getDept_id()+"").equals(station.getDeptid())){
                        Integer i = s.get(c.getPcheckname());
                        if(i==null){i=0;}
                        if(checktype==2){
                            s.put(c.getPcheckname(), Integer.valueOf((int) (i+c.getCheck_score())));
                        }else{
                            if(c.getUsername() == null || "".equals(c.getUsername())){
                                s.put(c.getPcheckname(), Integer.valueOf((int) (i+c.getCheck_score())));
                            }else {
                                s.put(c.getPcheckname(), i);
                            }
                        }

                    }
                }
                otherCheckStatistics1.setScoremap(s);
                otherCheckStatistics.add(otherCheckStatistics1);
            }


            for (FeeStation a:list
                    ) {
                List<OtherCheckStatistics> s=new ArrayList<>();
                for (OtherCheckStatistics o:otherCheckStatistics
                     ) {
                    if(o.getPdeptid().equals(a.getDeptid())){
                        o.setPdeptname(a.getName());
                        s.add(o);
                    }
                }

                datas.put(a.getName().replaceAll("道管中心",""),s);
            }
        }

        return datas;
    }

    @Override
    public void getexcel(CheckOther checkOther, HttpServletRequest req, HttpServletResponse resp){
	    String title = checkOther.getCheck_time_name();

        if(checkOther.getCheck_type()==2&&checkOther.getSpecial_check_type()==null){
            Map<String,Object> m= getOtherCheckStatistics(checkOther.getCheck_time_name(),checkOther.getCheck_type(),checkOther.getSpecial_check_type());
            Map<String,Object> map = new HashMap<>();
            map.put("datas",m);

            title+="月份特情稽查情况汇总";
            map.put("title",title.replaceAll("/","-"));
            exportExcel(title.replaceAll("/","-"), "other_check_info_teqing", map, resp);
        }

        if(checkOther.getCheck_type() == 1||checkOther.getCheck_type() == 4||checkOther.getCheck_type() == 3||(checkOther.getCheck_type() == 2&&checkOther.getSpecial_check_type()!=null)){
           Map<String,Object> m= getOtherCheckStatistics(checkOther.getCheck_time_name(),checkOther.getCheck_type(),checkOther.getSpecial_check_type());
           Map<String,Object> map = new HashMap<>();
           map.put("datas",m);

           if(checkOther.getCheck_type() == 1){title+="月份第三方暗访情况";}
           if(checkOther.getCheck_type() == 4){title+="月份数据平台应用情况";}
            if(checkOther.getCheck_type() == 3){title+="月份现场检查情况";}
            if(checkOther.getCheck_type() == 2 && (checkOther.getSpecial_check_type().intValue()==1)){title+="公司特情稽查情况";}
            if(checkOther.getCheck_type() == 2 && (checkOther.getSpecial_check_type().intValue()==2)){title+="联网特情稽查情况";}
            map.put("title",title.replaceAll("/","-"));

           exportExcel(title.replaceAll("/","-"), "other_check_info_anfang", map, resp);
        }

    }


}
