package com.zhongzheng.modules.recruit.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.zhongzheng.common.core.domain.model.LoginUser;
import com.zhongzheng.common.exception.CustomException;
import com.zhongzheng.common.utils.DateUtils;
import com.zhongzheng.common.utils.ServletUtils;
import com.zhongzheng.modules.course.domain.MajorCategory;
import com.zhongzheng.modules.recruit.bo.*;
import com.zhongzheng.modules.recruit.domain.RecruitResume;
import com.zhongzheng.modules.recruit.service.IRecruitInterviewLogService;
import com.zhongzheng.modules.recruit.service.IRecruitNeedsService;
import com.zhongzheng.modules.recruit.service.IRecruitResumeService;
import com.zhongzheng.modules.recruit.vo.*;
import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.zhongzheng.modules.recruit.domain.RecruitInterview;
import com.zhongzheng.modules.recruit.mapper.RecruitInterviewMapper;
import com.zhongzheng.modules.recruit.service.IRecruitInterviewService;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 招聘面试关联Service业务层处理
 *
 * @author ruoyi
 * @date 2021-08-20
 */
@Service
public class RecruitInterviewServiceImpl extends ServiceImpl<RecruitInterviewMapper, RecruitInterview> implements IRecruitInterviewService {

    @Autowired
    private IRecruitResumeService iRecruitResumeService;

    @Autowired
    private IRecruitInterviewLogService recruitInterviewLogService;



    @Override
    public RecruitInterviewVo queryById(Long interviewId){
        RecruitInterview db = this.baseMapper.selectById(interviewId);
        return BeanUtil.toBean(db, RecruitInterviewVo.class);
    }


    @Override
    public List<RecruitInterviewVo> queryList(RecruitInterviewQueryBo bo) {
        LambdaQueryWrapper<RecruitInterview> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getYear() != null, RecruitInterview::getYear, bo.getYear());
        lqw.eq(bo.getMonth() != null, RecruitInterview::getMonth, bo.getMonth());
        lqw.eq(bo.getDay() != null, RecruitInterview::getDay, bo.getDay());
        lqw.eq(bo.getTimingStart() != null, RecruitInterview::getTimingStart, bo.getTimingStart());
        lqw.eq(bo.getTimingEnd() != null, RecruitInterview::getTimingEnd, bo.getTimingEnd());
        lqw.eq(bo.getNeedsId() != null, RecruitInterview::getNeedsId, bo.getNeedsId());
        lqw.eq(StrUtil.isNotBlank(bo.getResumeJson()), RecruitInterview::getResumeJson, bo.getResumeJson());
        lqw.eq(bo.getStatus() != null, RecruitInterview::getStatus, bo.getStatus());
        lqw.eq(bo.getTenantId() != null, RecruitInterview::getTenantId, bo.getTenantId());
        lqw.eq(bo.getUserId() != null, RecruitInterview::getUserId, bo.getUserId());
        lqw.eq(StrUtil.isNotBlank(bo.getAttachUrl()), RecruitInterview::getAttachUrl, bo.getAttachUrl());
        lqw.eq(StrUtil.isNotBlank(bo.getRefuse()), RecruitInterview::getRefuse, bo.getRefuse());
        lqw.eq(bo.getResumeTime() != null, RecruitInterview::getResumeTime, bo.getResumeTime());
        lqw.eq(StrUtil.isNotBlank(bo.getLinkMan()), RecruitInterview::getLinkMan, bo.getLinkMan());
        lqw.eq(StrUtil.isNotBlank(bo.getLinkTel()), RecruitInterview::getLinkTel, bo.getLinkTel());
        lqw.like(StrUtil.isNotBlank(bo.getCompanyName()), RecruitInterview::getCompanyName, bo.getCompanyName());
        lqw.eq(StrUtil.isNotBlank(bo.getEmall()), RecruitInterview::getEmall, bo.getEmall());
        lqw.eq(bo.getStartYear() != null, RecruitInterview::getStartYear, bo.getStartYear());
        lqw.eq(bo.getUserBirth() != null, RecruitInterview::getUserBirth, bo.getUserBirth());
        lqw.eq(StrUtil.isNotBlank(bo.getEduLevel()), RecruitInterview::getEduLevel, bo.getEduLevel());
        lqw.eq(bo.getCompleteness() != null, RecruitInterview::getCompleteness, bo.getCompleteness());
        return entity2Vo(this.list(lqw));
    }

    @Override
    public List<RecruitInterviewExcel> queryExcelsList(RecruitInterviewQueryBo bo) {
        List<RecruitInterviewExcel> recruitInterviewExcels = baseMapper.selectQueryExcel(bo);
        for (int i = 0; i < recruitInterviewExcels.size(); i++) {
            recruitInterviewExcels.get(i).setSerial(i+1);
        }
        return recruitInterviewExcels;
    }

    /**
    * 实体类转化成视图对象
    *
    * @param collection 实体类集合
    * @return
    */
    private List<RecruitInterviewVo> entity2Vo(Collection<RecruitInterview> collection) {
        List<RecruitInterviewVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, RecruitInterviewVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<RecruitInterview> page = (Page<RecruitInterview>)collection;
            Page<RecruitInterviewVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page,pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }

    @Override
    public Boolean insertByAddBo(RecruitInterviewAddBo bo) {
        RecruitInterview add = BeanUtil.toBean(bo, RecruitInterview.class);
        validEntityBeforeSave(add);
        RecruitResumeVo recruitResumeVo = iRecruitResumeService.queryById(bo.getResumeId());
        if(checkDelivery(add)){
            throw new CustomException("你已投递过该岗位");
        }
        if(recruitResumeVo==null){
            throw new CustomException("简历不存在");
        }
        add.setStatus(1);
        add.setResumeJson(JSONObject.toJSONString(recruitResumeVo));
        add.setStartYear(recruitResumeVo.getStartYear());
        add.setUserBirth(recruitResumeVo.getUserBirth());
        add.setEduLevel(recruitResumeVo.getEduLevel());
        add.setCompleteness(recruitResumeVo.getCompleteness());
        add.setCreateTime(DateUtils.getNowTime());
        add.setUpdateTime(DateUtils.getNowTime());
        boolean save = this.save(add);
        RecruitInterviewLogAddBo recruitInterviewLogAddBo = new RecruitInterviewLogAddBo();
        recruitInterviewLogAddBo.setInterviewId(add.getInterviewId());
        recruitInterviewLogAddBo.setStatus(3);
        recruitInterviewLogAddBo.setCreateTime(DateUtils.getNowTime());
        recruitInterviewLogAddBo.setUpdateTime(DateUtils.getNowTime());
        recruitInterviewLogAddBo.setUserId(bo.getUserId());
        Boolean aBoolean = recruitInterviewLogService.insertByAddBo(recruitInterviewLogAddBo);
        return save;
    }

    @Override
    public Boolean updateByEditBo(RecruitInterviewEditBo bo) {
        RecruitInterview update = BeanUtil.toBean(bo, RecruitInterview.class);
        validEntityBeforeSave(update);
        update.setUpdateTime(DateUtils.getNowTime());
        return this.updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(RecruitInterview entity){
        //TODO 做一些数据校验,如唯一约束
    }

    private boolean checkDelivery(RecruitInterview entity) {
        RecruitInterview info = getOne(new LambdaQueryWrapper<RecruitInterview>()
                .eq(RecruitInterview::getUserId,entity.getUserId())
                .eq(RecruitInterview::getNeedsId,entity.getNeedsId())
                .last("limit 1"));
        if (Validator.isNotNull(info)) {
            return true;
        }
        return false;
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return this.removeByIds(ids);
    }

    @Override
    public CalendarInterviewVo queryListCalendar(RecruitInterviewQueryBo bo) {
        Calendar cal = Calendar.getInstance();
        CalendarInterviewVo calendarInterviewVo = new CalendarInterviewVo();
        //得到日历日期
        if (bo.getMonth() == null){
            bo.setMonth(cal.get(Calendar.MONTH)+1);
        }
        if(bo.getYear() == null){
            bo.setYear(cal.get(Calendar.YEAR));
        }
        if(bo.getDay() == null){
            throw new IllegalArgumentException("日期为空");
        }

        List<DayInterviewVo> dayStudyVosOne = null;
        try {
            dayStudyVosOne = getDays(bo.getYear(),bo.getMonth(),bo.getDay());
        } catch (ParseException e) {
            throw new RuntimeException("服务器正忙，请稍后重试");
        }
        for (DayInterviewVo dayInterviewVo : dayStudyVosOne) {
            for (QuantumVo quantumVo : dayInterviewVo.getQuantumList()) {
                List<RecruitInterviewVo> recruitInterviewVos = baseMapper.selectByDay(
                        Convert.toInt(dayInterviewVo.getDate()),bo.getMonth(), bo.getYear(), quantumVo.getTimingStart(), quantumVo.getTimingEnd(),
                        bo.getStatusIds());
                for (RecruitInterviewVo recruitInterviewVo : recruitInterviewVos) {
                        RecruitResumeVo recruitResumeVo = JSON.parseObject(recruitInterviewVo.getResumeJson(), new TypeReference<RecruitResumeVo>() {
                        });
                        recruitInterviewVo.setRecruitResumeVo(recruitResumeVo);
                }
                quantumVo.setRecruitInterviewList(recruitInterviewVos);
            }
        }
        calendarInterviewVo.setYear(Convert.toLong(bo.getYear()));
        calendarInterviewVo.setMonth(Convert.toLong(bo.getMonth()));
        calendarInterviewVo.setDayInterviewVos(dayStudyVosOne);
        return calendarInterviewVo;
    }

    @Override
    public List<RecruitInterviewVo> queryListAll(RecruitInterviewQueryBo bo) {
        List<RecruitInterviewVo> recruitInterviewVos = baseMapper.selectByListAll(bo);
        for (RecruitInterviewVo recruitInterviewVo : recruitInterviewVos) {
            RecruitResumeVo recruitResumeVo = JSON.parseObject(recruitInterviewVo.getResumeJson(), new TypeReference<RecruitResumeVo>() {
            });
            recruitInterviewVo.setRecruitResumeVo(recruitResumeVo);
        }
        return recruitInterviewVos;
    }

    @Override
    public RecruitInterviewUserVo interviewUserId(Long interviewUserId, LoginUser loginUser) {


        RecruitInterviewUserVo recruitInterviewUserVo = baseMapper.interviewUserId(interviewUserId);
        RecruitResumeVo recruitResumeVo = JSON.parseObject(recruitInterviewUserVo.getResumeJson(), new TypeReference<RecruitResumeVo>() {
        });
        recruitInterviewUserVo.setRecruitResumeVo(recruitResumeVo);

        RecruitInterviewLogQueryBo recruitInterviewLogQueryBo = new RecruitInterviewLogQueryBo();
        recruitInterviewLogQueryBo.setInterviewId(interviewUserId);
        List<RecruitInterviewLogVo> recruitInterviewLogVos = recruitInterviewLogService.queryList(recruitInterviewLogQueryBo);
        for (RecruitInterviewLogVo recruitInterviewLogVo : recruitInterviewLogVos) {
            if (recruitInterviewLogVo.getStatus() == 1 || recruitInterviewLogVo.getStatus() == 2){
                recruitInterviewLogVo.setUserName(baseMapper.selectSysUserName(recruitInterviewLogVo.getSysUserId()));
            }else {
                recruitInterviewLogVo.setUserName(baseMapper.selectUserName(recruitInterviewLogVo.getUserId()));
            }
        }
        if (!CollectionUtils.isEmpty(recruitInterviewLogVos)){
            recruitInterviewUserVo.setRecruitInterviewLogVoList(recruitInterviewLogVos);
        }

        RecruitInterviewLogAddBo recruitInterviewLogAddBo = new RecruitInterviewLogAddBo();
        recruitInterviewLogAddBo.setInterviewId(interviewUserId);
        recruitInterviewLogAddBo.setStatus(2);
        recruitInterviewLogAddBo.setCreateTime(DateUtils.getNowTime());
        recruitInterviewLogAddBo.setUpdateTime(DateUtils.getNowTime());
        recruitInterviewLogAddBo.setSysUserId(loginUser.getUser().getUserId());
        Boolean aBoolean = recruitInterviewLogService.insertByAddBo(recruitInterviewLogAddBo);

        return recruitInterviewUserVo;
    }

    @Override
    public List<RecruitInterviewVo> queryListAppAll(RecruitInterviewQueryBo bo) {
        List<RecruitInterviewVo> recruitInterviewVos = baseMapper.queryListAppAll(bo);
        for (RecruitInterviewVo recruitInterviewVo : recruitInterviewVos) {
            RecruitResumeVo recruitResumeVo = JSON.parseObject(recruitInterviewVo.getResumeJson(), new TypeReference<RecruitResumeVo>() {
            });
            recruitInterviewVo.setRecruitResumeVo(recruitResumeVo);
        }
        return recruitInterviewVos;
    }


    private static List<DayInterviewVo> getDays(int year, int month,int day) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        //自定义时间
        String recipeTime = year+"-"+month+"-"+day;
        //现在时间
        //String  recipeTime=simpleDateFormat.format(new Date());

        calendar.setTime(simpleDateFormat.parse(recipeTime));
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        int week = calendar.get(Calendar.DAY_OF_WEEK);
        if (1 == week) {
            calendar.add(Calendar.DAY_OF_MONTH, -1);
        }
        int getDayFirst =calendar.get(Calendar.DAY_OF_WEEK);
        calendar.add(Calendar.DATE, calendar.getFirstDayOfWeek() - getDayFirst);
        //本周星期一
        String beginDate = simpleDateFormat.format(calendar.getTime());
        //本周星期日
        calendar.add(Calendar.DATE, 6);
        String endDate = simpleDateFormat.format(calendar.getTime());
        List<DayInterviewVo> dayInterviewVos = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            calendar.setFirstDayOfWeek(Calendar.MONDAY);
            calendar.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY);
            long time = calendar.getTimeInMillis() + 24*60*60*1000*i;
            String sunday = simpleDateFormat.format(time);
            String strh = sunday.substring(sunday.length() -2,sunday.length());
            DayInterviewVo dayInterviewVo = new DayInterviewVo();
            dayInterviewVo.setDate(Convert.toLong(strh));
            dayInterviewVo.setStudyDay(Convert.toLong(i+1));
            dayInterviewVos.add(dayInterviewVo);
            List<QuantumVo> quantumList = new ArrayList<>();
            for (int j = 0; j < 24; j++) {
                QuantumVo quantumVo = new QuantumVo();
                quantumVo.setTimingStart(Convert.toLong(j));
                quantumVo.setTimingEnd(Convert.toLong(j+1));
                quantumList.add(quantumVo);
            }
            dayInterviewVo.setQuantumList(quantumList);
        }
        return dayInterviewVos;
    }

}
