package com.jeeplus.human.practice.register.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.utils.ResponseUtil;
import com.jeeplus.human.enrollment.enrollmentRegistration.domain.EnrollmentRegistration;
import com.jeeplus.human.enrollment.enrollmentRegistration.service.EnrollmentRegistrationService;
import com.jeeplus.human.enrollment.enrollmentRegistration.utils.HunamFreemarkerUtil;
import com.jeeplus.human.practice.register.domain.Registration;
import com.jeeplus.human.practice.register.service.RegistrationBankService;
import com.jeeplus.human.practice.register.service.RegistrationService;
import com.jeeplus.human.practice.register.service.dto.RegistrationDto;
import com.jeeplus.human.practice.utils.HumanResponseUtil;
import com.jeeplus.logging.annotation.ApiLog;
import com.jeeplus.logging.constant.enums.LogTypeEnum;

import freemarker.template.Configuration;
import freemarker.template.Template;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author 王强
 * @version 1.0
 * @date 2023-09-13 10:55
 */
@RestController
@Api("实习人员登记表信息")
@RequestMapping(value = "/register")
public class RegisterController {

    @Resource
    private RegistrationService service;
    @Resource
    private RegistrationBankService bankService;

    @Resource
    private EnrollmentRegistrationService enrollmentRegistrationService;

    /**
     * 查询
     * @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 projectReportData
     * @param page
     * @return
     */
    @ApiLog("查询实习人员登记信息列表")
    @GetMapping("list")
    public ResponseEntity<IPage<RegistrationDto>> data(RegistrationDto projectReportData, Page<RegistrationDto> page) throws Exception {
        IPage<RegistrationDto> result = new Page<RegistrationDto>();
        result = service.findList (page,projectReportData);
        return ResponseEntity.ok (result);
    }

    /**
     * 根据id查询实习生信息
     * @param projectReportData
     * @param page
     * @return
     */
    @ApiLog("查询实习人员登记信息列表")
    @GetMapping("list2")
    public ResponseEntity<IPage<RegistrationDto>> data2(RegistrationDto projectReportData, Page<RegistrationDto> page) throws Exception {
        IPage<RegistrationDto> result = new Page<RegistrationDto>();
        result = service.findList2 (page,projectReportData);
        return ResponseEntity.ok (result);
    }

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

    /**
     * 修改实习人员登记信息
     * @param registration
     * @return
     */
    @ApiLog(value = "修改实习人员登记信息", type = LogTypeEnum.SAVE)
    @PostMapping("updateInfo")
    public ResponseEntity updateInfo(@Valid @RequestBody Registration registration) throws Exception {
        service.updateRegistration(registration);
        return ResponseUtil.newInstance().ok("操作成功");
    }

    /**
     * 定时任务修改
     * @param id
     */
    @PostMapping("updatePracticeStatus")
    public void updatePracticeStatus(String id){
        service.adminUpdatePracticeStatus(id);
    }

    /**
     * 保存实习人员登记信息
     * @param registration
     * @return
     */
    @ApiLog(value = "保存实习人员登记信息", type = LogTypeEnum.SAVE)
    @PostMapping("saveForm")
    public ResponseEntity saveForm(@Valid @RequestBody Registration registration) throws Exception {
        service.saveForm(registration);
        return ResponseEntity.ok("操作成功");
    }

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

    /**
     * 根据id修改状态status
     */
    @ApiOperation(value = "根据id修改状态status")
    @PostMapping(value = "updateStatusById")
    public void updateStatusById(@RequestBody RegistrationDto dto) {
        service.updateStatusById(dto);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @ApiOperation(value = "删除")
    @GetMapping("/remove")
    public ResponseEntity<String> remove(@RequestParam String id){
        String s = service.remove(id);
        bankService.deleteByRegistrationId(id);
        return ResponseEntity.ok(s);
    }

    /**
     * 查询3天未发送日志状态为实习中的人员信息
     * @return
     */
    @GetMapping("getTimeOutRegisters")
    public String getTimeOutRegisters(){
        List<Registration> listInfos = service.getTimeOutRegisters();
        return JSON.toJSONString(listInfos);
    }

    /**
     * 获取最后一次发起报销且实习状态为结束，并且报销状态为完成的
     * @return
     */
    @GetMapping("getTimeOutReimburseRegisters")
    public String getTimeOutReimburseRegisters(){
        List<Registration> listInfos = service.getTimeOutReimburseRegisters();
        return JSON.toJSONString(listInfos);
    }

    /**
     * 获取正式工在职状态为离职的，并且user表中未删除的
     * @return
     */
    @GetMapping("getFormalUserInfo")
    public String getFormalUserInfo(){
        List<EnrollmentRegistration> listInfos = enrollmentRegistrationService.getFormalUserInfo();
        return JSON.toJSONString(listInfos);
    }

    /**
     * 获取所有的实习人员信息
     * @return
     */
    @GetMapping("getAllRegister")
    public String getAllRegister(){
        List<Registration> listInfos = service.getAllRegister();
        return JSON.toJSONString(listInfos);
    }

    /**
     * 下载实习用户信息
     * @param response
     * @param id
     */
    @RequestMapping(value="downloadRegistrationTpl")
    @ResponseBody
    public void downloadRegistration(HttpServletResponse response, @RequestParam("id") String id)  {
        Map data = service.getInfoMap(response, id );

        //模板对象
        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("registration.ftl","UTF-8");

            File docFile = new File("实习登记信息.doc");
            HunamFreemarkerUtil.generateFile(data,template,docFile);
            HumanResponseUtil.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();
                }
            }
        }

    }
}
