package com.xintong.visualinspection.visuallnspection_qzd.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xintong.visualinspection.bean.Constant;
import com.xintong.visualinspection.bean.FeeStation;
import com.xintong.visualinspection.bean.FwqCheckOther;
import com.xintong.visualinspection.bean.FwqCheckOtherStatistics;
import com.xintong.visualinspection.bean.Item;
import com.xintong.visualinspection.bean.Organ;
import com.xintong.visualinspection.service.CommonService;
import com.xintong.visualinspection.util.DateUtil;
import com.xintong.visualinspection.visuallnspection_qzd.dao.FwqCheckOtherDao;
import com.xintong.visualinspection.visuallnspection_qzd.service.CheckOtherService_F;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文件名：OtherCheckServiceImpl_F
 * 版本信息：日期：2017/4/7 Copyright 江苏省交通规划设计院 Corporation 2017 版权所有.
 *
 * @author wenhongquan
 * @date 2018/05/02
 */
@Service
public class CheckOtherService_FImpl implements CheckOtherService_F {

    private static final Logger logger = LoggerFactory.getLogger(CheckOtherService_FImpl.class);

    @Autowired
    private FwqCheckOtherDao fwqCheckOtherDao;

    @Reference(version = "1.0.0",
            application = "${dubbo.application.id}",
            registry = "${dubbo.registry.address}")
    private CommonService commonService;

    /**
     * 第三方暗访稽查查询(查询条件:时间,道管,服务区),<无分页>
     *
     * @param fwqCheckOther
     * @return
     */
    private Object getAllCheckOther(FwqCheckOther fwqCheckOther) {

        List<FwqCheckOther> checkOtherList = fwqCheckOtherDao.getAllCheckOther(fwqCheckOther == null ? new FwqCheckOther() : fwqCheckOther);
        Map<Long, Organ> deptMap = commonService.getDeptMap();
        Map<Long, Item> itemMap = commonService.getItemMap();
        Map<String, Constant> codeMap = commonService.getCodeMap();
        for (FwqCheckOther data : checkOtherList) {
            if (deptMap.get(data.getDept_id()) != null) {
                data.setOrgan_name(deptMap.get(data.getDept_id()).getOrganname());
            }
            if (itemMap.get(data.getCheck_item_id()) != null) {
                data.setCheck_item_name(itemMap.get(data.getCheck_item_id()).getName());
                if (itemMap.get(data.getCheck_item_id()).getParent_id() != null) {
                    if (itemMap.get(data.getCheck_item_id()).getScore() == null) {
                        data.setPcheckname(itemMap.get(data.getCheck_item_id()).getName());
                    } else {
                        data.setPcheckname(itemMap.get(itemMap.get(data.getCheck_item_id()).getParent_id()).getName());
                    }
                }
            }
            if (codeMap.get(data.getWrecker_check_type()) != null) {
                data.setWrecker_check_type_name(codeMap.get(data.getWrecker_check_type()).getCode_name());
            }
            if (codeMap.get(data.getSpecial_check_type()) != null) {
                data.setSpecial_check_type_name(codeMap.get(data.getSpecial_check_type()).getCode_name());
            }
        }
        return checkOtherList;
    }

    /**
     * 统计数据
     *
     * @param fwqCheckOther
     * @return
     */
    @Override
    public Map<String, Object> getCheckOtherStatistics(FwqCheckOther fwqCheckOther) {

        Map<String, Object> datas = new HashMap<>();
        List<FwqCheckOtherStatistics> fwqCheckOtherStatisticses = new ArrayList<>();

        fwqCheckOther.setCheck_time_name(fwqCheckOther.getCheck_period());
        List<FwqCheckOther> checkOtherList = fwqCheckOtherDao.getAllCheckOther(fwqCheckOther);
        Map<Long, Organ> deptMap = commonService.getDeptMap();
        Map<Long, Item> itemMap = commonService.getItemMap();
        Map<String, Constant> codeMap = commonService.getCodeMap();
        for (FwqCheckOther data : checkOtherList) {
            if (deptMap.get(data.getDept_id()) != null) {
                data.setOrgan_name(deptMap.get(data.getDept_id()).getOrganname());
            }
            if (itemMap.get(data.getCheck_item_id()) != null) {
                data.setCheck_item_name(itemMap.get(data.getCheck_item_id()).getName());
                if (itemMap.get(data.getCheck_item_id()).getParent_id() != null) {
                    if (itemMap.get(data.getCheck_item_id()).getScore() == null) {
                        data.setPcheckname(itemMap.get(data.getCheck_item_id()).getName());
                    } else {
                        data.setPcheckname(itemMap.get(itemMap.get(data.getCheck_item_id()).getParent_id()).getName());
                    }
                }
            }
            if (codeMap.get(data.getWrecker_check_type()) != null) {
                data.setWrecker_check_type_name(codeMap.get(data.getWrecker_check_type()).getCode_name());
            }
            if (codeMap.get(data.getSpecial_check_type()) != null) {
                data.setSpecial_check_type_name(codeMap.get(data.getSpecial_check_type()).getCode_name());
            }
        }

        // 获得所有服务区数据
        List<FeeStation> saList = commonService.getAllDeptByLayer("SA");
        // 获得所有道管中心数据
        List<FeeStation> rmList = commonService.getAllDeptByLayer("RM");

        int checkType = fwqCheckOther.getCheck_type();
        if (checkType == 8 || checkType == 9) {
            Long id = 26L;
            if (checkType == 8) {
                id = 26L;
            }
            if (checkType == 9) {
                id = 27L;
            }
            //获取考核办法对应的考核项
            List<String> itemName = commonService.getCheckItemName(id);

            for (FwqCheckOther c : checkOtherList) {
                if (!itemName.contains(c.getPcheckname())) {
                    itemName.add(c.getPcheckname());
                }
            }

            for (FeeStation station : saList) {
                FwqCheckOtherStatistics fwqCheckOtherStatistics = new FwqCheckOtherStatistics();
                fwqCheckOtherStatistics.setDeptid(station.getDeptid());
                fwqCheckOtherStatistics.setDeptname(station.getName().replaceAll("服务区", ""));
                fwqCheckOtherStatistics.setPdeptid(station.getParentid());
                HashMap<String, Integer> s = new HashMap<>();
                for (String i : itemName) {
                    s.put(i, 0);
                }
                for (FwqCheckOther c : checkOtherList) {
                    if (c.getDept_id().toString().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.getOrgan_name() == null || "".equals(c.getOrgan_name())) {
//                                s.put(c.getPcheckname(), Integer.valueOf((int) (i + c.getCheck_score())));
//                            } else {
//                                s.put(c.getPcheckname(), i);
//                            }
//                        }
                    }
                }
                fwqCheckOtherStatistics.setScoremap(s);
                fwqCheckOtherStatisticses.add(fwqCheckOtherStatistics);
            }

            for (FeeStation a : rmList) {
                List<FwqCheckOtherStatistics> s = new ArrayList<>();
                for (FwqCheckOtherStatistics o : fwqCheckOtherStatisticses) {
                    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(FwqCheckOther fwqCheckOther, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        String title = fwqCheckOther.getCheck_time_name();
        int checkType = fwqCheckOther.getCheck_type();
        fwqCheckOther.setCheck_period(title);
        if (checkType == 8 || checkType == 9) {
            Map<String, Object> m = getCheckOtherStatistics(fwqCheckOther);
            Map<String, Object> map = new HashMap<>();
            map.put("datas", m);

            if (checkType == 8) {
                title += "月份服务区第三方暗访情况";
            }
            if (checkType == 9) {
                title += "月份服务区现场检查情况";
            }
            map.put("title", title.replaceAll("/", "-"));

            exportExcel(title.replaceAll("/", "-"), "fwq_other_check_info_anfang", map, httpServletResponse);
        }
    }

    @Override
    public void getOtherCheckExcel(FwqCheckOther fwqCheckOther, HttpServletRequest req, HttpServletResponse resp) {
        List<FwqCheckOther> checkOtherList = (List<FwqCheckOther>) getAllCheckOther(fwqCheckOther);

        Long id = 1L;
        for (FwqCheckOther co : checkOtherList) {
            co.setId(id++);
            co.setCheck_time_name(DateUtil.DateFormatStr(co.getCheck_time()));
        }

        Map<String, Object> map = new HashMap<>();
        map.put("list", checkOtherList);
        if (fwqCheckOther.getCheck_type() == 8) {
            exportExcel("服务区第三方暗访稽查", "fwq_third_check", map, resp);
        } else if (fwqCheckOther.getCheck_type() == 9) {
            exportExcel("服务区现场稽查", "fwq_duty_check", 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());
        }
    }
}
