package com.jeeplus.human.enrollment.enrollmentRegistration.controller;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.jeeplus.common.constant.CacheNames;
import com.jeeplus.common.excel.EasyExcelUtils;
import com.jeeplus.common.excel.ExcelOptions;
import com.jeeplus.common.excel.annotation.ExportMode;
import com.jeeplus.common.redis.RedisUtils;
import com.jeeplus.common.utils.ResponseUtil;
import com.jeeplus.human.depart.handover.domain.Handover;
import com.jeeplus.human.depart.handover.service.HandoverService;
import com.jeeplus.human.enrollment.enrollmentRegistration.domain.*;
import com.jeeplus.human.enrollment.enrollmentRegistration.service.*;
import com.jeeplus.human.enrollment.enrollmentRegistration.service.dto.DownloadAttachmentDTO;
import com.jeeplus.human.enrollment.enrollmentRegistration.service.dto.ExportDTO;
import com.jeeplus.human.enrollment.enrollmentRegistration.service.dto.UserTemplate;
import com.jeeplus.human.enrollment.enrollmentRegistration.utils.DingTalkSyncUtil;
import com.jeeplus.human.enrollment.enrollmentRegistration.utils.EasyPoiUtil;
import com.jeeplus.logging.annotation.ApiLog;
import com.jeeplus.logging.constant.enums.LogTypeEnum;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.utils.StringUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 王强
 * @version 1.0
 * @date 2023-09-27 14:14
 */
@Slf4j
@RestController
@Api("实习人员登记表信息")
@RequestMapping(value = "/enrollmentRegistration")
public class EnrollmentRegistrationController {

    @Resource
    private EnrollmentRegistrationService service;

    @Resource
    private EnrollmentEduInfoService eduInfoService;

    @Resource
    private EnrollmentSocialSecurityCardService securityCardService;

    @Resource
    private EnrollmentKeyCardService keyCardService;

    @Resource
    private EnrollmentRiceCardService riceCardService;

    @Resource
    private HandoverService handoverService;

    @Resource
    private EnrollmentWageCardService wageCardService;
    @Resource
    private DingTalkSyncUtil dingTalkSyncUtil;

    @Resource
    private EnrollmentUserInfoAuditService userInfoAuditService;

    /**
     * 下载门禁卡开通注意事项
     * @param response
     */
    @RequestMapping(value="downloadFile")
    @ResponseBody
    public void downloadFile(HttpServletResponse response)  {


        //模板对象
        Template template=null;
        //下载文件地址
        String filePath = null;
        if(System.getProperty("os.name").toLowerCase().contains("win")){
            filePath = this.getClass().getResource("/").getPath()+"/freemarker";
        }else{
            filePath = "/mnt/project/cloud/freemarker";
        }
        //freemaker模板路径
        File path = new File(filePath);

        Configuration cfg = new Configuration();
        try {
            cfg.setDirectoryForTemplateLoading(path);
            //选择对应的ftl文件
            template = cfg.getTemplate("firstAudit.ftl","UTF-8");

            File docFile = new File("门禁卡开通注意事项.doc");
            com.jeeplus.human.enrollment.enrollmentRegistration.utils.ResponseUtil.docResponse("门禁卡开通注意事项.doc",docFile,response);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

            if(System.getProperty("os.name").toLowerCase().contains("win")){
                //获取tomcat的路径
                String tomcatFilePath=System.getProperty("catalina.home");
                //删除tomcat目录下的处理后的文件信息
                File tomcatFile = new File(tomcatFilePath+"/bin/"+"门禁卡开通注意事项.doc");
                if (tomcatFile.isFile()) {
                    tomcatFile.delete();
                }
            }else{
                //删除目录下的处理后的文件信息
                File tomcatFile = new File("/mnt/project/cloud/"+"门禁卡开通注意事项.doc");
                if (tomcatFile.isFile()) {
                    tomcatFile.delete();
                }
            }
        }

    }

    /**
     * 下载离职证明
     * @param response
     */
    @RequestMapping(value="downloadDepartFile")
    @ResponseBody
    public void downloadDepartFile(HttpServletResponse response,String handoverId)  {

        //根据离职交接表id获取  离职证明文件路径信息
        Handover handover = handoverService.getById(handoverId);

        //下载文件地址
        String filePath = handover.getWordFilePath();

        try {
            File docFile = new File(filePath);
            if (docFile.exists()) {
                // 设置响应头部信息
                response.setContentType("application/pdf");
                response.setHeader("Content-Disposition", "attachment; filename=" + docFile.getName());
                response.setContentLength((int) docFile.length());

                // 读取文件内容并写入响应输出流
                FileInputStream fis = new FileInputStream(docFile);
                BufferedInputStream bis = new BufferedInputStream(fis);
                ServletOutputStream sos = response.getOutputStream();

                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = bis.read(buffer, 0, 1024)) != -1) {
                    sos.write(buffer, 0, bytesRead);
                }

                sos.flush();
                sos.close();
                bis.close();
                fis.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询入职人员登记信息列表
     * @param projectReportData
     * @param page
     * @return
     */
    @ApiLog("查询入职人员登记信息列表")
    @GetMapping("list")
    public ResponseEntity<IPage<EnrollmentRegistration>> data(EnrollmentRegistration projectReportData, Page<EnrollmentRegistration> page) throws Exception {
        IPage<EnrollmentRegistration> result = new Page<EnrollmentRegistration>();
        result = service.findList (page,projectReportData);
        return ResponseEntity.ok (result);
    }

    /**
     * 保存入职人员登记信息
     * @param registration
     * @return
     */
    @ApiLog(value = "保存入职人员登记信息", type = LogTypeEnum.SAVE)
    @PostMapping("save")
    public ResponseEntity save(@Valid @RequestBody EnrollmentRegistration registration) throws Exception {
        EnrollmentRegistration s = service.saveRegistration(registration);
        return ResponseUtil.newInstance().add("businessTable", "human_resources_enrollment_registration")
                .add("businessId", s.getId())
                .ok ("操作成功");
    }

    /**
     * 用户新增时对入职信息进行同步
     * @param registration
     * @return
     */
    @ApiLog(value = "用户新增时对入职信息进行同步", type = LogTypeEnum.SAVE)
    @PostMapping("saveInfo")
    public void saveInfo(@Valid @RequestBody EnrollmentRegistration registration) throws Exception {
        service.saveInfo(registration);
    }

    /**
     * 保存个人信息完善登记信息
     * @param registration
     * @return
     */
    @ApiLog(value = "保存个人信息完善登记信息", type = LogTypeEnum.SAVE)
    @PostMapping("save2")
    public ResponseEntity save2(@Valid @RequestBody EnrollmentRegistration registration) throws Exception {
        EnrollmentRegistration s = service.saveRegistration2(registration);
        return ResponseUtil.newInstance().add("businessTable", "human_resources_enrollment_registration")
                .add("businessId", s.getId())
                .ok ("操作成功");
    }

    /**
     * 保存入职人员登记信息
     * @param registration
     * @return
     */
    @ApiLog(value = "修改入职人员登记信息", type = LogTypeEnum.SAVE)
    @PostMapping("updateInfo")
    public ResponseEntity updateInfo(@Valid @RequestBody EnrollmentRegistration registration) throws Exception {
        service.updateRegistration(registration);
        //清除用户缓存
        List<UserDTO> onLineUserList = SpringUtil.getBean(IUserApi.class).getOnLineUserList(registration.getLoginName(), "");
        for (UserDTO dto : onLineUserList) {
            SpringUtil.getBean(IUserApi.class).clearCache ( dto );
            RedisUtils.getInstance ().delete ( CacheNames.USER_CACHE_TOKEN, dto.getToken() );
            RedisUtils.getInstance ().delete ( CacheNames.USER_CACHE_ONLINE_USERS, dto.getToken() );
        }
        return ResponseUtil.newInstance().ok("操作成功");
    }


    /**
     * 用户修改信息提交审核流程
     * @param registration
     * @return
     */
    @ApiLog(value = "用户修改信息提交审核流程", type = LogTypeEnum.SAVE)
    @PostMapping("updateInfoAudit")
    public ResponseEntity updateInfoAudit(@Valid @RequestBody EnrollmentRegistration registration) throws Exception {
        service.updateInfoAudit(registration);
        return ResponseUtil.newInstance().ok("操作成功");
    }

    /**
     * 用户暂存信息
     * @param registration
     * @return
     */
    @ApiLog(value = "用户暂存信息", type = LogTypeEnum.SAVE)
    @PostMapping("updateInfoTemporary")
    public ResponseEntity updateInfoTemporary(@Valid @RequestBody EnrollmentRegistration registration) throws Exception {
        service.updateInfoTemporary(registration);
        return ResponseUtil.newInstance().ok("操作成功");
    }

    /**
     * 用户信息通过审批
     * @param registration
     * @return
     */
    @ApiLog(value = "用户信息通过审批", type = LogTypeEnum.SAVE)
    @PostMapping("updateInfoAgree")
    public ResponseEntity updateInfoAgree(@Valid @RequestBody EnrollmentUserInfoAudit registration) throws Exception {
        userInfoAuditService.updateInfoAgree(registration);
        return ResponseUtil.newInstance().ok("操作成功");
    }


    /**
     * 用户信息驳回审批
     * @param registration
     * @return
     */
    @ApiLog(value = "用户信息驳回审批", type = LogTypeEnum.SAVE)
    @PostMapping("updateInfoReject")
    public ResponseEntity updateInfoReject(@Valid @RequestBody EnrollmentUserInfoAudit registration) throws Exception {
        userInfoAuditService.updateInfoReject(registration);
        return ResponseUtil.newInstance().ok("操作成功");
    }


    /**
     * 修改用户信息状态
     * @param registration
     * @return
     */
    @ApiLog(value = "修改用户信息状态", type = LogTypeEnum.SAVE)
    @PostMapping("updateStatusByIdUserInfo")
    public ResponseEntity updateStatusByIdUserInfo(@Valid @RequestBody EnrollmentRegistration registration) throws Exception {
        userInfoAuditService.updateStatusByIdUserInfo(registration);
        return ResponseUtil.newInstance().ok("操作成功");
    }

    /**
     * 获取用户信息审核数据
     * @param enrollmentUserInfoAudit
     * @return
     */
    @ApiLog(value = "获取用户信息审核数据", type = LogTypeEnum.SAVE)
    @GetMapping("getUserInfoAudit")
    public ResponseEntity<EnrollmentUserInfoAudit> getUserInfoAudit(EnrollmentUserInfoAudit enrollmentUserInfoAudit) throws Exception {

        EnrollmentUserInfoAudit userInfo = userInfoAuditService.getOne(
                new LambdaQueryWrapper<EnrollmentUserInfoAudit>()
                        .eq(EnrollmentUserInfoAudit::getUserId, enrollmentUserInfoAudit.getUserId())
        );
        return ResponseEntity.ok(userInfo);
    }


    /**
     * 保存社保信息
     * @param securityCard
     * @return
     */
    @ApiLog(value = "保存社保信息", type = LogTypeEnum.SAVE)
    @PostMapping("saveSocialCard")
    public ResponseEntity saveSocialCard(@Valid @RequestBody EnrollmentSocialSecurityCard securityCard) throws Exception {
        EnrollmentSocialSecurityCard s = securityCardService.saveSecurityCard(securityCard);
        return ResponseUtil.newInstance().add("businessTable", "human_resources_enrollment_social_security_card")
                .add("businessId", s.getId())
                .ok ("操作成功");
    }

    /**
     * 保存门卡信息
     * @param securityCard
     * @return
     */
    @ApiLog(value = "保存门卡信息", type = LogTypeEnum.SAVE)
    @PostMapping("saveKeyCard")
    public ResponseEntity saveKeyCard(@Valid @RequestBody EnrollmentKeyCard securityCard) throws Exception {
        EnrollmentKeyCard s = keyCardService.saveSecurityCard(securityCard);
        return ResponseUtil.newInstance().add("businessTable", "human_resources_enrollment_key_card")
                .add("businessId", s.getId())
                .ok ("操作成功");
    }

    /**
     * 保存餐补卡号息
     * @param riceCard
     * @return
     */
    @ApiLog(value = "保存餐补卡号息", type = LogTypeEnum.SAVE)
    @PostMapping("saveRiceCard")
    public ResponseEntity saveRiceCard(@Valid @RequestBody EnrollmentRiceCard riceCard) throws Exception {
        EnrollmentRiceCard s = riceCardService.saveSecurityCard(riceCard);
        return ResponseUtil.newInstance().add("businessTable", "human_resources_enrollment_rice_card")
                .add("businessId", s.getId())
                .ok ("操作成功");
    }

    /**
     * 查询
     * @param id
     * @return
     */
    @ApiOperation(value = "查询")
    @GetMapping("/findById")
    public ResponseEntity<EnrollmentRegistration> findById(@RequestParam String id) throws Exception{
        EnrollmentRegistration dto = service.findById(id);
        return ResponseEntity.ok(dto);
    }

    /**
     * 查询正在审批中的信息
     * @return
     */
    @ApiOperation(value = "查询正在审批中的信息")
    @GetMapping("/findAuditInfoById")
    public ResponseEntity<EnrollmentUserInfoAudit> findAuditInfoById(EnrollmentUserInfoAudit info) throws Exception{
        String flag = "1";
        if(StringUtils.isBlank(info.getFlag())){
            flag = "0";
        }
        EnrollmentUserInfoAudit dto = service.findAuditInfoById(info.getId(),info.getStatus(),flag);
        return ResponseEntity.ok(dto);
    }

    /**
     * 根据人员id查询是否有对应信息
     * @param userId
     * @return
     */
    @ApiOperation(value = "根据人员id查询是否有对应信息")
    @GetMapping("/findByUserId")
    public Integer findByUserId(@RequestParam String userId) throws Exception{

        /*List<UserDTO> allUserInfos = SpringUtil.getBean(IUserApi.class).getAllUserInfos();
        List<String> allUserIdInSuccess = service.getAllUserIdInSuccess();
        // 使用流操作过滤掉 allUserIdInSuccess 中存在的用户数据
        List<UserDTO> filteredUsers = allUserInfos.stream()
                .filter(user -> !allUserIdInSuccess.contains(user.getId()))
                .collect(Collectors.toList());

        for (int i=0;i<filteredUsers.size();i++){
            //发起完善个人信息流程
            Map map = SpringUtil.getBean(IFlowableApi.class).getByNameForFen("完善个人信息");
            String procDefId = map.get("id")+"";

            EnrollmentRegistration report = new EnrollmentRegistration();
            String id = UUID.randomUUID().toString().replace("-", "");
            report.setId(id);
            report.setCreateById("1");
            report.setCreateTime(new Date());
            report.setUpdateById("1");
            report.setType("2");
            report.setUserId(filteredUsers.get(i).getId());
            report.setUpdateTime(new Date());

            report.setProcessDefinitionId(procDefId);

            String value = JSON.toJSONString(report);
            //先保存数据
            service.insertIntoEnrollmentRegistrationInfo(value);



            Map<String ,Map<String,String >>  allMap = new HashMap<>();

            String procDefKey = map.get("key")+"";
            String businessTable = "human_resources_enrollment_registration";

            String businessId = id;
            String title = "管理员发起了- [" + filteredUsers.get(i).getName() + "完善个人信息]";

            String assignee = filteredUsers.get(i).getId();
            String recordType = "";

            Map<String, String> newMap = pingMap(procDefId, procDefKey, businessTable, businessId, title, assignee, recordType);
            allMap.put("完善个人信息",newMap);
            SpringUtil.getBean(IFlowableApi.class).startForFenNew(allMap);
        }*/

        return service.findByUserId(userId);
    }

    /**
     * 根据人员id查询是否有对应信息
     * @param userId
     * @return
     */
    @ApiOperation(value = "根据用户id查询对应信息")
    @GetMapping("/findInfoByUserId")
    public ResponseEntity<EnrollmentRegistration> findInfoByUserId(@RequestParam String userId) throws Exception{
        EnrollmentRegistration dto = service.findInfoByUserId(userId);
        return ResponseEntity.ok(dto);
    }

    public Map<String,String> pingMap(String procDefId,String procDefKey,String businessTable,
                                      String businessId,String title,String assignee,String recordType){
        Map<String,String> map = new HashMap();
        map.put("procDefId", procDefId);
        map.put("procDefKey", procDefKey);
        map.put("businessTable", businessTable);
        map.put("businessId", businessId);
        map.put("title", title);
        map.put("assignee", assignee);
        map.put("recordType", recordType);
        return map;
    }

    /**
     * 定时任务发起  个人信息完善所用
     * @param value
     * @return
     */
    @ApiOperation(value = "保存信息")
    @GetMapping("/insertIntoEnrollmentRegistrationInfo")
    public void insertIntoEnrollmentRegistrationInfo(String value) throws Exception{

        service.insertIntoEnrollmentRegistrationInfo(value);

    }

    /**
     * 获取所有的入职登记表中的有效数据的id
     * @return
     */
    @ApiOperation(value = "获取所有的入职登记表中的有效数据的id")
    @GetMapping("/getAllUserIdInSuccess")
    public List<String> getAllUserIdInSuccess() throws Exception{
        return service.getAllUserIdInSuccess();
    }

    /**
     * 根据人员登记id查询社保信息
     * @param id
     * @return
     */
    @ApiOperation(value = "根据人员登记id查询社保信息")
    @GetMapping("/findSocialCardById")
    public ResponseEntity<EnrollmentSocialSecurityCard> findSocialCardById(@RequestParam String id) throws Exception{
        EnrollmentSocialSecurityCard dto = securityCardService.findById(id);
        return ResponseEntity.ok(dto);
    }

    /**
     * 根据人员登记id查询门卡信息
     * @param id
     * @return
     */
    @ApiOperation(value = "根据人员登记id查询门卡信息")
    @GetMapping("/findKeyCardById")
    public ResponseEntity<EnrollmentKeyCard> findKeyCardById(@RequestParam String id) throws Exception{
        EnrollmentKeyCard dto = keyCardService.findById(id);
        return ResponseEntity.ok(dto);
    }

    /**
     * 根据人员登记id查询餐补卡号信息
     * @param id
     * @return
     */
    @ApiOperation(value = "根据人员登记id查询餐补卡号信息")
    @GetMapping("/findRiceCardById")
    public ResponseEntity<EnrollmentRiceCard> findRiceCardById(@RequestParam String id) throws Exception{
        EnrollmentRiceCard dto = riceCardService.findById(id);
        return ResponseEntity.ok(dto);
    }

    /**
     * 根据人员登记id修改状态社保信息流程的status
     */
    @ApiOperation(value = "根据人员登记id修改状态社保信息流程的status")
    @PostMapping(value = "updateSocialCardStatusById")
    public void updateSocialCardStatusById(@RequestBody EnrollmentSocialSecurityCard dto) {
        securityCardService.updateStatusById(dto);
    }

    /**
     * 根据人员登记id修改状态社保信息流程的status
     */
    @ApiOperation(value = "根据人员登记id修改状态门卡流程的status")
    @PostMapping(value = "updateKeyCardStatusById")
    public void updateKeyCardStatusById(@RequestBody EnrollmentKeyCard dto) {
        keyCardService.updateStatusById(dto);
    }

    /**
     * 根据人员登记id修改状态餐补卡号信息流程的status
     */
    @ApiOperation(value = "根据人员登记id修改状态餐补卡号信息流程的status")
    @PostMapping(value = "updateRiceCardStatusById")
    public void updateRiceCardStatusById(@RequestBody EnrollmentRiceCard dto) {
        riceCardService.updateStatusById(dto);
    }

    /**
     * 根据id修改状态status
     */
    @ApiOperation(value = "根据id修改状态status")
    @PostMapping(value = "updateStatusById")
    public void updateStatusById(@RequestBody EnrollmentRegistration dto) {
        service.updateStatusById(dto);
    }
    /**
     * 删除
     * @param id
     * @return
     */
    @ApiOperation(value = "删除")
    @GetMapping("/remove")
    public ResponseEntity<String> remove(@RequestParam String id){
        String s = service.remove(id);
        //根据入职人员id删除对应的工资卡信息
        wageCardService.deleteByRegistrationId(id);
        //根据入职人员id删除对应的社保信息
        securityCardService.deleteByRegistrationId(id);
        //删除门卡信息
        keyCardService.deleteByRegistrationId(id);
        //删除餐补卡号信息
        riceCardService.deleteByRegistrationId(id);
        return ResponseEntity.ok(s);
    }

    /**
     * 用户表中删除时也删除入职信息
     */
    @ApiOperation(value = "删除")
    @GetMapping("/delByUserId")
    public void delByUserId(@RequestParam String id){
        service.delByUserId(id);
    }

    /**
     * 查询
     * @param idCard
     * @return
     */
    @ApiOperation(value = "查询身份证号码唯一性")
    @GetMapping("/findIdCardOnly")
    public ResponseEntity<Integer> findIdCardOnly(@RequestParam String idCard, @RequestParam String userId) throws Exception{
        Integer idCardOnly = service.findIdCardOnly(idCard,userId);
        return ResponseEntity.ok(idCardOnly);
    }

    /**
     * 根据用户id查询身份证号码
     * @param userId
     * @return
     */
    @ApiOperation(value = "根据用户id查询身份证号码")
    @GetMapping("/findIdCardByUserId")
    public ResponseEntity<String> findIdCardByUserId(@RequestParam String userId) throws Exception{
        String idCard= service.findIdCardByUserId(userId);

        return ResponseEntity.ok(idCard);
    }

    /**
     * 查询
     * @param mobilePhone
     * @return
     */
    @ApiOperation(value = "联系电话唯一性")
    @GetMapping("/findMobilePhoneOnly")
    public ResponseEntity<Integer> findMobilePhoneOnly(@RequestParam String mobilePhone) throws Exception{
        Integer idCardOnly = service.findMobilePhoneOnly(mobilePhone);
        return ResponseEntity.ok(idCardOnly);
    }


    /**
     * 查询
     * @param mobilePhone
     * @return
     */
    @ApiOperation(value = "联系电话唯一性，区分租户")
    @GetMapping("/findMobilePhoneOnlyByTenantId")
    public ResponseEntity<Integer> findMobilePhoneOnlyByTenantId(@RequestParam String mobilePhone,@RequestParam String tenantId,@RequestParam String userId) throws Exception{
        Integer count = service.findMobilePhoneOnlyByTenantId(mobilePhone,tenantId,userId);
        return ResponseEntity.ok(count);
    }


    /**
     * 下载导入用户数据模板
     *
     * @param response
     * @return
     */
    @GetMapping("import/template")
    @ApiOperation(value = "下载模板")
    public void importFileTemplate(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String fileName = "用户数据导入模板.xlsx";
        List <UserTemplate> list = Lists.newArrayList ( );
        UserTemplate userTemplate = new UserTemplate();
        userTemplate.setInDate("例:1970-01-01");
        list.add(userTemplate);
        EasyExcelUtils.newInstance ( ).exportExcel ( list, "用户数据", UserTemplate.class, fileName, null, response );
    }



    /**
     * 导入用户数据
     */
    /*@PostMapping("import")
    @ApiOperation(value = "导入用户excel")
    public ResponseEntity importDetail(@RequestPart("file") MultipartFile file, HttpServletRequest request) {
        List<EnrollmentRegistration> dtoArrayList = new ArrayList<>();
        //获取sheet
        dtoArrayList = EasyPoiUtil.importExcel(file, 0, 1, EnrollmentRegistration.class);
        //去除excel中的空行
        dtoArrayList = getExcelList(dtoArrayList);
        ArrayList<EnrollmentRegistration> list = new ArrayList<>();
        //根据用户身份证号获取用户年龄,性别,出生日期
        for (EnrollmentRegistration staffUserInfoDTO : dtoArrayList) {
            if (StringUtils.isNotBlank(staffUserInfoDTO.getIdCard())){
                //获取年龄
                Integer age = IdCardUtil.getAge(staffUserInfoDTO.getIdCard());
                staffUserInfoDTO.setAge(age.toString());
                //获取性别
                String sex = IdCardUtil.getSex(staffUserInfoDTO.getIdCard());
                if (sex.equals("男")){
                    staffUserInfoDTO.setSex("1");
                }else {
                    staffUserInfoDTO.setSex("2");
                }
                //获取出生日期
                String birthday = IdCardUtil.getBirthday(staffUserInfoDTO.getIdCard());
                staffUserInfoDTO.setBirthday(birthday);
            }
            staffUserInfoDTO.setOnJobStatus("2");
            //根据所属公司获取部门
            if (StringUtils.isNotBlank(staffUserInfoDTO.getCompany())){
                List<OfficeDTO> officeDTOList = SpringUtil.getBean(IOfficeApi.class).getOfficeByCompany(staffUserInfoDTO.getCompany());
                String tenantId = officeDTOList.get(0).getTenantId();
                if (CollectionUtil.isNotEmpty(officeDTOList)){
                    for (OfficeDTO officeDTO : officeDTOList) {
                        //获取部门
                        if (StringUtils.isNotBlank(staffUserInfoDTO.getDepartment())){
                            if (officeDTO.getName().equals(staffUserInfoDTO.getDepartment())){
                                staffUserInfoDTO.setDepartment(officeDTO.getId());
                                break;
                            }
                        }
                    }
                }
            }


            service.updateInfo(staffUserInfoDTO);
        }
        return ResponseEntity.ok("导入成功");


    }*/


    /**
     * 去除excel中的空行
     * @param list
     * @return
     */
    public ArrayList<EnrollmentRegistration> getExcelList(List<EnrollmentRegistration> list){

        ArrayList<EnrollmentRegistration> infoDTOS = new ArrayList<>();

        list.stream().forEach(item->{
            if(objectCheckIsNull(item)){
                infoDTOS.add(item);
            }
        });

        return infoDTOS;
    }

    public static boolean objectCheckIsNull(Object object) {
        boolean flag = false; //定义返回结果，默认为true

        if (Objects.isNull(object)) {
            flag = false;
        } else {
            Class clazz = (Class) object.getClass(); // 得到类对象
            Field fields[] = clazz.getDeclaredFields(); // 得到所有属性
            for (Field field : fields) {
                if("serialVersionUID".equals(field.getName()) || "BIZ_CODE".equalsIgnoreCase(field.getName())){
                    continue;
                }
                field.setAccessible(true);
                Object fieldValue = null;
                try {
                    fieldValue = field.get(object); //得到属性值
                    Type fieldType = field.getGenericType();//得到属性类型
                    String fieldName = field.getName(); // 得到属性名
                    log.info("属性类型：" + fieldType + ",属性名：" + fieldName + ",属性值：" + fieldValue);
                } catch (IllegalArgumentException e) {
                    log.error(e.getMessage(), e);
                } catch (IllegalAccessException e) {
                    log.error(e.getMessage(), e);
                }
                if (fieldValue != null && fieldValue != "") {  //只要有一个属性值不为null 就返回false 表示对象不为null
                    flag = true;
                    break;
                }
            }
        }

        return flag;
    }

    @ApiLog(value = "导出入职人员数据", type = LogTypeEnum.EXPORT)
    @GetMapping("export")
    @ApiOperation(value = "导出入职人员数据")
    public void exportFile(ExportDTO exportTemplate, Page <ExportDTO> page, ExcelOptions options, HttpServletResponse response) throws Exception {
        String fileName = options.getFilename();
        String sheetName = options.getSheetName();
        List<ExportDTO> result = new ArrayList<>();
        if ( ExportMode.current.equals ( options.getMode() ) ) {
            result = service.exportList(page,exportTemplate).getRecords();
        } else if (ExportMode.selected.equals ( options.getMode() )) {
            result = service.exportList(page,exportTemplate).getRecords().stream ( ).filter ( item ->
                    options.getSelectIds ( ).contains ( item.getId ( ) )
            ).collect ( Collectors.toList ( ) );
        } else {
            page.setSize (-1);
            page.setCurrent (0);
            result = service.exportList(page,exportTemplate).getRecords();
        }
        fillEducationInfoForExport(result);
        EasyPoiUtil.exportExcel ( result, sheetName,  sheetName, ExportDTO.class, fileName, response );

    }

    @ApiLog(value = "同步钉钉id", type = LogTypeEnum.EXPORT)
    @GetMapping("syncDingTalkInfo")
    @ApiOperation(value = "同步钉钉id")
    public void syncDingTalkInfo() {
        dingTalkSyncUtil.getUserByMobileSyncData();
    }

    /**
     * 导出添加教育经历信息
     * @param result
     */
    private void fillEducationInfoForExport(List<ExportDTO> result) {
        if (result == null || result.isEmpty()) {
            return;
        }
        Map<String, Optional<EnrollmentEduInfo>> eduInfoMap = new HashMap<>();
        for (ExportDTO item : result) {
            if (item == null || StringUtils.isBlank(item.getUserId())) {
                continue;
            }
            Optional<EnrollmentEduInfo> eduInfoOptional = eduInfoMap.computeIfAbsent(item.getUserId(), this::getExportEduInfo);
            if (!eduInfoOptional.isPresent()) {
                continue;
            }
            EnrollmentEduInfo eduInfo = eduInfoOptional.get();
            item.setGraduatedFrom(eduInfo.getGraduatedFrom());
            item.setSpeciality(eduInfo.getSpeciality());
            item.setDegree(eduInfo.getDegree());
            item.setEducation(eduInfo.getEducation());
            item.setEducationStartDate(eduInfo.getStartDate());
            item.setEducationEndDate(eduInfo.getEndDate());
        }
    }

    private Optional<EnrollmentEduInfo> getExportEduInfo(String userId) {
        List<EnrollmentEduInfo> list = eduInfoService.findByUserId(userId, "5");
        if (list == null || list.isEmpty()) {
            return Optional.empty();
        }
        EnrollmentEduInfo eduInfo = list.stream()
                .filter(this::isHighestEducation)
                .findFirst()
                .orElse(list.get(0));
        return Optional.ofNullable(eduInfo);
    }

    private boolean isHighestEducation(EnrollmentEduInfo eduInfo) {
        if (eduInfo == null || StringUtils.isBlank(eduInfo.getIsHighestEducation())) {
            return false;
        }
        String flag = eduInfo.getIsHighestEducation().trim();
        return "1".equals(flag)
                || "是".equals(flag)
                || "Y".equalsIgnoreCase(flag)
                || "YES".equalsIgnoreCase(flag)
                || "TRUE".equalsIgnoreCase(flag);
    }


    /**
     * 根据选中的用户批量下载附件
     */
    @ApiOperation(value = "根据选中的用户批量下载附件")
    @PostMapping(value = "downloadAttachmentById")
    public void downloadAttachmentById(@RequestBody DownloadAttachmentDTO dto, HttpServletResponse response) throws Exception {
        String userIds = dto.getIds();
        if(StringUtils.isNotEmpty(userIds)){
            List<String> idList = Arrays.asList(userIds.split(","));
            service.downloadAttachmentByUserIds(idList,dto.getAttachmentType(),response);
        }
    }

    /**
     * 修改信息状态
     * @return
     */
    @ApiLog(value = "修改信息状态", type = LogTypeEnum.SAVE)
    @PostMapping("updateInfoStatus")
    public ResponseEntity updateInfoStatus(@Valid @RequestBody EnrollmentRegistration info) throws Exception {
        service.updateInfoStatus(info);
        return ResponseEntity.ok ("操作成功");
    }

}
