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

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.common.utils.ResponseUtil;
import com.jeeplus.flowable.feign.IFlowableApi;
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.utils.HunamFreemarkerUtil;
import com.jeeplus.human.practice.register.domain.Registration;
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 freemarker.template.Configuration;
import freemarker.template.Template;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.graphics.state.RenderingMode;
import org.apache.pdfbox.util.Matrix;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

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

    @Resource
    private EnrollmentRegistrationService service;

    @Resource
    private EnrollmentSocialSecurityCardService securityCardService;

    @Resource
    private EnrollmentKeyCardService keyCardService;

    @Resource
    private EnrollmentRiceCardService riceCardService;

    @Resource
    private HandoverService handoverService;

    @Resource
    private EnrollmentWageCardService wageCardService;

    /**
     * 下载门禁卡开通注意事项
     * @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("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);
        return ResponseUtil.newInstance().ok("操作成功");
    }

    /**
     * 保存社保信息
     * @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);
    }

    /**
     * 根据人员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);
    }

    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);
    }

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

    /**
     * 查询
     * @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);
    }
}
