package com.kingdee.eas.custom.recuritment.task;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.metadata.entity.*;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.shr.recuritment.IRecuritmentDemand;
import com.kingdee.shr.recuritment.RecuritmentDemandCollection;
import com.kingdee.shr.recuritment.RecuritmentDemandFactory;
import com.kingdee.shr.recuritment.RecuritmentDemandInfo;
import com.kingdee.util.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.log4j.Logger;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class RecuritmentFacadeControllerBean extends AbstractRecuritmentFacadeControllerBean {
    private static Logger logger =
            Logger.getLogger(RecuritmentFacadeControllerBean.class);


    // 北京时区/shanghai时区
//    private static final ZoneId BEIJING_ZONE = ZoneId.of("Asia/Shanghai");

    private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 同步北森简历和附件
     *
     * @param ctx
     * @param applyId
     * @throws BOSException
     * @throws EASBizException
     */
    @Override
    protected void _syncBeisenResume(Context ctx, String applyId) throws BOSException, EASBizException {
        super._syncBeisenResume(ctx, applyId);
    }

    @Override
    protected void _syncRecuritmentToBeisen(Context ctx, String billId) throws BOSException, EASBizException {
        super._syncRecuritmentToBeisen(ctx, billId);

        IRecuritmentDemand dIns = RecuritmentDemandFactory.getLocalInstance(ctx);
        RecuritmentDemandInfo recuritmentDemandInfo = dIns.getRecuritmentDemandInfo(new ObjectUuidPK(billId));
        RecruitmentDemandService recruitmentDemandService = new RecruitmentDemandService(false);
        //更新或新增
        try {
            Object requirementId = recuritmentDemandInfo.get("requirementId");
            if (ObjectUtils.allNotNull(requirementId)) {
                recruitmentDemandService.updateRequirement(ctx, String.valueOf(requirementId), recuritmentDemandInfo);
            } else {
                recruitmentDemandService.createRecruitmentDemand(ctx, recuritmentDemandInfo);
            }
        } catch (Exception e) {
            SelectorItemCollection selectorCol = new SelectorItemCollection();
            selectorCol.add(new SelectorItemInfo("syncBeisenResult"));
            String message = e.getMessage();
            recuritmentDemandInfo.put("syncBeisenResult", "失败: " + message);
            dIns.updatePartial(recuritmentDemandInfo, selectorCol);
            throw new RuntimeException(e);
        }
    }


    /**
     * 招聘需求更新
     * coyle
     */
    @Override
    protected void _updateRecuritment(Context ctx, String startDate, String endDate, int offset)
            throws BOSException, EASBizException {
        super._updateRecuritment(ctx, startDate, endDate, offset);

        // 0. 参数校验与日期解析
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate start = LocalDate.now();
        LocalDate end = LocalDate.now();
        //如果时间参数都为空,则使用offset参数
        if (StringUtils.isEmpty(startDate) && StringUtils.isEmpty(endDate)) {
            if (offset > 0) {
                //eDate增加offset天
                end = end.plusDays(offset);
            } else if (offset < 0) {
                start = start.plusDays(offset);
            }
        }
        if (!StringUtils.isEmpty(startDate)) {
            //开始日期字定义,结束日期都是今天
            start = LocalDate.parse(startDate, dateFormatter);
        }
        if (!StringUtils.isEmpty(endDate)) {
            //开始日期,结束日期都是今天
            end = LocalDate.parse(endDate, dateFormatter);
        }
        if (start.isAfter(end)) {
            throw new BOSException("开始日期不能晚于结束日期");
        }

        // LocalDate 转 String (使用之前的 dateFormatter)
        String startStr = toStartTime(start.format(dateFormatter));
        String endStr = toEndTime(end.format(dateFormatter));

        IRecuritmentDemand localInstance = RecuritmentDemandFactory.getLocalInstance(ctx);
        EntityViewInfo ev = new EntityViewInfo();
        FilterInfo filter = new FilterInfo();
        filter.getFilterItems().add(new FilterItemInfo("requirementId", null, CompareType.NOTEMPTY));
        filter.getFilterItems().add(new FilterItemInfo("lastUpdateTime", startStr, CompareType.GREATER_EQUALS));
        filter.getFilterItems().add(new FilterItemInfo("lastUpdateTime", endStr, CompareType.LESS_EQUALS));
        ev.setFilter(filter);

        RecuritmentDemandCollection recuritmentDemandCollection = localInstance.getRecuritmentDemandCollection(ev);
        for (int i = 0; i < recuritmentDemandCollection.size(); i++) {
            RecuritmentDemandInfo recuritmentDemandInfo = recuritmentDemandCollection.get(i);
            _syncRecuritmentToBeisen(ctx, recuritmentDemandInfo.getId().toString());
        }

    }


    /**
     * 将日期字符串转换为一天的开始时间（UTC格式）
     *
     * @param dateStr "yyyy-MM-dd"格式的日期字符串
     * @return Moka API要求的时间格式
     */
    public static String toStartTime(String dateStr) {
        LocalDate date = LocalDate.parse(dateStr);
        LocalDateTime startOfDay = date.atStartOfDay();
        return TIME_FORMATTER.format(startOfDay);
    }

    /**
     * 将日期字符串转换为一天的结束时间（UTC格式）
     *
     * @param dateStr "yyyy-MM-dd"格式的日期字符串
     * @return Moka API要求的时间格式
     */
    public static String toEndTime(String dateStr) {
        LocalDate date = LocalDate.parse(dateStr);
        LocalDateTime endOfDay = date.atTime(23, 59, 59);
        return TIME_FORMATTER.format(endOfDay);
    }


}
