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

import cn.axzo.basics.profiles.api.UserProfileServiceApi;
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.service.enums.OrganizationTypeEnum;
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.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

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

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

    private static final long DEFAULT_PAGE_SIZE = 1000;

    /**
     * 只需要清洗templateCode
     */
    public static final List<String> TEMPLATE_CODES = Lists.newArrayList("156981aecdea44ab8a969b586dc600dd");

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

        UpdateRouterParam updateRouterParam = Optional.ofNullable(s)
                .map(e -> JSONObject.parseObject(e, UpdateRouterParam.class))
                .orElseGet(() -> UpdateRouterParam.builder().build());
        long pageNumber = 1;
        while (true) {
            PendingMessageRecordService.PendingMessageRecordPageReq req = PendingMessageRecordService.PendingMessageRecordPageReq.builder()
                    .ids(updateRouterParam.getIds())
                    .orgType(OrganizationTypeEnum.PROJECT)
                    .templateCodes(TEMPLATE_CODES)
                    .build();
            req.setPage(pageNumber++);
            req.setPageSize(DEFAULT_PAGE_SIZE);
            Page<PendingMessageRecord> page = pendingMessageRecordService.page(req);
            log.info("start updateRouterJob,pageNumber:{}", pageNumber);
            if (CollectionUtils.isNotEmpty(page.getList())) {

                List<PendingMessageRecord> pendingMessageRecords = page.getList().parallelStream()
                        .filter(pendingMessageRecord -> {
                            PendingMessageRecord.RouterParams routerParams = pendingMessageRecord.resolveRouterParams();
                            return StringUtils.isBlank(routerParams.getOuId()) || Objects.equals(routerParams.getOuId(), "0");
                        })
                        .map(record -> {
                            PendingMessageRecord pendingMessageRecord = new PendingMessageRecord();
                            pendingMessageRecord.setId(record.getId());
                            pendingMessageRecord.setRouterParams(record.mergeRouterParams(PendingMessageRecord.RouterParams.builder()
                                    .workspaceId(record.getOrgId().toString())
                                    .ouId(record.getOuId().toString())
                                    .build()));
                            return pendingMessageRecord;
                        }).collect(Collectors.toList());
                pendingMessageRecordDao.updateBatchById(pendingMessageRecords);
            }

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

    // page工具后续有统计的提供，所以放这里
    public static <T> boolean hasNext(Page<T> page) {
        return page.getPageNum() < getPages(page);
    }

    public static <T> long getPages(Page<T> page) {
        if (page.getTotalElements() == 0L) {
            return 0L;
        } else {
            long pages = page.getTotalElements() / page.getPageSize();
            if (page.getTotalElements() % page.getPageSize() != 0L) {
                ++pages;
            }
            return pages;
        }
    }


    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    static class MigrateZeroOuIdJobParam {
        private Long id;
    }

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

        private List<Long> ids;
    }
}
