package com.ssj.sys.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import com.alibaba.fastjson.JSON;
import com.ssj.bean.weixin.libmy.domain.LibBookApply;
import com.ssj.framework.basic.common.bean.SplitPage;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.common.controller.BaseController;
import com.ssj.framework.core.util.ResponseEntity;
import com.ssj.service.reading.request.GradeReq;
import com.ssj.service.reading.request.RandomBookReq;
import com.ssj.service.reading.request.ThemeReq;
import com.ssj.service.weixin.library.service.LibBookApplyService;
import com.ssj.service.weixin.library.service.LibBookLockingService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@RequestMapping("/sys/dispatcher")
@Controller
public class DispatcherController extends BaseController {
    @Autowired
    private LibBookLockingService lockingService;
    @Autowired
    private LibBookApplyService applyService;

    @RequestMapping("/lockList")
    public String lockList(Model model, @RequestParam(required = false, defaultValue = "10") int pageSize,
                           @RequestParam(required = false, defaultValue = "1") int pageNo) throws Exception{

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("leagueName",request.getParameter("leagueName")==null?"":request.getParameter("leagueName"));//图书馆
        params.put("stat",request.getParameter("stat")==null?"2":request.getParameter("stat"));//图书馆
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI().toString());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String, Object>> page= lockingService.findLockList(params, initPage(pageNo,pageSize));
        sp.setRowCnt((int)page.getTotalElements());
        model.addAttribute("list", page.getContent());
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);

        return "sys/dispatcher/locklist";
    }

    @RequestMapping("/infoList")
    public String infoList(Model model, @RequestParam(required = false, defaultValue = "10") int pageSize,
                           @RequestParam(required = false, defaultValue = "1") int pageNo) throws Exception{

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("leagueName",request.getParameter("leagueName")==null?"":request.getParameter("leagueName"));//图书馆
        System.out.println(request.getParameter("statTime"));
        params.put("statTime",request.getParameter("statTime")==null?"":request.getParameter("statTime"));//图书馆
        params.put("endTime",request.getParameter("endTime")==null?"":request.getParameter("endTime"));//图书馆
        if(request.getParameter("statTime")==null && request.getParameter("endTime")==null){
            params.put("statTime",request.getParameter("statTime")==null? DateHelper.format(new Date(),"yyyy-MM-dd") :request.getParameter("statTime"));//图书馆
        }
        params.put("type",request.getParameter("type")==null?"":request.getParameter("type"));//图书馆
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI().toString());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String, Object>> page= lockingService.findInfoList(params, initPage(pageNo,pageSize));
        sp.setRowCnt((int)page.getTotalElements());
        model.addAttribute("list", page.getContent());
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);

        return "sys/dispatcher/infolist";
    }

    @RequestMapping(value = "/exportInfoDetail", method = RequestMethod.POST)
    @ResponseBody
    public void exportInfoDetail(HttpServletRequest request, HttpServletResponse response) {
        ServletOutputStream os = null;
        try {
            String libName="调度记录数据";
            os = response.getOutputStream(); //获得输出流
            response.reset();   //清空输出流
            String fileName = new String(libName.getBytes("gb2312"), "ISO8859-1") +".xlsx";
            response.setHeader("Content-disposition", "attachment; filename="+ fileName); //设定输出文件头
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("utf-8");
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("leagueName",request.getParameter("leagueName")==null?"":request.getParameter("leagueName"));//图书馆
            params.put("statTime",request.getParameter("statTime")==null?"":request.getParameter("statTime"));//图书馆
            params.put("endTime",request.getParameter("endTime")==null?"":request.getParameter("endTime"));//图书馆
            if(request.getParameter("statTime")==null && request.getParameter("endTime")==null){
                params.put("statTime",request.getParameter("statTime")==null? DateHelper.format(new Date(),"yyyy-MM-dd") :request.getParameter("statTime"));//图书馆
            }
            params.put("type",request.getParameter("type")==null?"":request.getParameter("type"));//图书馆

            Page<Map<String, Object>> page = lockingService.findInfoList(params, initPage(1, 100000));
            List<Map<String, Object>> list = page.getContent();
            List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
            dataList.addAll(list);
            List<ExcelExportEntity> entity = new ArrayList<ExcelExportEntity>();
            //构造对象等同于@Excel
            entity.add(new ExcelExportEntity("操作类型", "type"));
            entity.add(new ExcelExportEntity("图书馆名称", "league_name"));
            entity.add(new ExcelExportEntity("书名", "title"));
            entity.add(new ExcelExportEntity("一级标签", "fname"));
            entity.add(new ExcelExportEntity("二级标签", "sname"));
            entity.add(new ExcelExportEntity("价钱", "price"));
            entity.add(new ExcelExportEntity("书架位置", "bookcase"));
            entity.add(new ExcelExportEntity("创建时间", "create_time"));
            entity.add(new ExcelExportEntity("ISBN", "isbn13"));

            //把我们构造好的bean对象放到params就可以了
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("调度记录数据", "调度记录数据", ExcelType.XSSF), entity,
                    dataList);
            workbook.write(os);
        }catch (IOException e) {
            logger.error("异常", e);
        }catch (Exception e1){
            logger.error("异常", e1);
        }finally{
            if(os != null){
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    logger.error("异常", e);
                }
            }

        }
    }

    @RequestMapping(value = "/exportDetail", method = RequestMethod.POST)
    @ResponseBody
    public void exportDetail(HttpServletRequest request, HttpServletResponse response) {
        ServletOutputStream os = null;
        try {
            String libName="调度数据";
            os = response.getOutputStream(); //获得输出流
            response.reset();   //清空输出流
            String fileName = new String(libName.getBytes("gb2312"), "ISO8859-1") +".xlsx";
            response.setHeader("Content-disposition", "attachment; filename="+ fileName); //设定输出文件头
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("utf-8");
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("leagueName",request.getParameter("leagueName")==null?"":request.getParameter("leagueName"));//图书馆
            params.put("stat",request.getParameter("stat")==null?"2":request.getParameter("stat"));//图书馆

            Page<Map<String, Object>> page = lockingService.findLockList(params, initPage(1, 100000));
            List<Map<String, Object>> list = page.getContent();
            List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
            dataList.addAll(list);
            List<ExcelExportEntity> entity = new ArrayList<ExcelExportEntity>();
//构造对象等同于@Excel
            ExcelExportEntity excelentity = new ExcelExportEntity("图书馆名称", "league_name");
            entity.add(excelentity);
            ExcelExportEntity excelentity2 = new ExcelExportEntity("书籍标题", "title");
            entity.add(excelentity2);
            ExcelExportEntity excelentity3 = new ExcelExportEntity("一级标签", "fname");
            entity.add(excelentity3);
            ExcelExportEntity excelentity4 = new ExcelExportEntity("二级标签", "sname");
            entity.add(excelentity4);
            ExcelExportEntity excelentity5 = new ExcelExportEntity("价钱", "price");
            entity.add(excelentity5);
            ExcelExportEntity excelentity6 = new ExcelExportEntity("书架位置", "bookcase");
            entity.add(excelentity6);

            ExcelExportEntity excelentity7 = new ExcelExportEntity("创建时间", "create_time");
            entity.add(excelentity7);

//把我们构造好的bean对象放到params就可以了
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("调度明细", "调度明细", ExcelType.XSSF), entity,
                    dataList);
            workbook.write(os);
        }catch (IOException e) {
            logger.error("异常", e);
        }catch (Exception e1){
            logger.error("异常", e1);
        }finally{
            if(os != null){
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    logger.error("异常", e);
                }
            }

        }
    }

    //共享馆图书信息
    @RequestMapping("/libInfoList")
    public String libInfoList(Model model, @RequestParam(required = false, defaultValue = "10") int pageSize,
                           @RequestParam(required = false, defaultValue = "1") int pageNo) throws Exception{

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("leagueName",request.getParameter("leagueName")==null?"":request.getParameter("leagueName"));
        params.put("queryDate",request.getParameter("queryDate")==null?"":request.getParameter("queryDate"));
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI().toString());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String, Object>> page= lockingService.findLibInfoList(params, initPage(pageNo,pageSize));
        sp.setRowCnt((int)page.getTotalElements());
        model.addAttribute("list", page.getContent());
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);

        return "sys/dispatcher/libInfolist";
    }

    @RequestMapping(value = "/exportLibInfoDetail", method = RequestMethod.POST)
    @ResponseBody
    public void exportLibInfoDetail(HttpServletRequest request, HttpServletResponse response) {
        ServletOutputStream os = null;
        try {
            String libName="图书馆图书记录数据";
            os = response.getOutputStream(); //获得输出流
            response.reset();   //清空输出流
            String fileName = new String(libName.getBytes("gb2312"), "ISO8859-1") +".xlsx";
            response.setHeader("Content-disposition", "attachment; filename="+ fileName); //设定输出文件头
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("utf-8");
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("leagueName",request.getParameter("leagueName")==null?"":request.getParameter("leagueName"));//图书馆

            Page<Map<String, Object>> page = lockingService.findLibInfoList(params, initPage(1, 10000));
            List<Map<String, Object>> list = page.getContent();
            List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
            dataList.addAll(list);
            List<ExcelExportEntity> entity = new ArrayList<ExcelExportEntity>();
            //构造对象等同于@Excel
            entity.add(new ExcelExportEntity("图书馆名称", "league_name"));
            entity.add(new ExcelExportEntity("书名", "title"));
            entity.add(new ExcelExportEntity("一级标签", "fname"));
            entity.add(new ExcelExportEntity("二级标签", "sname"));
            entity.add(new ExcelExportEntity("价钱", "price"));
            entity.add(new ExcelExportEntity("书架位置", "bookcase"));
            entity.add(new ExcelExportEntity("ISBN", "isbn13"));
            entity.add(new ExcelExportEntity("录入时间", "create_time"));

            //把我们构造好的bean对象放到params就可以了
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("图书馆图书记录数据", "图书馆图书记录数据", ExcelType.XSSF), entity,
                    dataList);
            workbook.write(os);
        }catch (IOException e) {
            logger.error("异常", e);
        }catch (Exception e1){
            logger.error("异常", e1);
        }finally{
            if(os != null){
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    logger.error("异常", e);
                }
            }

        }
    }

    @RequestMapping("/libApplyInfoList")
    public String libApplyInfoList(Model model, @RequestParam(required = false, defaultValue = "10") int pageSize,
                              @RequestParam(required = false, defaultValue = "1") int pageNo) throws Exception{

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("leagueName",request.getParameter("leagueName")==null?"":request.getParameter("leagueName"));//图书馆
        params.put("type",1);//图书馆
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI().toString());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String, Object>> page= lockingService.findApplyInfoList(params, initPage(pageNo,pageSize));
        sp.setRowCnt((int)page.getTotalElements());
        model.addAttribute("list", page.getContent());
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);

        return "sys/dispatcher/applyInfolist";
    }

    @RequestMapping(value = "/exportLibApplyDetail", method = RequestMethod.POST)
    @ResponseBody
    public void exportLibApplyDetail(HttpServletRequest request, HttpServletResponse response) {
        ServletOutputStream os = null;
        try {
            String libName="图书馆图书记录数据";
            os = response.getOutputStream(); //获得输出流
            response.reset();   //清空输出流
            String fileName = new String(libName.getBytes("gb2312"), "ISO8859-1") +".xlsx";
            response.setHeader("Content-disposition", "attachment; filename="+ fileName); //设定输出文件头
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("utf-8");
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("leagueName",request.getParameter("leagueName")==null?"":request.getParameter("leagueName"));//图书馆
            params.put("type",1);//图书馆
            Page<Map<String, Object>> page = lockingService.findApplyInfoList(params, initPage(1, 100000));
            List<Map<String, Object>> list = page.getContent();
            List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
            dataList.addAll(list);
            List<ExcelExportEntity> entity = new ArrayList<ExcelExportEntity>();
            //构造对象等同于@Excel
            entity.add(new ExcelExportEntity("图书馆名称", "league_name"));
            entity.add(new ExcelExportEntity("申请批次", "batch_id"));
            entity.add(new ExcelExportEntity("书名", "title"));
            entity.add(new ExcelExportEntity("出版社", "publish"));
            entity.add(new ExcelExportEntity("期望派送时间", "pai_date"));
            entity.add(new ExcelExportEntity("书籍来源", "book_src"));
            entity.add(new ExcelExportEntity("提交时间", "create_time"));
            //t12.state,t12.audit_msg,t12.batch_id
            //把我们构造好的bean对象放到params就可以了
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("图书馆图书记录数据", "图书馆图书记录数据", ExcelType.XSSF), entity,
                    dataList);
            workbook.write(os);
        }catch (IOException e) {
            logger.error("异常", e);
        }catch (Exception e1){
            logger.error("异常", e1);
        }finally{
            if(os != null){
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    logger.error("异常", e);
                }
            }

        }
    }
    @RequestMapping(value="/saveApplyAudit",method = RequestMethod.POST)
    @ResponseBody

    public ResponseEntity saveApplyAudit(@RequestParam String id, @RequestParam int state,  String msg){
        ResponseEntity responseEntity = new ResponseEntity();
        try {
            LibBookApply apply = applyService.getById(id);
            if(apply == null){
                responseEntity.failure("000","审核数据不存在");
                return responseEntity;
            }
            applyService.saveApplyAudit(apply.getLibId(),apply.getBatchId(),state,msg);
            responseEntity.success("审核通过");
        }catch (Exception e){
            responseEntity.failure("系统出现异常，保存失败");
            logger.error("异常", e);
        }

        return responseEntity;
    }

    @RequestMapping("/libApplyEdit")
    public String libApplyEdit(Model model, @RequestParam(required = false, defaultValue = "1") String id) throws Exception{

        LibBookApply apply = applyService.getById(id);
        model.addAttribute("ws", apply);

        return "sys/dispatcher/applyMsgEdit";
    }

    @RequestMapping("/libRadomApplyList")
    public String libRadomApplyList(Model model, @RequestParam(required = false, defaultValue = "10") int pageSize,
                                   @RequestParam(required = false, defaultValue = "1") int pageNo) throws Exception{

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("leagueName",request.getParameter("leagueName")==null?"":request.getParameter("leagueName"));//图书馆
        params.put("type",2);//图书馆
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI().toString());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String, Object>> page= lockingService.findApplyInfoList(params, initPage(pageNo,pageSize));
        sp.setRowCnt((int)page.getTotalElements());
        List<Map<String, Object>> list = page.getContent();
        if(list!=null && list.size()>0){
            for (Map<String, Object> map:list){
                 String join = map.get("radom_json").toString();
                 RandomBookReq req = JSON.parseObject(join,RandomBookReq.class);
                 map.put("grades",GradeToString(req.getGradeList()));
                 map.put("theme",ThemeToString(req.getThemeList()));
                 map.put("bookSize",req.getBookSize());
                 map.put("stateSrc",map.get("state")==null?"未处理":"已处理");
            }
        }
        model.addAttribute("list", list);
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);

        return "sys/dispatcher/applyRadomlist";
    }

    @RequestMapping(value="/saveApplyRadom",method = RequestMethod.POST)
    @ResponseBody

    public ResponseEntity saveApplyRadom(@RequestParam String id){
        ResponseEntity responseEntity = new ResponseEntity();
        try {
            LibBookApply apply = applyService.getById(id);
            if(apply == null){
                responseEntity.failure("000","审核数据不存在");
                return responseEntity;
            }
            applyService.saveApplyRadom(apply);
            responseEntity.success("书单生成成功");
        }catch (Exception e){
            responseEntity.failure("系统出现异常，保存失败");
            logger.error("异常", e);
        }

        return responseEntity;
    }
    private String GradeToString(List<GradeReq> req){
        String reStr = "";
        if (req!=null && req.size()>0){
            for (GradeReq gradeReq:req){
                if(reStr.length()>0){
                    reStr+=",";
                }
                reStr+=gradeReq.getGrade();
            }
        }
        return  reStr;
    }

    private String ThemeToString(List<ThemeReq> req){
        String reStr = "";
        if (req!=null && req.size()>0){
            for (ThemeReq themeReq:req){
                if(reStr.length()>0){
                    reStr+=",";
                }
                reStr+=themeReq.getName();
                if(themeReq.getChildList()!=null && themeReq.getChildList().size()>0){
                    for (ThemeReq themeReq2:themeReq.getChildList()){
                        if(reStr.length()>0){
                            reStr+=",";
                        }
                        reStr+=themeReq2.getName();
                    }
                }
            }
        }
        return  reStr;
    }
}
