package cn.axzo.msg.center.message.xxl;

import cn.axzo.basics.profiles.api.UserProfileServiceApi;
import cn.axzo.basics.profiles.dto.basic.IdentityProfileDto;
import cn.axzo.basics.profiles.dto.request.QueryIdentityProfileDto;
import cn.axzo.msg.center.dal.PendingMessageRecordDao;
import cn.axzo.msg.center.domain.entity.PendingMessageRecord;
import cn.axzo.msg.center.inside.notices.service.PendingMessageRecordService;
import cn.axzo.msg.center.message.migrate.OuIdMigrateService;
import cn.axzo.msg.center.service.enums.YesOrNo;
import cn.azxo.framework.common.model.Page;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Component
@RequiredArgsConstructor
public class UpdateOuIdJob extends IJobHandler {


    @Autowired
    private OuIdMigrateService ouIdMigrateService;
    @Autowired
    private PendingMessageRecordService pendingMessageRecordService;
    @Autowired
    private UserProfileServiceApi userProfileServiceApi;
    @Autowired
    private PendingMessageRecordDao pendingMessageRecordDao;

    private static final long DEFAULT_PAGE_SIZE = 3000;

    @Override
    @XxlJob("updateOuIdJob")
    public ReturnT<String> execute(String s) throws Exception {
        log.info("start updateOuIdJob,s:{}", s);

        UpdateOuIdParam updateOuIdParam = Optional.ofNullable(s)
                .map(e -> JSONObject.parseObject(e, UpdateOuIdParam.class))
                .orElseGet(() -> UpdateOuIdParam.builder().build());

        long pageNumber = 1;
        while (true) {
            PendingMessageRecordService.PendingMessageRecordPageReq req = PendingMessageRecordService.PendingMessageRecordPageReq.builder()
                    .isOuIdMigrated(YesOrNo.NO)
                    .ids(updateOuIdParam.getIds())
                    .templateCodes(UpdateRouterJob.TEMPLATE_CODES)
                    .build();
            req.setPage(pageNumber++);
            req.setPageSize(DEFAULT_PAGE_SIZE);
            Page<PendingMessageRecord> page = pendingMessageRecordService.page(req);
            log.info("start updateOuIdJob,pageNumber:{}, pageListSize:{}", pageNumber, page.getList().size());

            if (CollectionUtils.isNotEmpty(page.getList())) {
                log.info("updateOuIdJob begin migrate");
                // 一条一个更新，需要优化，
                ouIdMigrateService.migrate(page.getList());
                log.info("updateOuIdJob end migrate");
            }

            if (!UpdateRouterJob.hasNext(page)) {
                break;
            }
        }
        log.info("end updateOuIdJob");
        return ReturnT.SUCCESS;
    }


    private void updateExecutorPerson(List<PendingMessageRecord> pendingMessageRecords) {

        List<PendingMessageRecord> updatePendingMessageRecords = pendingMessageRecords.stream()
                .filter(pendingMessageRecord -> pendingMessageRecord.getExecutorPersonId() == null
                        || pendingMessageRecord.getExecutorPersonId() == 0)
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(updatePendingMessageRecords)) {
            return;
        }

        // 根据executorId和executorType 解析对应的executorPerson
        List<PendingMessageRecord> updatePendingMessageRecords2 = updatePendingMessageRecords.parallelStream()
                .map(record -> {
                    List<Long> identityIds = Lists.newArrayList();
                    identityIds.add(record.getExecutorId());
                    IdentityProfileDto identityProfileDto = userProfileServiceApi.getIdentityProfileDto(QueryIdentityProfileDto.builder()
                                    .identityIds(identityIds)
                                    .IdentityType(record.getExecutorType().getCode())
                                    .build())
                            .getData()
                            .stream()
                            .findFirst()
                            .orElse(null);
                    if (identityProfileDto == null) {
                        log.info("identityProfileDto not found: {}", record.getExecutorId(), record.getExecutorType());
                        return null;
                    }
                    PendingMessageRecord pendingMessageRecord = new PendingMessageRecord();
                    pendingMessageRecord.setId(record.getId());
                    pendingMessageRecord.setUpdateAt(new Date());
                    pendingMessageRecord.setExecutorPersonId(identityProfileDto.getPersonProfile().getId());
                    pendingMessageRecord.setExecutorName(identityProfileDto.getPersonProfile().getRealName());
                    return pendingMessageRecord;
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        pendingMessageRecordDao.updateBatchById(updatePendingMessageRecords2);
    }

    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class UpdateOuIdParam {

        private List<Long> ids;
    }
}
