package com.ruoyi.web.work.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.work.api.util.AppUtil;
import com.ruoyi.web.work.domain.Enterprise;
import com.ruoyi.web.work.domain.Position;
import com.ruoyi.web.work.domain.Resume;
import com.ruoyi.web.work.domain.ResumeDeliver;
import com.ruoyi.web.work.domain.dto.ResumeDeliverDto;
import com.ruoyi.web.work.domain.dto.ResumeInviteDto;
import com.ruoyi.web.work.domain.vo.ReceiveListVo;
import com.ruoyi.web.work.domain.vo.ReceiveVo;
import com.ruoyi.web.work.mapper.ResumeDeliverMapper;
import com.ruoyi.web.work.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.List;

/**
 * @author lsw
 * @date 2024-06-13
 */
@Service
public class ResumeDeliverServiceImpl extends ServiceImpl<ResumeDeliverMapper, ResumeDeliver> implements IResumeDeliverService {
    @Autowired
    private ResumeDeliverMapper resumeDeliverMapper;

    @Autowired
    private IPositionService positionService;

    @Autowired
    private IResumeService resumeService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IEnterpriseService enterpriseService;

    @Autowired
    private Environment env;

    @Override
    public List<ResumeDeliver> selectList(ResumeDeliver resumeDeliver) {
        return resumeDeliverMapper.selectList(resumeDeliver);
    }

    @Override
    public AjaxResult send(Long id) {
        if (AppUtil.getUser().getIsAuthentication() != 1) {
            return AjaxResult.error(7878, "您需要实名认证才能投递简历");
        }
        Resume resume = resumeService.getById(AppUtil.getUser().getId());
        if (StringUtils.isEmpty(resume.getName())) {
            return AjaxResult.error(7979, "请先完善简历再投递");
        }
        Position position = positionService.getById(id);
        if (position == null || position.getState() != 0 || position.getAudit() != 1) {
            return AjaxResult.error("该职位不存在或已下架");
        }
        ResumeDeliver resumeDeliver = resumeDeliverMapper.check(position.getId(), AppUtil.getUser().getId());
        if (resumeDeliver != null) {
            return AjaxResult.error("请勿重复投递简历");
        }
        resumeDeliver = new ResumeDeliver();
        resumeDeliver.setUserId(AppUtil.getUser().getId());
        resumeDeliver.setType(position.getType());
        resumeDeliver.setPositionId(position.getId());
        resumeDeliver.setEnterpriseId(position.getUserId());
        resumeDeliver.setOpenId(AppUtil.getUser().getOpenId());
        if (!save(resumeDeliver)) {
            throw new ServiceException("投递简历失败");
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult agree(ResumeDeliverDto dto) {
        ResumeDeliver resumeDeliver = getById(dto.getId());
        if (resumeDeliver == null || !resumeDeliver.getUserId().equals(AppUtil.getUser().getId())) {
            return AjaxResult.error("面试不存在或非法操作");
        }
        resumeDeliver.setIsAccept(dto.getIsAccept());
        if (!updateById(resumeDeliver)) {
            throw new ServiceException("接受或拒绝面试邀请失败");
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult invite(ResumeInviteDto dto) throws ParseException {
        ResumeDeliver resumeDeliver = getById(dto.getId());
        if (resumeDeliver == null || !resumeDeliver.getEnterpriseId().equals(AppUtil.getUser().getId())) {
            return AjaxResult.error("简历不存在或非法操作");
        }
        if (resumeDeliver.getIsAccept() == 2) {
            return AjaxResult.error("求职者已拒绝，无法重复发送");
        }
        if (resumeDeliver.getIsAccept() == 1) {
            return AjaxResult.error("求职者已同意，请及时安排线下面试");
        }
        if (resumeDeliver.getState() == 1) {
            return AjaxResult.error("已发送邀请，等待求职者同意");
        }
        resumeDeliver.setState(1);
        resumeDeliver.setInviteTime(dto.getInviteTime());
        if (!updateById(resumeDeliver)) {
            throw new ServiceException("发送面试邀请失败");
        }
        sendMessage(resumeDeliver);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult complete(Long id) {
        ResumeDeliver resumeDeliver = getById(id);
        if (resumeDeliver == null || !resumeDeliver.getEnterpriseId().equals(AppUtil.getUser().getId())) {
            return AjaxResult.error("简历不存在或非法操作");
        }
        resumeDeliver.setIsAccept(3);
        if (!updateById(resumeDeliver)) {
            throw new ServiceException("操作面试失败");
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult detail(Long id) {
        ResumeDeliver resumeDeliver = getById(id);
        if (resumeDeliver == null || !resumeDeliver.getEnterpriseId().equals(AppUtil.getUser().getId())) {
            return AjaxResult.error("简历不存在或非法操作");
        }
        if (resumeDeliver.getIsRead() == 0) {
            resumeDeliver.setIsRead(1);
            updateById(resumeDeliver);
        }
        Resume resume = resumeService.getById(resumeDeliver.getUserId());
        return AjaxResult.success(resume);
    }

    @Override
    public AjaxResult remove(Long id) {
        ResumeDeliver resumeDeliver = getById(id);
        if (resumeDeliver == null || !resumeDeliver.getUserId().equals(AppUtil.getUser().getId())) {
            return AjaxResult.error("简历不存在或非法操作");
        }
        if (!removeById(id)) {
            throw new ServiceException("删除投递失败");
        }
        return AjaxResult.success();
    }

    @Override
    public List<ReceiveVo> receive(Long userId) {
        return resumeDeliverMapper.receive(userId);
    }

    @Override
    public List<ReceiveListVo> receiveList(ResumeDeliver resumeDeliver) {
        return resumeDeliverMapper.receiveList(resumeDeliver);
    }

    @Override
    public void sendMessage(ResumeDeliver resumeDeliver) throws ParseException {
        JSONObject jsonObject = JSONUtil.parseObj(HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + env.getProperty("wx.appid") + "&secret=" + env.getProperty("wx.appSecret")));
        JSONObject body = new JSONObject();
        body.set("touser", resumeDeliver.getOpenId());
        body.set("appid", env.getProperty("wx.appid"));
        JSONObject content = new JSONObject();
        //面试邀请通知
        if (resumeDeliver.getState() == 1 && resumeDeliver.getIsAccept() == 0) {
            Position position = positionService.getById(resumeDeliver.getPositionId());
            Enterprise enterprise = enterpriseService.getById(resumeDeliver.getUserId());
            body.set("template_id", "ll-qdaEgbDN4rEod0nJpsjUuSqHT9e12EniZfRPiNqM");
            body.set("page", "pages/user/resume/deliver/invite");
            content.set("thing5", new JSONObject().set("value", enterprise.getName()));//公司名称
            content.set("thing1", new JSONObject().set("value", position.getTitle()));//职位
            content.set("time3", new JSONObject().set("value", DateUtils.formatDate(resumeDeliver.getInviteTime())));//面试时间
            content.set("thing4", new JSONObject().set("value", StringUtils.truncateString(position.getAddress(), 15))); //面试地点
        }
        body.set("data", content);
        String result = HttpUtil.post("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + jsonObject.getStr("access_token"), body.toString());
        System.out.println("body：" + body);
        System.out.println("小程序订阅消息：" + result);
    }
}
