package com.hz.pm.api.scheduler.task;

import cn.hutool.core.date.StopWatch;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.hz.pm.api.ding.constants.DingOrganizationContant;
import com.hz.pm.api.ding.task.EmployeeBatchGetTask;
import com.hz.pm.api.organization.model.entity.DingOrganization;
import com.hz.pm.api.organization.service.IDingOrganizationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

/**
 * @author liuxinxin
 * @date 2023/1/12 上午9:53
 * 批量获取/更新部门信息任务
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class BatchUpdateEmployeeTask {

    @Value("${hostname}")
    private String HOST_NAME;

    private final EmployeeBatchGetTask employeeBatchGetTask;
    private final IDingOrganizationService organizationService;

    //@Scheduled(cron = "0 45 1 * * ?")
    public void doTask() throws UnknownHostException {
        if (!HOST_NAME.equals(InetAddress.getLocalHost().getHostName())) {
            return;
        }

        log.info("=========== 每日更新 浙政钉员工信息 (根据现有单位) ======== 任务开始");
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        // 1.查出浙政钉 所有单位
        List<DingOrganization> units = organizationService.list(Wrappers.lambdaQuery(DingOrganization.class)
                .in(DingOrganization::getTypeCode, Lists.newArrayList(
                        DingOrganizationContant.UNIT_TYPE,DingOrganizationContant.GOV_TEMPORARY
                )));

        log.info("需要更新的 单位数量为 {}",units.size());

        for(DingOrganization organization :  units){
            log.info("当前单位是 {}",organization.getOrganizationName());
            employeeBatchGetTask.batchGetEmployeeTaskByOrdCode(organization.getOrganizationCode());
        }

        stopWatch.stop();
        log.info("=========== 每日更新 浙政钉员工信息 (根据现有单位) ======== 任务结束 {}s", stopWatch.getTotalTimeSeconds());
    }

}
