package com.ym.mec.web.controller;

import com.ym.mec.biz.dal.dao.InspectionItemPlanDao;
import com.ym.mec.biz.dal.entity.InspectionItemPlan;
import com.ym.mec.biz.service.InspectionItemPlanConclusionService;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.entity.HttpResponseResult;
import com.ym.mec.util.date.DateUtil;
import com.ym.mec.util.excel.POIUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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

@Api(tags = "巡查结果")
@RequestMapping("inspectionItemPlanConclusion")
@RestController
public class InspectionItemPlanConclusionController extends BaseController {
    @Autowired
    private InspectionItemPlanConclusionService InspectionItemPlanConclusionService;
    @Autowired
    private InspectionItemPlanDao inspectionItemPlanDao;

    @ApiOperation(value = "获取日程的巡查结果")
    @GetMapping("/getPlanConclusion")
    @PreAuthorize("@pcs.hasPermissions('inspectionItemPlanConclusion/getPlanConclusion')")
    @ApiImplicitParams({@ApiImplicitParam(name = "planId", value = "日程id", required = true, dataType = "int")})
    public HttpResponseResult<List<Map<String, String>>> getPlanConclusion(Long planId) {
        return succeed(InspectionItemPlanConclusionService.getPlanConclusion(planId));
    }

    @ApiOperation(value = "导出日程的巡查结果")
    @GetMapping("/exportPlanConclusion")
    @PreAuthorize("@pcs.hasPermissions('inspectionItemPlanConclusion/exportPlanConclusion')")
    @ApiImplicitParams({@ApiImplicitParam(name = "planId", value = "日程id", required = true, dataType = "int")})
    public void exportPlanConclusion(Long planId, HttpServletResponse response) throws Exception {
        List<Map<String, String>> conclusions = InspectionItemPlanConclusionService.getPlanConclusion(planId);
        if (conclusions.size() <= 0) {
            response.setStatus(200);
            response.setContentType("Content-Type: application/json;charset=UTF-8");
            response.getOutputStream().write("{\"data\": null, \"code\": 500, \"status\": false, \"msg\": \"没有可导出的记录\"}".getBytes());
            response.flushBuffer();
            return;
        }
        OutputStream outputStream = response.getOutputStream();
        try {
            conclusions.forEach(conclusionMap -> {
                conclusionMap.forEach((key, val) -> {
                    if (val.equals("1")) {
                        conclusionMap.put(key, "√");
                    } else if (val.equals("0")) {
                        conclusionMap.put(key, "×");
                    }
                });
            });

            List<String> bodyList = new LinkedList<>();
            conclusions.get(0).forEach((key, vak) -> {
                bodyList.add(key);
            });
            InspectionItemPlan planInfo = inspectionItemPlanDao.getPlanInfo(planId);
            String dateTime = DateUtil.dateToString(planInfo.getPlanStart(), "yyyy-MM-dd") + " " + DateUtil.dateToString(planInfo.getPlanStart(), "HH:mm") + "~" + DateUtil.dateToString(planInfo.getPlanEnd(), "HH:mm");
            String[] header = {"所属分部", planInfo.getOrganName(), "", "合作单位", planInfo.getCooperationName(), "", "巡查乐团", planInfo.getMusicGroupName(), "", "", "", "", "", "", "", ""};
            String[] header1 = {"乐团主管", planInfo.getRealName(), "", "巡查时间", dateTime, "", "提交时间", DateUtil.dateToString(planInfo.getSubmitedTime(), "yyyy-MM-dd HH:mm"), "", "", "", "", "", "", ""};
            String[] header2 = {"处理方式", planInfo.getMemo(), "", "", "", "", "", "", "", "", "", "", "", "", "", ""};
            String[] header3 = {"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""};
            String[] header4 = {"巡查项目", "课前管理", "", "", "", "", "课中管理", "", "", "", "", "", "", "课后管理", "", ""};
            String[] header5 = {"", "老师是否提前准备板书（本课内容、作业）", "老师是否佩戴工牌", "老师是否仪容仪表整洁", "老师是否携带乐器", "老师是否携带教学资料、设备", "老师是否合理安排学员座位", "乐器箱包、书包是否摆放整齐", "课堂纪律是否保持良好", "老师是否全程站立教学", "老师是否全程使用节拍器或教学音频", "未发现私换乐器", "老师是否将上课照片/视频发送到声部群", "老师是否保持教室环境卫生", "老师是否关好所有电源、门窗", "老师是否有序组织学员放学"};

            List<String[]> headers = new LinkedList<>();
            headers.add(header);
            headers.add(header1);
            headers.add(header2);
            headers.add(header3);
            headers.add(header4);
            headers.add(header5);

            String[] body = bodyList.toArray(new String[bodyList.size()]);


            HSSFWorkbook workbook = POIUtil.multipleHeaderExportExcel(headers, body, conclusions);
            //合并单元格处理
            CellRangeAddressList cellRangeAddressList = new CellRangeAddressList();
            cellRangeAddressList.addCellRangeAddress(0, 1, 0, 2);
            cellRangeAddressList.addCellRangeAddress(0, 4, 0, 5);
            cellRangeAddressList.addCellRangeAddress(0, 7, 0, 8);
            cellRangeAddressList.addCellRangeAddress(1, 1, 1, 2);
            cellRangeAddressList.addCellRangeAddress(1, 4, 1, 5);
            cellRangeAddressList.addCellRangeAddress(1, 7, 1, 8);
            cellRangeAddressList.addCellRangeAddress(2, 1, 2, 2);
            cellRangeAddressList.addCellRangeAddress(2, 3, 2, 8);
            cellRangeAddressList.addCellRangeAddress(3, 0, 3, 15);
            cellRangeAddressList.addCellRangeAddress(4, 0, 5, 0);
            cellRangeAddressList.addCellRangeAddress(4, 1, 4, 5);
            cellRangeAddressList.addCellRangeAddress(4, 6, 4, 12);
            cellRangeAddressList.addCellRangeAddress(4, 13, 4, 15);

            for (CellRangeAddress cellRangeAddress : cellRangeAddressList.getCellRangeAddresses()) {
                workbook.getSheetAt(0).addMergedRegion(cellRangeAddress);
            }

            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=conclusion-" + DateUtil.getDate(new Date()) + ".xls");
            response.flushBuffer();
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
