package com.ruoyi.cms.controller.cms;

import com.alibaba.fastjson.JSON;
import com.ruoyi.cms.domain.*;
import com.ruoyi.cms.domain.query.ESJobSearch;
import com.ruoyi.cms.domain.vo.CandidateVO;
import com.ruoyi.cms.domain.vo.CompanyVo;
import com.ruoyi.cms.domain.vo.JobExcelVo;
import com.ruoyi.cms.service.*;
import com.ruoyi.cms.util.EasyExcelUtils;
import com.ruoyi.cms.util.RoleUtils;
import com.ruoyi.cms.util.StringUtil;
import com.ruoyi.cms.util.sensitiveWord.SensitiveWordChecker;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.AppUser;
import com.ruoyi.common.core.domain.entity.Company;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.quickssl.api.CryptoClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 岗位Controller
 * 
 * @author lishundong
 * @date 2024-09-03
 */
@RestController
@RequestMapping("/cms/job")
@Api(tags = "后台：岗位管理")
@Anonymous
public class CmsJobController extends BaseController
{
    @Autowired
    private IJobService jobService;
    @Autowired
    SensitiveWordChecker sensitiveWordChecker;
    @Autowired
    private ICompanyService companyService;
    @Autowired
    private IJobCollectionService jobCollectionService;
    @Autowired
    private IAppUserService appUserService;
    @Autowired
    private IJobApplyService iJobApplyService;
    @Autowired
    private IAppReviewJobService iAppReviewJobService;
    /**
     * 查询岗位列表
     */
    @ApiOperation("查询岗位列表")
//    @PreAuthorize("@ss.hasPermi('cms:job:list')")
    @GetMapping("/list")
    public TableDataInfo list(Job job,HttpServletRequest request)
    {
        if (RoleUtils.isCompanyAdmin()) {
            Company company = companyService.queryCodeCompany(RoleUtils.getCurrentUseridCard());
            job.setCompanyId(Objects.nonNull(company) ? company.getCompanyId() : null);
        }
        startPage();
        //List<Job> list = jobService.selectJobList(job);
        List<Job> list = jobService.selectHttpJobList(job,request);
        return getDataTable(list);
    }

    /**
     * 获取岗位详细信息
     */
    @ApiOperation("获取岗位详细信息")
//    @PreAuthorize("@ss.hasPermi('bussiness:job:query')")
    @GetMapping(value = "/{jobId}")
    public AjaxResult getInfo(@PathVariable("jobId") Long jobId, HttpServletRequest request)
    {
        if (jobId == null) {
            return AjaxResult.error("jobId不能为空");
        }
        //return success(jobService.selectJobByJobId(jobId));
        return success(jobService.selectHttpJobByJobId(jobId,request));
    }

    /**
     * 导出岗位列表
     */
    @ApiOperation("导出岗位列表")
//    @PreAuthorize("@ss.hasPermi('bussiness:job:export')")
    @Log(title = "岗位", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Job job)
    {
        List<Job> list = jobService.selectJobList(job);
        ExcelUtil<Job> util = new ExcelUtil<Job>(Job.class);
        util.exportExcel(response, list, "岗位数据");
    }
    /**
     * 新增岗位
     */
    @ApiOperation("新增岗位")
//    @PreAuthorize("@ss.hasPermi('bussiness:job:add')")
    @Log(title = "岗位", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Job job)
    {
        // 校验描述中的敏感词
        List<String> sensitiveWords = sensitiveWordChecker.checkSensitiveWords(job.getDescription());
        if (!sensitiveWords.isEmpty()) {
            String errorMsg = "描述中包含敏感词：" + String.join("、", sensitiveWords);
            return AjaxResult.error(errorMsg);
        }
        job.setJobStatus("0");//上架
        if(StringUtils.isBlank(job.getDownTime())){
            job.setDownTime(DateUtils.getMonthThree(DateUtils.YYYY_MM_DD_HH_MM_SS));
        }
        // 无敏感词，执行插入
        return toAjax(jobService.insertJob(job));
    }

    /**
     * 修改岗位
     */
    @ApiOperation("修改岗位")
//    @PreAuthorize("@ss.hasPermi('bussiness:job:edit')")
    @Log(title = "岗位", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Job job)
    {
        // 校验描述中的敏感词
        List<String> sensitiveWords = sensitiveWordChecker.checkSensitiveWords(job.getDescription());
        if (!sensitiveWords.isEmpty()) {
            String errorMsg = "描述中包含敏感词：" + String.join("、", sensitiveWords);
            return AjaxResult.error(errorMsg);
        }
        if(StringUtils.isBlank(job.getDownTime())){
            job.setDownTime(DateUtils.getMonthThree(DateUtils.YYYY_MM_DD_HH_MM_SS));
        }
        return toAjax(jobService.updateJob(job));
    }

    /**
     * 删除岗位
     */
    @ApiOperation("删除岗位")
//    @PreAuthorize("@ss.hasPermi('bussiness:job:remove')")
    @Log(title = "岗位", businessType = BusinessType.DELETE)
    @DeleteMapping("/{jobIds}")
    public AjaxResult remove(@PathVariable Long[] jobIds)
    {
        return toAjax(jobService.deleteJobByJobIds(jobIds));
    }

    @ApiOperation("候选人查询")
    @Log(title = "岗位", businessType = BusinessType.DELETE)
    @GetMapping("/candidates")
    @PreAuthorize("@ss.hasPermi('bussiness:job:candidates')")
    public TableDataInfo candidates(Long jobId)
    {
        startPage();
        List<CandidateVO> list = jobService.candidates(jobId);
        return getDataTable(list);
    }

    @ApiOperation("获取推荐岗位")
    @GetMapping("/recommend")
    public AjaxResult recommend(ESJobSearch esJobSearch)
    {
        if (RoleUtils.isCompanyAdmin()) {
            esJobSearch.setCode(RoleUtils.getCurrentUseridCard());
            esJobSearch.setUserType(StringUtil.IS_COMPANY_USER);
        }
        //判断pageSize
        Integer pageSize=esJobSearch.getPageSize();
        if (pageSize == null || pageSize <= 0) {
            esJobSearch.setPageSize(20);
        }
        List<ESJobDocument> jobList = jobService.sysRecommend(esJobSearch);
        List<Job> jobs=new ArrayList<>();
        jobList.stream().forEach(it->{
            Job job=new Job();
            BeanUtils.copyBeanProp(job, it);
            job.setCompanyVo(JSON.parseObject(it.getCompanyVoJson(), CompanyVo.class));
            jobs.add(job);
        });
        return success(jobs);
    }

    @ApiOperation("获取所有岗位")
    @GetMapping("/selectAllJob")
    public AjaxResult selectAllJob()
    {
        List<Job> jobList = jobService.selectAllJob();
        return success(jobList);
    }

    @PostMapping("/collection")
    @ApiOperation("用户收藏")
    public AjaxResult jobCollection(@RequestBody JobCollection jobCollection)
    {
        if(jobCollection.getJobId()==null){
            return AjaxResult.error("岗位id为空");
        }
        if(!SecurityUtils.isLogin()){
            return AjaxResult.error("用户未登录!");
        }
        if(jobCollection.getUserId()==null){
            String idCard=RoleUtils.getCurrentUseridCard();
            AppUser appUser=appUserService.selectAppuserByIdcard(idCard);
            if(appUser==null){
                return AjaxResult.error("用户信息未完善,请完善身份证信息!");
            }else{
                jobCollection.setUserId(appUser.getUserId());
            }
        }
        return toAjax(jobCollectionService.pcJobCollection(jobCollection));
    }

    @ApiOperation("获取用户岗位收藏列表")
    @GetMapping("/getAppUserYhsc")
    public AjaxResult getAppUserYhsc(JobCollection jobCollection)
    {
        if(!SecurityUtils.isLogin()){
            return AjaxResult.error("用户未登录!");
        }
        if(jobCollection.getUserId()==null){
            String idCard=RoleUtils.getCurrentUseridCard();
            AppUser appUser=appUserService.selectAppuserByIdcard(idCard);
            if(appUser==null){
                return AjaxResult.error("用户信息未完善,请完善身份证信息!");
            }else{
                jobCollection.setUserId(appUser.getUserId());
            }
        }
        return success(jobCollectionService.selectJobCollectionListJob(jobCollection));
    }

    @ApiOperation("获取用户岗位申请列表")
    @GetMapping("/getAppUserYhsq")
    public AjaxResult getAppUserYhsq(JobApply jobApply)
    {
        if(!SecurityUtils.isLogin()){
            return AjaxResult.error("用户未登录!");
        }
        if(jobApply.getUserId()==null){
            String idCard=RoleUtils.getCurrentUseridCard();
            AppUser appUser=appUserService.selectAppuserByIdcard(idCard);
            if(appUser==null){
                return AjaxResult.error("用户信息未完善,请完善身份证信息!");
            }else{
                jobApply.setUserId(appUser.getUserId());
            }
        }
        return success(iJobApplyService.selectJobApplyListJob(jobApply));
    }

    @ApiOperation("获取用户岗位访问足迹列表")
    @GetMapping("/getAppUserYhfwzj")
    public AjaxResult getAppUserYhfwzj(AppReviewJob appReviewJob)
    {
        if(!SecurityUtils.isLogin()){
            return AjaxResult.error("用户未登录!");
        }
        if(appReviewJob.getUserId()==null){
            String idCard=RoleUtils.getCurrentUseridCard();
            AppUser appUser=appUserService.selectAppuserByIdcard(idCard);
            if(appUser==null){
                return AjaxResult.error("用户信息未完善,请完善身份证信息!");
            }else{
                appReviewJob.setUserId(appUser.getUserId());
            }
        }
        return success(iAppReviewJobService.selectAppReviewJobListJob(appReviewJob));
    }

    @PostMapping("/collectionCancel")
    @ApiOperation("取消收藏")
    public AjaxResult pcCancel(@RequestBody JobCollection jobCollection)
    {
        if(jobCollection.getJobId()==null){
            return AjaxResult.error("岗位id为空");
        }
        if(!SecurityUtils.isLogin()){
            return AjaxResult.error("用户未登录!");
        }
        if(jobCollection.getUserId()==null){
            String idCard=RoleUtils.getCurrentUseridCard();
            AppUser appUser=appUserService.selectAppuserByIdcard(idCard);
            if(appUser==null){
                return AjaxResult.error("用户信息未完善,请完善身份证信息!");
            }else{
                jobCollection.setUserId(appUser.getUserId());
            }
        }
        return toAjax(jobCollectionService.pcCancel(jobCollection));
    }

    @PostMapping("/browse")
    @ApiOperation("岗位浏览")
    public AjaxResult browse(@RequestBody AppReviewJob appReviewJob)
    {
        if(appReviewJob.getJobId()==null){
            return AjaxResult.error("岗位id为空");
        }
        if(!SecurityUtils.isLogin()){
            return AjaxResult.error("用户未登录!");
        }
        if(StringUtils.isEmpty(appReviewJob.getReviewDate())){
            appReviewJob.setReviewDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,new Date()));
        }
        if(appReviewJob.getUserId()==null){
            String idCard=RoleUtils.getCurrentUseridCard();
            AppUser appUser=appUserService.selectAppuserByIdcard(idCard);
            if(appUser==null){
                return AjaxResult.error("用户信息未完善,请完善身份证信息!");
            }else{
                appReviewJob.setUserId(appUser.getUserId());
            }
        }
        return toAjax(iAppReviewJobService.insertAppReviewJob(appReviewJob));
    }


    @ApiOperation("获取推荐岗位-给数据底座的")
    @GetMapping("/recommendTosjdz")
    public AjaxResult recommendTosjdz(ESJobSearch esJobSearch)
    {
        if (RoleUtils.isCompanyAdmin()) {
            esJobSearch.setCode(RoleUtils.getCurrentUseridCard());
            esJobSearch.setUserType(StringUtil.IS_COMPANY_USER);
        }
        esJobSearch.setPageSize(20);
        List<ESJobDocument> jobList = jobService.sysRecommend(esJobSearch);
        jobList.stream().forEach(it->{
            it.setAppJobUrl(StringUtil.BASE_WW_GW+it.getJobId());
        });
        return success(jobList);
    }

    @PostMapping("/wechat")
    @ApiOperation("微信抓取功能调用的新增")
    public AjaxResult wechatInsert(@RequestBody Job job) {
        // 不发布
        job.setIsPublish(0);
        if (job.getJobContactList() == null) {
            job.setJobContactList(new ArrayList<>());
        }
        Integer total=jobService.getTotals(job);
        int totalNum = total != null ? total : 0;
        System.out.println("岗位条数======================"+totalNum);
        if (totalNum == 0) {
            if(StringUtils.isBlank(job.getDownTime())){
                job.setDownTime(DateUtils.getMonthThree(DateUtils.YYYY_MM_DD_HH_MM_SS));
            }
            return toAjax(jobService.insertJob(job));
        }
        return AjaxResult.success("此岗位已存在!");
    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/uploadFile")
    @ApiOperation("岗位批量上传")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return AjaxResult.error("上传文件不能为空");
        }
        String fileName = file.getOriginalFilename();
        if (fileName == null || !fileName.endsWith(".xlsx") && !fileName.endsWith(".xls")) {
            return AjaxResult.error("请上传Excel格式的文件");
        }

        try (InputStream inputStream = file.getInputStream()){
            List<JobExcelVo> allExcelVoList = new ArrayList<>();
            EasyExcelUtils.readExcelByBatch(inputStream, JobExcelVo.class, 100, list -> {
                allExcelVoList.addAll(list);
            });
            if (CollectionUtils.isEmpty(allExcelVoList)) {
                throw new Exception("Excel文件中无有效数据");
            }
            jobService.uploadFileJob(allExcelVoList);
            return AjaxResult.success("已上传!");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 模板下载
     * @param request
     * @param response
     * @throws Exception
     */
    @PostMapping("/downloadModel")
    @ApiOperation("岗位批量上传模板下载")
    public void downloadModel(HttpServletRequest request, HttpServletResponse response)throws Exception{
        String name = "模板.xlsx";
        String pathFile="/data/downloadmodel/"+name;
        File url = new File(pathFile);

        String resMsg = "";
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        try {
            name = new String(name.getBytes("gb2312"), "ISO8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.reset();

        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename="+ name);
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "max-age=0");
        InputStream in = null;
        try {
            in = new FileInputStream(url);
        } catch (FileNotFoundException e1) {
            resMsg = "文件未找到";
            e1.printStackTrace();
            response.getWriter().write(resMsg + ":" + name);
        }
        OutputStream ou = response.getOutputStream();
        byte[] buffer = new byte[1024];
        int i = -1;
        while ((i = in.read(buffer)) != -1) {
            ou.write(buffer, 0, i);
        }
        ou.flush();
        ou.close();
        in.close();
    }

    @ApiOperation("岗位下架")
    @PutMapping("/jobDown/{jobId}")
    public AjaxResult jobDown(@PathVariable("jobId") Long jobId){
        if(jobId==null){
            return error("岗位id为空");
        }
        return toAjax(jobService.jobDown(jobId));
    }

    @ApiOperation("岗位上架")
    @PutMapping("/jobUp/{jobId}")
    public AjaxResult jobUp(@PathVariable("jobId") Long jobId) throws CryptoClient.CryptoException {
        if(jobId==null){
            return error("岗位id为空");
        }
        return toAjax(jobService.jobUp(jobId));
    }


}
