package com.unis.base.server.controller;

import com.github.pagehelper.PageInfo;
import com.unis.base.common.vo.*;
import com.unis.base.server.service.PersonnelMxService;
import com.unis.base.server.service.TalentGroupService;
import com.unis.common.utils.ResponseWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/TalentGroup")
@Api(value = "人才组管理", tags = "人才组管理")
@Slf4j
public class TalentGroupController {
    @Autowired
    private TalentGroupService talentGroupService;
    @Autowired
    private PersonnelMxService personnelMxService;

    @ApiOperation(value = "新增人才组")
    @PostMapping(value = "/addOrganization")
    public ResponseWrapper addOrganization(@RequestBody GroupVO groupVO) {
        try {
            talentGroupService.addOrganization(groupVO);
            return ResponseWrapper.success(HttpStatus.OK.value(), "新增成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), "人才组名称重复!");
    }

    @ApiOperation(value = "人才组分页")
    @PostMapping(value = "/organization")
    public ResponseWrapper organization(@RequestParam("groupName") String groupName,
                                        @RequestParam("pageNum") Integer pageNum,
                                        @RequestParam("pageSize") Integer pageSize) {
        try {
            PageInfo<GroupVO> voPageInfo = talentGroupService.organization(groupName, pageNum, pageSize);
            return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), voPageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), "服务错误，请联系管理员");
    }

    @ApiOperation(value = "人才组详情")
    @PostMapping(value = "/seeOrganization")
    public ResponseWrapper seeOrganization(@RequestParam("groupId") String groupId,
                                           @RequestParam("pageNum") Integer pageNum,
                                           @RequestParam("pageSize") Integer pageSize) {
        try {
            PageInfo<GroupPersonSVO> voPageInfo = talentGroupService.seeOrganization(groupId, pageNum, pageSize);
            return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), voPageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), "服务错误，请联系管理员");
    }

    @ApiOperation(value = "人员信息详情")
    @PostMapping(value = "/seePersonOrganization")
    public ResponseWrapper seePersonOrganization(@RequestParam("rybh") String rybh) {
        try {
            PersonnelMxVO pagePersonnelVOS = talentGroupService.catchPersonnelHDetails(rybh);
            return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), pagePersonnelVOS);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), "服务错误，请联系管理员");
    }

    @ApiOperation(value = "人员信息导出")
    @PostMapping(value = "/personexport")
    public ResponseWrapper personexport(HttpServletResponse response,
                                        @RequestParam("groupId") String groupId) {
        try {
            List<GroupPersonSVO> pagePersonnelVOS = talentGroupService.personexport(groupId);
            //fileName导出文件名
//            if (pagePersonnelVOS.size() == 0) {
//                return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), "导出数据为空");
//            }
            String fileName;
            String sheetName;
            if (pagePersonnelVOS.size() == 0) {
                fileName = "人员信息.xls";
                sheetName = "人员信息";
            } else {
                fileName = pagePersonnelVOS.get(0).getQymc() + "人员信息.xls";
                sheetName = pagePersonnelVOS.get(0).getQymc() + "人员信息";
            }
            //headMap表头Map, key为属性名, value为展示名,根据实际情况修改
            // 设置响应类型和编码
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            Workbook workbook = new XSSFWorkbook();
            // 创建单个工作表并填充数据
            Sheet sheet = workbook.createSheet(sheetName);
            Font font = workbook.createFont();
            font.setFontName("宋体");
            font.setFontHeightInPoints((short) 14);

            // 创建标题行
            // 姓名 单位/企业名称 岗位 全日制学历 职业资格证书名称
            Row firstTitleRow = sheet.createRow(0);
            CellStyle headerStyle = workbook.createCellStyle();
            headerStyle.setAlignment(HorizontalAlignment.CENTER);
            headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            headerStyle.setWrapText(true);
            headerStyle.setFont(font);
            headerStyle.setBorderBottom(BorderStyle.THIN); // 下边框
            headerStyle.setBorderLeft(BorderStyle.THIN); // 左边框
            headerStyle.setBorderTop(BorderStyle.THIN); // 上边框
            headerStyle.setBorderRight(BorderStyle.THIN); // 右边框

            Cell cell = firstTitleRow.createCell(0);
            cell.setCellValue("姓名");
            cell.setCellStyle(headerStyle);
            sheet.setColumnWidth(0, 32 * 256);
            cell = firstTitleRow.createCell(1);
            cell.setCellValue("单位/企业名称");
            cell.setCellStyle(headerStyle);
            cell = firstTitleRow.createCell(2);
            sheet.setColumnWidth(1, 32 * 256);
            cell.setCellValue("岗位");
            cell.setCellStyle(headerStyle);
            cell = firstTitleRow.createCell(3);
            sheet.setColumnWidth(2, 32 * 256);
            cell.setCellValue("全日制学历");
            cell.setCellStyle(headerStyle);
            cell = firstTitleRow.createCell(4);
            sheet.setColumnWidth(3, 32 * 256);
            cell.setCellValue("职业资格证书名称");
            cell.setCellStyle(headerStyle);
            sheet.setColumnWidth(4, 32 * 256);

            // 插入数据
            int rowIndex = 1;
            // 创建单元格样式，并设置水平居中
            Font font1 = workbook.createFont();
            font1.setFontName("宋体");
            font1.setFontHeightInPoints((short) 11);
            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            cellStyle.setFont(font1);
            cellStyle.setBorderBottom(BorderStyle.THIN);
            cellStyle.setBorderTop(BorderStyle.THIN);
            cellStyle.setBorderRight(BorderStyle.THIN);
            cellStyle.setBorderLeft(BorderStyle.THIN);

            for (GroupPersonSVO pagePersonnelVO : pagePersonnelVOS) {
                Row row = sheet.createRow(rowIndex);
                Cell cell1 = row.createCell(0);
                cell1.setCellValue(pagePersonnelVO.getRyxm());
                cell1.setCellStyle(cellStyle);
                cell1 = row.createCell(1);
                cell1.setCellValue(pagePersonnelVO.getQymc());
                cell1.setCellStyle(cellStyle);
                cell1 = row.createCell(2);
                cell1.setCellValue(pagePersonnelVO.getZwmc());
                cell1.setCellStyle(cellStyle);
                cell1 = row.createCell(3);
                cell1.setCellValue(StringUtils.isNotBlank(pagePersonnelVO.getXw()) ? getFullTimeEducation(pagePersonnelVO.getXw()) : "");
                cell1.setCellStyle(cellStyle);
                cell1 = row.createCell(4);
                cell1.setCellValue(pagePersonnelVO.getRych());
                cell1.setCellStyle(cellStyle);
                rowIndex++;
            }
            // 将工作簿写入输出流
            workbook.write(response.getOutputStream());
            workbook.close();
            return ResponseWrapper.success("导出成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ResponseWrapper.error("导出失败！");
        }
    }

    // 全日制学历字典翻译方法
    private String getFullTimeEducation(String dictCode) {
        switch (dictCode) {
            case "40":
                return "高中";
            case "41":
                return "中专";
            case "42":
                return "大专";
            case "43":
                return "本科";
            case "44":
                return "研究生";
            case "45":
                return "博士";
            case "46":
                return "博士后";
            default:
                return "";
        }
    }


    @ApiOperation(value = "部门层级")
    @PostMapping(value = "/getPageSDetails")
    public ResponseWrapper getPageSDetails() {
        try {
            List<GetPagePersonnelVO> pagePersonnelVOS = talentGroupService.pageSDetails();
            return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), pagePersonnelVOS);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), "服务错误，请联系管理员");
    }

    @ApiOperation(value = "人员层级")
    @PostMapping(value = "/getPpersonDetails")
    public ResponseWrapper getPpersonDetails(@RequestBody UserQueryVo userQueryVo) {
        try {
            PageInfo<PersonnelMxVO> pageInfos = talentGroupService.getPpersonDetails(userQueryVo);
            return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), pageInfos);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), "服务错误，请联系管理员");
    }

    @ApiOperation(value = "根据人员获取人员信息")
    @PostMapping(value = "/seeAndPersonOrganization")
    public ResponseWrapper seeAndPersonOrganization(@RequestBody GroupMainVo viewObj) {
        try {
            List<GroupPersonVO> groupPersonVOList = talentGroupService.seeAndPersonOrganization(viewObj);
            return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), groupPersonVOList);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), "服务错误，请联系管理员");
    }

    @ApiOperation(value = "新增人才组信息", notes = "")
    @PostMapping(value = "/info")
    public ResponseWrapper insertInfo(@RequestBody GroupMainVo viewObj) {
        try {
            talentGroupService.insertInfo(viewObj);
            return ResponseWrapper.success("新增成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
        return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "插入信息失败", null);
    }

    @ApiOperation(value = "删除人才组信息", notes = "")
    @PostMapping(value = "/deleteinfo")
    public ResponseWrapper deleteInfo(@RequestParam("groupId") String groupId) {
        try {
            talentGroupService.deleteInfo(groupId);
            return ResponseWrapper.success("删除成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
        return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "删除失败", null);
    }

    @ApiOperation(value = "删除人才组人员信息", notes = "")
    @PostMapping(value = "/deletePersonInfo")
    public ResponseWrapper deletePersonInfo(@RequestParam("userId") String userId,
                                            @RequestParam("groupId") String groupId) {
        try {
            talentGroupService.deletePersonInfo(userId, groupId);
            return ResponseWrapper.success("删除成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
        return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "删除失败", null);
    }
}
