package com.ruoyi.cms.controller.app;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.deepoove.poi.util.PoitlIOUtils;
import com.ruoyi.cms.domain.AppReviewJob;
import com.ruoyi.cms.util.DictUtils;
import com.ruoyi.cms.util.StringUtil;
import com.ruoyi.common.core.domain.entity.AppSkill;
import com.ruoyi.common.core.domain.entity.AppUser;
import com.ruoyi.common.core.domain.entity.Company;
import com.ruoyi.cms.domain.Job;
import com.ruoyi.cms.domain.JobFair;
import com.ruoyi.cms.domain.query.MineJobQuery;
import com.ruoyi.cms.service.*;
import com.ruoyi.common.annotation.BussinessLog;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.cms.domain.vo.AppUserLky;
import com.ruoyi.common.core.domain.entity.UserWorkExperiences;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SiteSecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * app用户Controller
 * 
 * @author lishundong
 * @date 2024-09-03
 */
@RestController
@RequestMapping("/app/user")
@Api(tags = "移动端:用户相关")
public class AppUserController extends BaseController
{
    @Autowired
    private IAppUserService appUserService;
    @Autowired
    private IAppReviewJobService appReviewJobService;
    @Autowired
    private IJobCollectionService jobCollectionService;
    @Autowired
    private ICompanyCollectionService companyCollectionService;
    @Autowired
    private IJobApplyService jobApplyService;
    @Autowired
    private IFairCollectionService fairCollectionService;
    /**
     * 查询岗位列表
     */
    @ApiOperation("保存注册信息")
    @PostMapping("/registerUser")
    @BussinessLog(title = "保存简历")
    public AjaxResult registerUser(@RequestBody RegisterBody registerBody)
    {
        appUserService.registerAppUser(registerBody);
        return AjaxResult.success();
    }

    @ApiOperation("保存简历")
    @PostMapping("/resume")
    public AjaxResult saveResume(@RequestBody AppUser appUser)
    {
        appUser.setUserId(SiteSecurityUtils.getUserId());
        appUserService.updateAppUser(appUser);
        return AjaxResult.success();
    }

    @ApiOperation("查看简历")
    @GetMapping("/resume")
    public AjaxResult getResume()
    {
        AppUser appUser = appUserService.selectAppUserByUserId(SiteSecurityUtils.getUserId());
        return AjaxResult.success(appUser);
    }

    @ApiOperation("企业查看简历")
    @GetMapping("/userResume/{id}")
    public AjaxResult getResume(@PathVariable(name = "id", required = true) Long userId)
    {
        if(userId==null){
            return AjaxResult.error("用户id为空!");
        }
        AppUser appUser = appUserService.selectAppUserByUserId(userId);
        return AjaxResult.success(appUser);
    }

    @ApiOperation("我的浏览")
    @GetMapping("/review")
    public TableDataInfo review(MineJobQuery jobQuery)
    {
        startPage();
        List<Job> jobs = appReviewJobService.review(jobQuery);
        return getDataTable(jobs);
    }
    @ApiOperation("我的浏览-日期数组")
    @GetMapping("/review/array")
    public AjaxResult reviewArray(MineJobQuery jobQuery)
    {

        List<String> dateList = appReviewJobService.reviewArray();
        return AjaxResult.success(dateList);
    }
    @ApiOperation("我的岗位收藏")
    @GetMapping("/collection/job")
    public TableDataInfo collectionJob()
    {
        startPage();
        List<Job> jobs = jobCollectionService.collectionJob();
        return getDataTable(jobs);
    }
    @ApiOperation("我的公司收藏")
    @GetMapping("/collection/company")
    public TableDataInfo collectionCompany()
    {
        startPage();
        List<Company> jobs = companyCollectionService.collectionCompany();
        return getDataTable(jobs);
    }
    @ApiOperation("我的招聘会收藏")
    @GetMapping("/collection/fair")
    public TableDataInfo collectionFair(@RequestParam(name = "type") Integer type)
    {
        startPage();
        List<JobFair> jobs = fairCollectionService.appCollectionFair(type);
        return getDataTable(jobs);
    }
    @ApiOperation("我申请的岗位")
    @GetMapping("/apply/job")
    public TableDataInfo applyJob()
    {
        startPage();
        List<Job> jobs = jobApplyService.applyJob();
        return getDataTable(jobs);
    }
    @ApiOperation("统计")
    @GetMapping("/statistics")
    public AjaxResult statistics()
    {
        HashMap<String,Integer> result = jobApplyService.statistics();
        return AjaxResult.success(result);
    }

    @ApiOperation("根据条件查询用户信息")
    @GetMapping("/list")
    public AjaxResult getUserList(AppUser appUser)
    {
        List<AppUser> list = appUserService.selectAppUserList(appUser);
        return AjaxResult.success(list);
    }

    @ApiOperation("返回求职者劳科院-当前职位名称、技能标签")
    @GetMapping("/appUserInfo")
    public AjaxResult appUserInfo(AppUser appUser)
    {
        if(!SiteSecurityUtils.isLogin()){
            return AjaxResult.error("未登录！");
        }
        appUser.setUserId(SiteSecurityUtils.getUserId());
        AppUserLky appUserLky = appUserService.selectAppUserInfo(appUser);
        return AjaxResult.success(appUserLky);
    }

    @PostMapping("/browse")
    @ApiOperation("用户浏览")
    public AjaxResult browse(@RequestBody AppReviewJob appReviewJob)
    {
        if(appReviewJob.getJobId()==null){
            return AjaxResult.error("岗位id为空");
        }
        if(!SiteSecurityUtils.isLogin()){
            return AjaxResult.error("用户未登录!");
        }
        if(StringUtils.isEmpty(appReviewJob.getReviewDate())){
            appReviewJob.setReviewDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,new Date()));
        }
        appReviewJob.setUserId(SiteSecurityUtils.getUserId());
        return toAjax(appReviewJobService.insertAppReviewJob(appReviewJob));
    }

    @ApiOperation("生成简历")
    @GetMapping("/createResume")
    public void createResume(HttpServletResponse response){
        try {
            Long userId=null;
            if(SiteSecurityUtils.isLogin()){
                userId=SiteSecurityUtils.getUserId();
            }
            String templatePath="/data/downloadmodel/简历.docx";
            AppUser result=appUserService.selectAppUserByUserId(userId);
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("name", result.getName());
            dataMap.put("sex", DictUtils.getDictLabel("app_sex",result.getSex()));
            dataMap.put("birthDate", StringUtil.getBirthDateFromIdCard(result.getIdCard()));
            dataMap.put("education", DictUtils.getDictLabel("education",result.getEducation()));
            dataMap.put("politicalAffiliation", DictUtils.getDictLabel("political_affiliation",result.getPoliticalAffiliation()));
            dataMap.put("nation", DictUtils.getDictLabel("nation",result.getNation()));
            dataMap.put("domicileAddress", result.getDomicileAddress());
            dataMap.put("address", result.getAddress());
            String salary=result.getSalaryMin()+"-"+result.getSalaryMax();
            dataMap.put("salary", salary);
            dataMap.put("area", DictUtils.getDictLabel("area",result.getArea()));
            dataMap.put("jobTitle", String.join(",",result.getJobTitle()));

            LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
            Configure builder = Configure.builder()
                    .bind("workExperiences",policy)
                    .bind("skillList",policy)
                    .build();

            List<UserWorkExperiences> userWorkExperiences = result.getExperiencesList();
            List<AppSkill> skillList=result.getAppSkillsList();
            skillList.forEach(it->it.setLevels(DictUtils.getDictLabel("skill_level",it.getLevels())));

            dataMap.put("workExperiences", userWorkExperiences);
            dataMap.put("skillList", skillList);

            String name=result.getName();
            name = new String(name.getBytes("gb2312"), "ISO8859-1");
            XWPFTemplate template = XWPFTemplate.compile(templatePath,builder).render(dataMap);

            response.setCharacterEncoding("utf-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename="+ name);
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-Control", "max-age=0");

            OutputStream out = response.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(out);
            template.write(bos);
            bos.flush();
            out.flush();
            PoitlIOUtils.closeQuietlyMulti(template, bos, out);

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

    @ApiOperation("简历识别")
    @PostMapping("/resume/recognition")
    @ResponseBody
    @BussinessLog(title = "简历识别")
    public AjaxResult recognition(@RequestParam("file") MultipartFile file) throws Exception{
        return appUserService.recognition(file.getBytes(),file.getOriginalFilename(),SiteSecurityUtils.getUserId());
    }
}
