package com.bonus.system.holiday.controller;

import com.bonus.common.core.utils.StringHelper;
import com.bonus.common.core.utils.poi.ExcelUtil;
import com.bonus.common.core.utils.poi.MultiSheetExcelExporter;
import com.bonus.common.core.web.controller.BaseController;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.core.web.page.TableDataInfo;
import com.bonus.common.log.annotation.Log;
import com.bonus.common.log.annotation.SysLog;
import com.bonus.common.log.enums.BusinessType;
import com.bonus.common.log.enums.OperaType;
import com.bonus.common.security.annotation.RequiresPermissions;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.system.holiday.entity.HolidayBean;
import com.bonus.system.holiday.entity.WorkReportBean;
import com.bonus.system.holiday.service.HolidayService;
import com.bonus.system.holiday.service.WorkReportService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 工作安排统计报表
 * @author hay
 */
@RestController
@RequestMapping("/workReport")
@Slf4j
public class WorkReportController extends BaseController {

    @Resource(name = "WorkReportService")
    private WorkReportService service;

    /**
     * 获取列表
     */
    @RequiresPermissions("flow:workReport:list")
    @GetMapping("/list")
    @Log(title = "流程管理->工作安排统计报表->列表查询", businessType = BusinessType.QUERY)
    public TableDataInfo list(WorkReportBean bean) {
        try{
            startPage();
            return getDataTable(service.getWorkReportList(bean));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return getDataTableError(new ArrayList<>());
    }

    @PostMapping("/getDetailsList")
    @Log(title = "流程管理->工作安排统计报表->详情查询", businessType = BusinessType.QUERY)
    public TableDataInfo getDetailsList(WorkReportBean bean) {
        try{
            startPage();
            return getDataTable(service.getDetailsList(bean));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return getDataTableError(new ArrayList<>());
    }

    @PostMapping("/setCheck")
    @Log(title = "流程管理->工作安排统计报表->详情查询", businessType = BusinessType.QUERY)
    public AjaxResult setCheck(WorkReportBean bean) {
        try{
            int res = service.setCheck(bean);
            return toAjax(res);
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    /**
     * 新增假期
     */
//    @RequiresPermissions("flow:holiday:add")
    @PostMapping
    @Log(title = "流程管理->假期管理->新增假期", businessType = BusinessType.INSERT)
    public AjaxResult add(@Validated @RequestBody HolidayBean o) {
        try{
            int res = service.insertHoliday(o);
            return toAjax(res);
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }


    @GetMapping("/export")
    @SysLog(title = "工作安排统计报表", businessType = OperaType.EXPORT,module = "工作安排统计报表")
    public void export(HttpServletResponse response, WorkReportBean bean) {
        try {
            //先查询工作安排统计报表列表数据
            List<WorkReportBean> list = service.getWorkReportList(bean);
            //轮休数据
            List<WorkReportBean> listLeave=new ArrayList<>();
            //临时外出数据
            List<WorkReportBean> listOut=new ArrayList<>();
            //出差数据
            List<WorkReportBean> listBusiness=new ArrayList<>();
            //请假数据
            List<WorkReportBean> listHoliday=new ArrayList<>();
            MultiSheetExcelExporter exporter = new MultiSheetExcelExporter();
            // 创建第一个sheet：员工信息
            Sheet employeeSheet = exporter.createSheet("工作安排统计报表");
            List<String> employeeHeaders = Arrays.asList("序号", "月份", "部门名称", "轮休人数", "临时外出人数", "出差人数", "请假人数", "状态");
            exporter.addHeaderRow(employeeSheet, employeeHeaders);

            List<Map<String, Object>> employeeData = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> map = new LinkedHashMap<>();
                map.put("序号", i + 1);
                map.put("月份", list.get(i).getMonth());
                map.put("部门名称", list.get(i).getOrgName());
                map.put("轮休人数", list.get(i).getLeaveNum());
                map.put("临时外出人数", list.get(i).getOutNum());
                map.put("出差人数", list.get(i).getBusinessTripNum());
                map.put("请假人数", list.get(i).getHolidayNum());
                map.put("状态", list.get(i).getStatus() != null ? "已核对" : "未处理");
               employeeData.add(map);

                //查询轮休人员
                WorkReportBean bean1 = new WorkReportBean();
                bean1.setMonth(list.get(i).getMonth());
                bean1.setOrgId(list.get(i).getOrgId());
                bean1.setType("轮休");
                List<WorkReportBean> list1 = service.getDetailsList(bean1);
                listLeave.addAll(list1);

                //查询临时外出人员
                WorkReportBean bean2 = new WorkReportBean();
                bean2.setMonth(list.get(i).getMonth());
                bean2.setOrgId(list.get(i).getOrgId());
                bean2.setType("临时外出");
                List<WorkReportBean> list2 = service.getDetailsList(bean2);
                listOut.addAll(list2);

                //查询出差人员
                WorkReportBean bean3 = new WorkReportBean();
                bean3.setMonth(list.get(i).getMonth());
                bean3.setOrgId(list.get(i).getOrgId());
                bean3.setType("出差");
                List<WorkReportBean> list3 = service.getDetailsList(bean3);
                listBusiness.addAll(list3);

                //查询请假人员
                WorkReportBean bean4 = new WorkReportBean();
                bean4.setMonth(list.get(i).getMonth());
                bean4.setOrgId(list.get(i).getOrgId());
                bean4.setType("请假");
                List<WorkReportBean> list4 = service.getDetailsList(bean4);
                listHoliday.addAll(list4);
            }
            exporter.addDataRows(employeeSheet, employeeData, employeeHeaders);

            // 创建第二个sheet：部门信息
            Sheet departmentSheet = exporter.createSheet("轮休人员");
            List<String> departmentHeaders = Arrays.asList("序号", "姓名", "职务", "所属部门", "申请时间", "开始时间", "结束时间", "时长（天）","审批状态");
            exporter.addHeaderRow(departmentSheet, departmentHeaders);
            List<Map<String, Object>> departmentData = new ArrayList<>();
            for (int i = 0; i < listLeave.size(); i++) {
                Map<String, Object> map = new LinkedHashMap<>();
                map.put("序号", i + 1);
                map.put("姓名", listLeave.get(i).getUserName());
                map.put("职务", listLeave.get(i).getPostName());
                map.put("所属部门", listLeave.get(i).getOrgName());
                map.put("申请时间",listLeave.get(i).getCreateTime());
                map.put("开始时间",listLeave.get(i).getStartDate());
                map.put("结束时间",listLeave.get(i).getEndDate());
                map.put("时长（天）",listLeave.get(i).getLeaveDuration());
                if (StringHelper.isNotEmpty(listLeave.get(i).getExamineStatus())){
                    if ("1".equals(listLeave.get(i).getExamineStatus())){
                        map.put("审批状态","已通过");
                    } else if ("0".equals(listLeave.get(i).getExamineStatus())){
                        map.put("审批状态","待审核");
                    }
                }else {
                    map.put("审批状态","");
                }
                departmentData.add(map);
            }
            exporter.addDataRows(departmentSheet, departmentData, departmentHeaders);

            // 创建第3个sheet：部门信息
            Sheet departmentSheet3 = exporter.createSheet("临时外出人员");
            List<String> departmentHeaders3 = Arrays.asList("序号", "姓名", "职务", "所属部门", "申请时间", "开始时间", "结束时间", "时长（天）","审批状态");
            exporter.addHeaderRow(departmentSheet3, departmentHeaders3);
            List<Map<String, Object>> departmentData3 = new ArrayList<>();
            for (int i = 0; i < listOut.size(); i++) {
                Map<String, Object> map = new LinkedHashMap<>();
                map.put("序号", i + 1);
                map.put("姓名", listOut.get(i).getUserName());
                map.put("职务", listOut.get(i).getPostName());
                map.put("所属部门", listOut.get(i).getOrgName());
                map.put("申请时间",listOut.get(i).getCreateTime());
                map.put("开始时间",listOut.get(i).getStartDate());
                map.put("结束时间",listOut.get(i).getEndDate());
                map.put("时长（天）",listOut.get(i).getLeaveDuration());
                if (StringHelper.isNotEmpty(listOut.get(i).getExamineStatus())){
                    if ("1".equals(listOut.get(i).getExamineStatus())){
                        map.put("审批状态","已通过");
                    } else if ("0".equals(listOut.get(i).getExamineStatus())){
                        map.put("审批状态","待审核");
                    }
                }else {
                    map.put("审批状态","");
                }
                departmentData3.add(map);
            }
            exporter.addDataRows(departmentSheet3, departmentData3,departmentHeaders3);

            // 创建第4个sheet：部门信息
            Sheet departmentSheet4 = exporter.createSheet("出差人员");
            List<String> departmentHeaders4 = Arrays.asList("序号", "姓名", "职务", "所属部门", "申请时间", "开始时间", "结束时间", "时长（天）");
            exporter.addHeaderRow(departmentSheet4, departmentHeaders4);
            List<Map<String, Object>> departmentData4 = new ArrayList<>();
            for (int i = 0; i < listBusiness.size(); i++) {
                Map<String, Object> map = new LinkedHashMap<>();
                map.put("序号", i + 1);
                map.put("姓名", listBusiness.get(i).getUserName());
                map.put("职务", listBusiness.get(i).getPostName());
                map.put("所属部门", listBusiness.get(i).getOrgName());
                map.put("申请时间",listBusiness.get(i).getCreateTime());
                map.put("开始时间",listBusiness.get(i).getStartDate());
                map.put("结束时间",listBusiness.get(i).getEndDate());
                map.put("时长（天）",listBusiness.get(i).getLeaveDuration());
                departmentData4.add(map);
            }
            exporter.addDataRows(departmentSheet4, departmentData4, departmentHeaders4);

            // 创建第5个sheet：部门信息
            Sheet departmentSheet5 = exporter.createSheet("请假人员");
            List<String> departmentHeaders5 = Arrays.asList("序号", "姓名", "职务", "所属部门", "申请时间", "开始时间", "结束时间", "时长（天）");
            exporter.addHeaderRow(departmentSheet5, departmentHeaders5);
            List<Map<String, Object>> departmentData5 = new ArrayList<>();
            for (int i = 0; i < listHoliday.size(); i++) {
                Map<String, Object> map = new LinkedHashMap<>();
                map.put("序号", i + 1);
                map.put("姓名", listHoliday.get(i).getUserName());
                map.put("职务", listHoliday.get(i).getPostName());
                map.put("所属部门", listHoliday.get(i).getOrgName());
                map.put("申请时间",listHoliday.get(i).getCreateTime());
                map.put("开始时间",listHoliday.get(i).getStartDate());
                map.put("结束时间",listHoliday.get(i).getEndDate());
                map.put("时长（天）",listHoliday.get(i).getLeaveDuration());
                departmentData5.add(map);
            }
            exporter.addDataRows(departmentSheet5, departmentData5,departmentHeaders5);

            // 导出Excel文件
            exporter.exportToResponse(response, "工作安排统计报表");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
