package jnpf.personnels.utils;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import jnpf.account.PTenantAccountApi;
import jnpf.cultivate.utils.CultivateLearnUtils;
import jnpf.database.util.TenantDataSourceUtil;
import jnpf.model.im.UserAndLinkDTO;
import jnpf.model.personnels.po.FtbPersonnelsStaffRegistrationFormData;
import jnpf.model.personnels.po.FtbPersonnelsStaffRoster;
import jnpf.model.personnels.req.roster.UserAccountDto;
import jnpf.model.user.GenerateHeadFileForm;
import jnpf.model.user.GenerateHeadForm;
import jnpf.permission.UserApi;
import jnpf.permission.dto.SaveUserManagerAddDTO;
import jnpf.personnels.service.*;
import jnpf.util.UserProvider;
import jnpf.util.im.ImMessageNoticeUtils;
import jnpf.utils.FeignHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class PersonnelAsyncServiceUtils {

    @Value("${invite-url}")
    private String joinUrl;

    @Autowired
    @Lazy
    private FtbPersonnelsTurnoverManagementService ftbPersonnelsTurnoverManagementService;

    @Autowired
    @Lazy
    private FtbPersonnelsStaffArchivesHistoryService ftbPersonnelsStaffArchivesHistoryService;

    @Autowired
    @Lazy
    private PTenantAccountApi pTenantAccountApi;

    @Autowired
    @Lazy
    private PersonnelOrgUtils personnelOrgUtils;

    @Autowired
    @Lazy
    private ImMessageNoticeUtils noticeUtils;


    @Autowired
    @Lazy
    private UserApi userApi;

    @Autowired
    @Lazy
    private FtbPersonnelsPermissionsService personnelsPermissionsService;

    @Autowired
    @Lazy
    private FtbPersonnelsStaffRegistrationFormDataService registrationFormDataService;

    @Autowired
    @Lazy
    private FtbPersonnelsStaffEmploymentApplyService staffEmploymentApplyService;

    @Autowired
    private CultivateLearnUtils cultivateLearnUtils;

    @Autowired
    FtbPersonnelsRegularManagementService regularManagementService;


    @Autowired
    FtbPersonnelsTransferManageService transferManageService;

    @Autowired
    FtbPersonnelsSecondmentManagementService secondmentManagementService;


    /**
     * 异步删除用户历史档案信息
     *
     * @param userIds
     * @param tenantCode
     * @param headers
     */

    @Async
    public void deleteTurnoverUserHistory(List<String> userIds, String tenantCode, Map<String, String> headers) {
        try {
            FeignHolder.set(headers);
            TenantDataSourceUtil.switchTenant(tenantCode);
            ftbPersonnelsTurnoverManagementService.deleteResignationApplication(userIds);
            ftbPersonnelsStaffArchivesHistoryService.deleteForUserIds(userIds);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("deleteTurnoverUserHistory 异常");
        } finally {
            FeignHolder.clear();
        }
    }

    /**
     * 异步删除用户历史档案信息
     *
     * @param userIds
     * @param tenantCode
     */

    @Async
    public void asyncAddNewPersonToTask(List<String> userIds, String tenantCode) {
        try {
            TenantDataSourceUtil.switchTenant(tenantCode);
            cultivateLearnUtils.addNewPersonToTask(userIds,tenantCode);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("asyncAddNewPersonToTask 异常");
        } finally {
        }
    }


    @Async
    public void batchGeneralHead(List<GenerateHeadFileForm> headLogoList, String tenantCode, Map<String, String> headers) {
        try {
            log.error("批量生成头像={}", JSONUtil.toJsonStr(headLogoList));
            FeignHolder.set(headers);
            TenantDataSourceUtil.switchTenant(tenantCode);
            GenerateHeadForm generateHeadForm = new GenerateHeadForm();
            generateHeadForm.setFileFormList(headLogoList);
            long start = System.currentTimeMillis();
            pTenantAccountApi.generateDefaultAvatar(generateHeadForm);
            long end = System.currentTimeMillis();
            log.error("批量生成头像调用PTenantAccountApi.generateDefaultAvatar 数量:{} 耗时：{}ms", headLogoList.size(), end - start);
        } catch (Exception e) {
            log.error("批量生成头像异常");
        } finally {
            FeignHolder.clear();
        }
    }

    @Async
    public Boolean sendRegisterForm(String userId,String phone, String tenantCode, Map<String, String> headers) {
        try {
            log.error("发送填写入职登记表alert={}", JSONUtil.toJsonStr(userId));
            FeignHolder.set(headers);
            TenantDataSourceUtil.switchTenant(tenantCode);
            String currJoinUrl = joinUrl + "&phone=" + phone;
            //获取邀请码
            String storeCode = personnelOrgUtils.queryCodeForTenantId(tenantCode);
            UserAndLinkDTO userAndLinkDTO = new UserAndLinkDTO(
                    userId,
                    String.format(currJoinUrl, tenantCode, storeCode)
            );
            noticeUtils.inviteToJoin(List.of(userAndLinkDTO));
            return true;
        } catch (Exception e) {
            log.error("发送填写入职登记表alert异常");
        } finally {
            FeignHolder.clear();
        }
        return false;
    }

    @Async
    public void batchFillAccountForUserId(List<UserAccountDto> list, String tenantCode, Map<String, String> headers) {
        try {
            log.error("花名册导入回填账号信息={}", JSONUtil.toJsonStr(list));
            FeignHolder.set(headers);
            TenantDataSourceUtil.switchTenant(tenantCode);

            if (CollectionUtil.isEmpty(list)) {
                return;
            }
            for (UserAccountDto userAccountDto : list) {
                SaveUserManagerAddDTO dto = new SaveUserManagerAddDTO();
                dto.setAccount(userAccountDto.getAccount());
                dto.setUserId(userAccountDto.getFid());
                dto.setRealName(userAccountDto.getUserName());

                String fileName = userAccountDto.getHeadImageUrl();
                if (StringUtils.isNotEmpty(fileName)) {
                    int lastIndex = fileName.lastIndexOf('/');
                    fileName = fileName.substring(lastIndex + 1);
                }
                dto.setHeadIcon(fileName);
                dto.setNickName(userAccountDto.getUserNickName());
                Boolean aBoolean = userApi.userInfoUpdate(dto);
                if (null == aBoolean || !aBoolean) {
                    log.error("导入回填账号信息异常,dto={},result={}", JSONUtil.toJsonStr(dto), aBoolean);
                } else {
                    log.error("导入回填账号信息正常，修改租户账号,dto={},result={}", JSONUtil.toJsonStr(dto), aBoolean);
                }
            }
        } catch (Exception e) {
            log.error("花名册导入回填账号信息异常");
        } finally {
            FeignHolder.clear();
        }
    }

    @Async
    public void asyncDeleteRosterOtherData(FtbPersonnelsStaffRoster roster, String tenantId, Map<String, String> headers) {
        try {
            FeignHolder.set(headers);
            TenantDataSourceUtil.switchTenant(tenantId);
            personnelsPermissionsService.clearUserPermissions(roster.getUserId());
            //删除动态字段
            // registrationFormDataService.deleteByRosterId(roster.getId());
            //删除入职信息
            staffEmploymentApplyService.deleteByPhone(roster.getPhone());
            //pTenantAccountApi.deleteUser(roster.getUserId());
            // 转正,
            regularManagementService.clearHistoricalConversionData(List.of(roster.getUserId()));
            // 调岗数据
            transferManageService.clearTransferData(List.of(roster.getUserId()));
            // 借调数据
            secondmentManagementService.endByUserConfirm(roster.getUserId(),new Date());
            // 删除离职信息
            ftbPersonnelsTurnoverManagementService.deleteResignationApplication(List.of(roster.getUserId()));
            UserProvider.kickoutByUserId(roster.getUserId(), tenantId);
        } catch (Exception e) {
            log.error("异步删除花名册异常");
        } finally {
            FeignHolder.clear();
        }
    }

}



