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.ssj.bean.conch.curator.dto.CuratorTeacherListDto;
import com.ssj.bean.sys.fx.domain.Merchant;
import com.ssj.bean.weixin.libmy.domain.TbLibJoin;
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.framework.weixin.util.Collections3;
import com.ssj.framework.weixin.util.DateUtil;
import com.ssj.service.conch.parents.service.ParentService;
import com.ssj.service.conch.parents.v1.dto.CorrectDetailDto4;
import com.ssj.service.sys.fx.service.MerchantService;
import com.ssj.service.sys.fx.service.SysCuratorService;
import com.ssj.service.weixin.library.service.ILibJoinService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
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.*;

/**
 * @author sh
 * @className SysCuratorController
 * @description TODO
 * @date 2020/6/17
 */
@Controller
@RequestMapping("/sys/admin/curator")
public class SysCuratorController extends BaseController {

    @Autowired
    private SysCuratorService sysCuratorService;
    @Autowired
    private ILibJoinService joinService;
    @Autowired
	private MerchantService merchantService;
    @Autowired
    private ParentService parentService;

    @RequestMapping("/index")
    public String index(Model model, @RequestParam String libId){
        Map<String,Object> data = sysCuratorService.findIndexData(libId);
        TbLibJoin join = joinService.getById(libId);
        model.addAllAttributes(data);
        model.addAttribute("libId",libId);
        model.addAttribute("leagueName",join.getLeagueName());
        Merchant merchant=merchantService.getMerchantByLibId(libId);
        model.addAttribute("merchant",merchant);
        return "sys/fx/curator/index";
    }

    @RequestMapping("/studentIndex")
    public String studentIndex(Model model, @RequestParam String libId,@RequestParam(required = false, defaultValue = "10") int pageSize,
                              @RequestParam(required = false, defaultValue = "1") int pageNo,@RequestParam(required = false, defaultValue = "") String searchValue){
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("searchValue",searchValue);
        params.put("libId",libId);
        params.put("stat",request.getParameter("stat")==null?"":request.getParameter("stat"));
        params.put("startDate",request.getParameter("startDate")==null?"":request.getParameter("startDate"));
        params.put("endDate",request.getParameter("endDate")==null?"":request.getParameter("endDate"));
        params.put("serviceType",request.getParameter("serviceType")==null?"":request.getParameter("serviceType"));
        params.put("pageSize",pageSize);
        params.put("pageNo",pageNo);
        String classId = request.getParameter("classId")==null?"":request.getParameter("classId");
        params.put("classId",classId);
        Map<String,Object> data = sysCuratorService.studentIndex(libId,params);
        getModel(model,data,params,pageSize,pageNo);
        return "sys/fx/curator/studentIndex";
    }

    @RequestMapping("/teacherIndex")
    public String teacherIndex(Model model, @RequestParam String libId,@RequestParam(required = false, defaultValue = "10") int pageSize,
                               @RequestParam(required = false, defaultValue = "1") int pageNo,@RequestParam(required = false, defaultValue = "") String searchValue){
        String classId = request.getParameter("classId")==null?"":request.getParameter("classId");
        Map<String,Object> data = sysCuratorService.teacherIndex(libId,pageSize,pageNo,searchValue,classId);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("searchValue",searchValue);
        params.put("libId",libId);
        params.put("classId",classId);
        getModel(model,data,params,pageSize,pageNo);
        return "sys/fx/curator/teacherIndex";
    }

    @RequestMapping("/classIndex")
    public String classIndex(Model model, @RequestParam String libId,@RequestParam(required = false, defaultValue = "10") int pageSize,
                               @RequestParam(required = false, defaultValue = "1") int pageNo,@RequestParam(required = false, defaultValue = "") String searchValue){
        String teacherId = request.getParameter("teacherId")==null?"":request.getParameter("teacherId");
        Map<String,Object> data = sysCuratorService.classIndex(libId,pageSize,pageNo,searchValue,teacherId);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("searchValue",searchValue);
        params.put("libId",libId);
        params.put("teacherId",teacherId);
        getModel(model,data,params,pageSize,pageNo);
        return "sys/fx/curator/classIndex";
    }

    @RequestMapping("/homeworkIndex")
    public String homeworkIndex(Model model, @RequestParam String libId,@RequestParam(required = false, defaultValue = "10") int pageSize,
                             @RequestParam(required = false, defaultValue = "1") int pageNo,@RequestParam(required = false, defaultValue = "") String searchValue){
        Map<String, Object> params = new HashMap<String, Object>();
        String queryDate = request.getParameter("queryDate")==null? DateHelper.format(new Date(),"yyyy-MM-dd"):request.getParameter("queryDate");
        String queryEndDate = request.getParameter("queryEndDate")==null? DateHelper.format(new Date(),"yyyy-MM-dd"):request.getParameter("queryEndDate");
        params.put("searchValue",searchValue==null?"":searchValue);
        params.put("queryDate",queryDate);
        params.put("queryEndDate",queryEndDate);
        params.put("libId",libId);
        Map<String,Object> data = sysCuratorService.homeworkIndex(libId,pageSize,pageNo,params);
        getModel(model,data,params,pageSize,pageNo);
        return "sys/fx/curator/homeworkIndex";
    }

    public Model getModel(Model model,Map<String,Object> data,Map<String, Object> params,int pageSize,int pageNo){
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        sp.setRowCnt(Integer.parseInt(data.get("total").toString()));
        model.addAttribute("page", sp);
        model.addAllAttributes(data);
        model.addAttribute("search", params);
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        return  model;
    }

    @RequestMapping("/allLibIndex")
    public String allLibIndex(Model model){
        String queryDate = request.getParameter("queryDate")==null? DateHelper.format(DateUtil.addDays(new Date(),-1),"yyyy-MM-dd"):request.getParameter("queryDate");
        Map<String,Object> data = sysCuratorService.allLibIndex(queryDate);
        model.addAllAttributes(data);
        return "sys/fx/curator/home";
    }

    @RequestMapping(value = "/searchTop")
    @ResponseBody
    public ResponseEntity searchTop(String startDate,String endDate,String  subject,@RequestParam(defaultValue = "1") Integer pageNo,@RequestParam(defaultValue = "10") Integer pageSize) {
        ResponseEntity responseEntity = new ResponseEntity();
        try{
            SplitPage sp = new SplitPage();
            sp.setAction(request.getRequestURI());
            sp.setPageNo(pageNo);
            sp.setPageSize(pageSize);

            Map<String, Object> map=sysCuratorService.searchTop(startDate,endDate,pageNo,pageSize,subject);
            sp.setRowCnt(Integer.parseInt(map.get("total").toString()));
            map.put("listNavigatHtml",sp.getHomeHtml().replace("listData","showTopByUser"));
            responseEntity.success(map,"操作成功");
        }catch (Exception e) {
            e.printStackTrace();
        }
        return responseEntity;
    }

    @RequestMapping(value = "/searchActiveTop")
    @ResponseBody
    public ResponseEntity searchActiveTop(String startDate,String endDate,String  subject,@RequestParam(defaultValue = "1") Integer pageNo,@RequestParam(defaultValue = "10") Integer pageSize) {
        ResponseEntity responseEntity = new ResponseEntity();
        try{
            SplitPage sp = new SplitPage();
            sp.setAction(request.getRequestURI());
            sp.setPageNo(pageNo);
            sp.setPageSize(pageSize);

            Map<String, Object> map=sysCuratorService.searchActiveTop(startDate,endDate,pageNo,pageSize);
            sp.setRowCnt(Integer.parseInt(map.get("total").toString()));
            map.put("listNavigatHtml",sp.getHomeHtml().replace("listData","showTopByActive"));
            responseEntity.success(map,"操作成功");
        }catch (Exception e) {
            e.printStackTrace();
        }
        return responseEntity;
    }

    @RequestMapping(value = "/exportActiveInfo", method = RequestMethod.POST)
    @ResponseBody
    public void exportActiveInfo(Model model, HttpServletRequest request, HttpServletResponse response) {
        String startDate = request.getParameter("startDate")==null?"":request.getParameter("startDate");
        String endDate = request.getParameter("endDate")==null?"":request.getParameter("endDate");
        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");


            int pageSize = 10;
            int pageNo =  -1;
            Map<String, Object> data=sysCuratorService.searchActiveTop(startDate,endDate,pageNo,pageSize);
            List<Map<String, Object>> studentList = (List<Map<String, Object>>)data.get("list");
            //学生数据
            List<ExcelExportEntity> entity = new ArrayList<ExcelExportEntity>();
            entity.add(new ExcelExportEntity("馆名称", "league_name"));
            entity.add(new ExcelExportEntity("模式", "sign_type"));
            entity.add(new ExcelExportEntity("活跃人数", "active_count"));
            entity.add(new ExcelExportEntity("总人数", "all_vips"));
            entity.add(new ExcelExportEntity("百分比(%)", "percent"));
            //把我们构造好的bean对象放到params就可以了
            List<Map<String, Object>> studentList2 = new ArrayList<>();
            studentList2.addAll(studentList);
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(libName, libName, ExcelType.XSSF), entity,
                    studentList2);
            workbook.write(os);
        }catch (IOException e) {
            e.printStackTrace();
        }catch (Exception e1){
            e1.printStackTrace();
        }finally{
            if(os != null){
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    @RequestMapping(value = "/exportInfo", method = RequestMethod.POST)
    @ResponseBody
    public void exportInfo(Model model, HttpServletRequest request, HttpServletResponse response) {
        String startDate = request.getParameter("startDate")==null?"":request.getParameter("startDate");
        String endDate = request.getParameter("endDate")==null?"":request.getParameter("endDate");
        String subject = request.getParameter("type")==null?"":request.getParameter("type");
        ServletOutputStream os = null;
        try {
            String libName= StringUtils.isEmpty(subject)?"上传作业总排行":subject+"作业排行";
            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>();

            int pageSize = 10000;
            int pageNo =  1;
            Map<String, Object> data=sysCuratorService.searchTop(startDate,endDate,pageNo,pageSize,subject);
            List<Map<String, Object>> studentList = (List<Map<String, Object>>)data.get("list");
            //学生数据
            List<ExcelExportEntity> entity = new ArrayList<ExcelExportEntity>();
            entity.add(new ExcelExportEntity("馆名称", "league_name"));
            entity.add(new ExcelExportEntity("作业份数", "totolCount"));
            //把我们构造好的bean对象放到params就可以了
            List<Map<String, Object>> studentList2 = new ArrayList<>();
            studentList2.addAll(studentList);
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(libName, libName, ExcelType.XSSF), entity,
                    studentList2);
            workbook.write(os);
        }catch (IOException e) {
            e.printStackTrace();
        }catch (Exception e1){
            e1.printStackTrace();
        }finally{
            if(os != null){
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @RequestMapping(value = "/exportDetail", method = RequestMethod.POST)
    @ResponseBody
    public void exportDetail(Model model, HttpServletRequest request, HttpServletResponse response) {
        String type = request.getParameter("reportType");
        ServletOutputStream os = null;
        try {
            String libName=type.equals("1")?"学生":type.equals("2")?"老师":"作业";
            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>();

            String libId = request.getParameter("libId");
            int pageSize = request.getParameter("pageSize")==null?1:Integer.parseInt(request.getParameter("pageSize"));
            int pageNo =  request.getParameter("pageNo")==null?1:Integer.parseInt(request.getParameter("pageNo"));
            String searchValue = request.getParameter("searchValue")==null?"":request.getParameter("searchValue");
            String classId = request.getParameter("classId")==null?"":request.getParameter("classId");
            String serviceType = request.getParameter("serviceType") ==null?"":request.getParameter("serviceType");
            if("1".equals(type)){
                params.put("searchValue",request.getParameter("searchValue"));
                params.put("libId",request.getParameter("libId"));
                params.put("startDate",request.getParameter("startDate")==null?"":request.getParameter("startDate"));
                params.put("endDate",request.getParameter("endDate")==null?"":request.getParameter("endDate"));
                params.put("stat",request.getParameter("stat")==null?"":request.getParameter("stat"));
                params.put("classId",classId);
                params.put("serviceType",serviceType);
                params.put("pageSize",1);
                params.put("pageNo",1);
                Map<String,Object> data = sysCuratorService.studentIndex(request.getParameter("libId"),params);
                params.put("pageSize",data.get("total"));
                data = sysCuratorService.studentIndex(request.getParameter("libId"),params);
                List<Map<String, Object>> studentList = (List<Map<String, Object>>)data.get("list");

                //学生数据
                List<ExcelExportEntity> entity = new ArrayList<ExcelExportEntity>();
                //构造对象等同于@Excel
                ExcelExportEntity excelentity0 = new ExcelExportEntity("学生姓名", "childName");
                excelentity0.setNeedMerge(true);
                entity.add(excelentity0);
                ExcelExportEntity excelentity = new ExcelExportEntity("班级名称", "className");
                excelentity.setNeedMerge(true);
                entity.add(excelentity);
                ExcelExportEntity excelentity2 = new ExcelExportEntity("年级", "grade");
                excelentity2.setNeedMerge(true);
                entity.add(excelentity2);
                ExcelExportEntity excelentity6 = new ExcelExportEntity("电话", "phone");
                excelentity6.setNeedMerge(true);
                entity.add(excelentity6);
                ExcelExportEntity excelentity5 = new ExcelExportEntity(null, "serviceList");
                List<ExcelExportEntity> temp = new ArrayList<ExcelExportEntity>();
                temp.add(new ExcelExportEntity("服务开始时间", "start_time"));
                temp.add(new ExcelExportEntity("服务结束时间", "end_time"));
                temp.add(new ExcelExportEntity("是否有效", "stat"));
                temp.add(new ExcelExportEntity("服务类型", "correct_type"));
                //构造List等同于@ExcelCollection
                excelentity5.setList(temp);
                entity.add(excelentity5);
                //把我们构造好的bean对象放到params就可以了
                List<Map<String, Object>> studentList2 = new ArrayList<>();
                studentList2.addAll(studentList);
                Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(libName, libName, ExcelType.XSSF), entity,
                        studentList2);
                workbook.write(os);
            }else if("2".equals(type)){
                //老师数据
                Map<String,Object> data = sysCuratorService.teacherIndex(libId,pageSize,pageNo,searchValue,classId);
                pageSize = Integer.parseInt(data.get("total").toString());
                data = sysCuratorService.teacherIndex(libId,pageSize,pageNo,searchValue,classId);
                List<ExcelExportEntity> entity = new ArrayList<ExcelExportEntity>();
                entity.add(new ExcelExportEntity("老师姓名","name"));
                entity.add(new ExcelExportEntity("科目","subject"));
                entity.add(new ExcelExportEntity("模块","teacherTypeValues"));
                entity.add(new ExcelExportEntity("班级数","classSum"));
                entity.add(new ExcelExportEntity("电话号码","phone"));
                //把我们构造好的bean对象放到params就可以了
                List<CuratorTeacherListDto> teacherList = (List<CuratorTeacherListDto>)data.get("list");

                List<Map<String, Object>> teacherListNew = dtoToMap(teacherList);

                Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(libName, libName, ExcelType.XSSF), entity,
                        teacherListNew);
                workbook.write(os);
            }else{
                String queryDate = request.getParameter("queryDate")==null? DateHelper.format(new Date(),"yyyy-MM-dd"):request.getParameter("queryDate");
                String queryEndDate = request.getParameter("queryEndDate")==null? DateHelper.format(new Date(),"yyyy-MM-dd"):request.getParameter("queryEndDate");
                params.put("queryEndDate",queryEndDate);
                params.put("queryDate",queryDate);
                params.put("libId",request.getParameter("libId"));
                params.put("searchValue",searchValue);
                Map<String,Object> data = sysCuratorService.homeworkIndex(libId,pageSize,pageNo,params);
                pageSize =Integer.parseInt(data.get("total").toString());
                data = sysCuratorService.homeworkIndex(libId,pageSize,pageNo,params);
                List<Map<String, Object>> homeworkList = (List<Map<String, Object>>)data.get("list");
                List<ExcelExportEntity> entity = new ArrayList<ExcelExportEntity>();
                entity.add(new ExcelExportEntity("学生名称","child_name"));
                entity.add(new ExcelExportEntity("年级","grade"));
                entity.add(new ExcelExportEntity("学校","school"));
                entity.add(new ExcelExportEntity("绑定校区","league_name"));
                entity.add(new ExcelExportEntity("作业日期","create_time"));
                entity.add(new ExcelExportEntity("上传作业份数","pictureCount"));
                entity.add(new ExcelExportEntity("语文作业份数","count1"));
                entity.add(new ExcelExportEntity("数学作业份数","count2"));
                entity.add(new ExcelExportEntity("英语作业份数","count3"));
                entity.add(new ExcelExportEntity("批改作业份数","correctedCount"));
                List<Map<String, Object>> studentList2 = new ArrayList<>();
                studentList2.addAll(homeworkList);
                Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(libName, libName, ExcelType.XSSF), entity,
                        studentList2);
                workbook.write(os);
            }

        }catch (IOException e) {
            e.printStackTrace();
        }catch (Exception e1){
            e1.printStackTrace();
        }finally{
            if(os != null){
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private  List<Map<String, Object>> dtoToMap(List<CuratorTeacherListDto> teacherList){
        if(Collections3.isEmpty(teacherList)){
            return  new ArrayList<>();
        }
        List<Map<String, Object>> list = new ArrayList<>();
        for (CuratorTeacherListDto dto:teacherList){
            Map<String, Object> map = new HashMap<>();
            map.put("name",dto.getName());
            map.put("subject",dto.getSubject());
            List<String> teacherTypeList = dto.getTeacherTypeList();
            if(Collections3.isEmpty(teacherTypeList)){
                map.put("teacherTypeList","");
            }else{
                String teacherTypeValues = "";
                for (String str:teacherTypeList){
                    if(str.equals("2")){
                        teacherTypeValues+="现场管理、";
                    }else if(str.equals("3")){
                        teacherTypeValues+="学科答疑、";
                    }else{
                        teacherTypeValues+="作业标注";
                    }
                }
                if(teacherTypeValues.endsWith("、")){
                    teacherTypeValues = teacherTypeValues.substring(0,teacherTypeValues.length()-1);
                }
                map.put("teacherTypeValues",teacherTypeValues);
            }
            map.put("classSum",dto.getClassSum());
            map.put("phone",dto.getPhone());
            list.add(map);
        }
        return  list;
    }
    
    
    
    @RequestMapping("/homeworkInfoVip")
    public String homeworkInfoVip(Model model,
    		@RequestParam String vipId,
    		@RequestParam String subject,
    		@RequestParam String queryDate){
        CorrectDetailDto4 correctDetail = parentService.correctDetail4(vipId, subject,queryDate);
        model.addAttribute("correctDetail", correctDetail);
        return "sys/fx/curator/homeworkInfoVip";
    }
    
    
    
}
