package com.sqx.modules.interviewRecord.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.firstLogin.service.HrService;
import com.sqx.modules.industry.entity.Industry;
import com.sqx.modules.interviewRecord.entity.InterviewRecord;
import com.sqx.modules.interviewRecord.dao.InterviewRecordDao;
import com.sqx.modules.interviewRecord.service.InterviewRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.message.service.MessageService;
import com.sqx.modules.resumes.entity.Company;
import com.sqx.modules.resumes.entity.PostPush;
import com.sqx.modules.resumes.entity.Resumes;
import com.sqx.modules.resumes.service.CompanyService;
import com.sqx.modules.resumes.service.PostPushService;
import com.sqx.modules.resumes.service.ResumesService;
import com.sqx.modules.utils.SenInfoCheckUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author www.javacoder.top
 * @since 2023-02-08
 */
@Service
public class InterviewRecordServiceImpl extends ServiceImpl<InterviewRecordDao, InterviewRecord> implements InterviewRecordService {
    @Autowired
    private CompanyService companyService;
    @Autowired
    private PostPushService postPushService;
    @Autowired
    private UserService userService;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private ResumesService resumesService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private HrService hrService;

    @Override
    public IPage<InterviewRecord> interviewList(Integer page, Integer limit, InterviewRecord interviewRecord) {
        Page<InterviewRecord> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        IPage<InterviewRecord> selectPage = baseMapper.selectPage(pages, new QueryWrapper<>(interviewRecord).orderByDesc("create_time"));
        List<InterviewRecord> records = selectPage.getRecords();
        for (InterviewRecord record : records) {
            record.setCompany(companyService.getById(record.getCompanyId()));
            record.setPostPush(postPushService.getById(record.getPostPushId()));
            UserEntity userEntity = userService.getById(record.getUserId());
            if (userEntity != null) {
                Resumes resumes = resumesService.getOne(new QueryWrapper<Resumes>().eq("user_id", userEntity.getUserId()));
                if (resumes != null) {
                    userEntity.setResumesId(resumes.getResumesId());
                }
                record.setUserEntity(userEntity);
            }
        }
        return selectPage;
    }

    @Override
    public Result saveInterview(InterviewRecord interviewRecord) {
        if (interviewRecord.getRecordId() != null) {
            return Result.upStatus(baseMapper.updateById(interviewRecord));
        } else {
            InterviewRecord record = baseMapper.selectOne(new QueryWrapper<InterviewRecord>().in("company_id", interviewRecord.getCompanyId()).eq("user_id", interviewRecord.getUserId()).eq("status", 1));
            if (record != null) {
                return Result.error("已发送面试邀请,请等待对方处理");
            }
            interviewRecord.setStatus(1);
            interviewRecord.setIsSendDay(0);
            interviewRecord.setIsSendHour(0);
            interviewRecord.setCreateTime(LocalDateTime.now());

            UserEntity userEntity = userService.getById(interviewRecord.getInterviewerId());
            if (StringUtils.isNotEmpty(userEntity.getClientid())) {
                userService.pushToSingle("面试邀请", "您收到一个面试邀请", userEntity.getClientid());
            }
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setContent("您收到一个面试邀请");
            messageInfo.setTitle("面试邀请");
            messageInfo.setState(String.valueOf(5));
            messageInfo.setUserName(userEntity.getUserName());
            messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
            messageInfo.setCreateAt(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            messageService.saveBody(messageInfo);

            if (StringUtils.isNotBlank(userEntity.getOpenId())) {
                CommonInfo one = commonInfoService.findOne(342);
                Company company = companyService.getById(interviewRecord.getCompanyId());
                UserEntity companyEntity = userService.getById(company.getUserId());
                DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                List<String> msgList = new ArrayList<>();
                msgList.add(company.getCompanyName());
                msgList.add("请点击后查看");
                msgList.add(companyEntity.getPhone());
                msgList.add(interviewRecord.getInterviewDateTime().format(fmt));
                msgList.add(interviewRecord.getRemarks());
                SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 4, null);
            }

            return Result.upStatus(baseMapper.insert(interviewRecord));
        }

    }

    @Override
    public List<InterviewRecord> getRecordList(Integer hour) {

        return baseMapper.getRecordList(hour);


    }

    @Override
    public Result userUpdateInter(Long userId, Long recordId, Integer type) {
        InterviewRecord interview = baseMapper.selectById(recordId);
        if (interview != null) {
            UserEntity userEntity = userService.getById(interview.getUserId());
            if (type == 1) {
                interview.setStatus(2);
            } else {
                interview.setStatus(3);
            }
            int result = baseMapper.updateById(interview);
            if (result > 0) {
                //给用户的通知
                if (StringUtils.isNotBlank(userEntity.getOpenId())) {
                    sendInterViewMsg(userEntity, interview, 1);
                }
                //给企业绑定的用户的通知
                Company company = companyService.getById(interview.getCompanyId());
                UserEntity companyUser = userService.getById(company.getUserId());
                if (StringUtils.isNotBlank(companyUser.getOpenId())) {
                    sendInterViewMsg(companyUser, interview, 2);
                }
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setTitle("面试预约通知");
                Resumes resumes = resumesService.selectResumesByUserId(interview.getUserId());
                if (type == 1) {
                    messageInfo.setContent(resumes.getResumesName() + "同意了您的面试邀请");
                } else {
                    messageInfo.setContent(resumes.getResumesName() + "拒绝了您的面试邀请");
                }
                messageInfo.setState(String.valueOf(8));
                messageInfo.setUserId(companyUser.getUserId().toString());
                messageInfo.setIsSee("0");
                messageService.saveBody(messageInfo);
                if (StringUtils.isNotEmpty(companyUser.getClientid())) {
                    if (type == 1) {
                        userService.pushToSingle("预约通知", "对方已同意", companyUser.getClientid());
                    } else {
                        userService.pushToSingle("预约通知", "对方已拒绝", companyUser.getClientid());
                    }
                }
                return Result.success();
            } else {
                return Result.error("操作失败,请重试!");
            }
        } else {
            return Result.error("面试邀请不存在");
        }
    }

    /**
     * @param userEntity
     * @param interview
     * @param userType   1用户 2企业
     */
    private void sendInterViewMsg(UserEntity userEntity, InterviewRecord interview, Integer userType) {
        CommonInfo tempId = commonInfoService.findOne(337);
        List<String> msgList = new ArrayList<>();
        StringBuilder stringBuilder=new StringBuilder();
        if(StringUtils.isNotEmpty(interview.getProvince())){
            stringBuilder.append(interview.getProvince());
        }
        if(StringUtils.isNotEmpty(interview.getCity())){
            stringBuilder.append(interview.getCity());
        }
        if(StringUtils.isNotEmpty(interview.getCounty())){
            stringBuilder.append(interview.getCounty());
        }
        String content=stringBuilder.toString();
        if(content.length()>20){
            content=content.substring(0,15)+"...";
        }
        msgList.add(content);
        msgList.add(interview.getInterviewDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        Resumes resumes = resumesService.getOne(new QueryWrapper<Resumes>().eq("user_id", interview.getUserId()));
        if (StringUtils.isNotBlank(interview.getRemarks())) {
            content=interview.getRemarks();
            if(interview.getRemarks().length()>20){
                content=interview.getRemarks().substring(0,15)+"...";
            }
            msgList.add(content);
        } else {
            msgList.add("请准时参加,如有变动请及时联系预约人");
        }
        if (userType == 1) {
            Company company = companyService.getById(interview.getCompanyId());
            UserEntity companyUser = userService.getById(company.getUserId());
            content=companyUser.getUserName();
            if(companyUser.getUserName().length()>20){
                content=companyUser.getUserName().substring(0,15)+"...";
            }
            msgList.add(content);
        } else {
            content=resumes.getResumesName();
            if(resumes.getResumesName().length()>20){
                content=resumes.getResumesName().substring(0,15)+"...";
            }
            msgList.add(content);
        }
        SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), tempId.getValue(), msgList, 1, null);
    }

    @Override
    public InterviewRecord getInterviewInfo(Long recordId) {
        InterviewRecord record = baseMapper.selectById(recordId);
        record.setCompany(companyService.getById(record.getCompanyId()));
        record.setPostPush(postPushService.getById(record.getPostPushId()));
        record.setUserEntity(userService.getById(record.getUserId()));
        record.setHr(hrService.getByUserId(String.valueOf(record.getUserId())));
        return record;
    }

    /**
     * 是否能发送简历
     *
     * @param postPushId
     * @param userId
     * @return
     */
    @Override
    public Result isSendView(Long postPushId, Long userId) {
        List<InterviewRecord> records = baseMapper.selectList(new QueryWrapper<InterviewRecord>().eq("user_id", userId).eq("post_push_id", postPushId).in("status", 1, 2));
        if (records.size() > 0) {
            return Result.success().put("data", false);
        } else {
            return Result.success().put("data", true);
        }
    }

    @Override
    public List<Object> selectInterviewList(Long userId) {
        return baseMapper.selectInterviewList(userId);
    }
}
