package com.ningdatech.kqapi.scheduler.task;

import cn.hutool.core.date.StopWatch;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.ningdatech.kqapi.common.constant.BizConst;
import com.ningdatech.kqapi.common.enumeration.CommonEnum;
import com.ningdatech.kqapi.common.helper.MatterCacheHelper;
import com.ningdatech.kqapi.zzsfw.manage.MatterManage;
import com.ningdatech.kqapi.zzsfw.model.entity.*;
import com.ningdatech.kqapi.zzsfw.service.ComponentsMatterEliminateService;
import com.ningdatech.kqapi.zzsfw.service.IDscSxAdsShareItemQltQlsxCommonIDVKqService;
import com.ningdatech.kqapi.zzsfw.service.IKqZzsfwMatterDeduplicateService;
import com.ningdatech.kqapi.zzsfw.service.IKqZzsfwMenuService;
import lombok.RequiredArgsConstructor;
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.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Classname SynTask
 * @Description
 * @Date 2024/1/4 9:04
 * @Author PoffyZhang
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class SynTask {
    @Value("${hostname}")
    public String HOST;

    @Value("${task.switch.is-open}")
    private boolean flag;

    @Value("${spring.profiles.active}")
    public String active;

    @Autowired
    private MatterCacheHelper matterCacheHelper;

    @Autowired
    private MatterManage matterManage;

    @Autowired
    private IKqZzsfwMatterDeduplicateService matterDeduplicateService;

    @Autowired
    private IKqZzsfwMenuService menuService;

    @Autowired
    private IDscSxAdsShareItemQltQlsxCommonIDVKqService kqService;

    @Autowired
    private ComponentsMatterEliminateService componentsMatterEliminateService;

    protected LoadingCache<MatterKey, KqZzsfwMattersDeduplicate> mattersDupCache;

    private final String KQ_ZZS_BASE_URL = "https://www.zjzwfw.gov.cn/zjservice-fe/#/workguide?localInnerCode=&siteCode=330000000000";

    /**
     * 每天8:30 同步数据
     */
    @Scheduled(cron = "0 30 8 * * ?")
    public void synData() throws UnknownHostException {
        // 线上环境运行
        if (flag && HOST.equals(InetAddress.getLocalHost().getHostName())) {
            log.info("政务数据 ===================== 同步开始");
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();

            //1.处理 去重数据
            if (matterCacheHelper.refreshAll()) {
                matterManage.removeAllDup();
                List<KqZzsfwMattersDeduplicate> allDup = matterCacheHelper.all();
                matterDeduplicateService.saveBatch(allDup);

                //2. 事项
                List<KqZzsfwMenu> menus = menuService.list();
                for (KqZzsfwMenu menu : menus) {
                    String url = matterCacheHelper.getUrl(menu.getItemName());
                    if (StringUtils.isBlank(url)) {
                        menuService.update(Wrappers.lambdaUpdate(KqZzsfwMenu.class)
                                .eq(KqZzsfwMenu::getId, menu.getId())
                                .set(KqZzsfwMenu::getWebapplyurl, null)
                                .set(KqZzsfwMenu::getHasUrl, CommonEnum.NO.getCode()));
                    } else {
                        menuService.update(Wrappers.lambdaUpdate(KqZzsfwMenu.class)
                                .eq(KqZzsfwMenu::getId, menu.getId())
                                .set(KqZzsfwMenu::getWebapplyurl, url)
                                .set(KqZzsfwMenu::getHasUrl, CommonEnum.YES.getCode()));
                    }
                }
            }

            stopWatch.stop();
            log.info("政务数据 ===================== 同步总共耗时 :{} s", stopWatch.getTotalTimeSeconds());
        }
    }

    public void synMenu() {
        //2. 事项
        List<KqZzsfwMenu> menus = menuService.list();
        for (KqZzsfwMenu menu : menus) {
            String url = matterCacheHelper.getUrl(menu.getItemName());
            log.info("当前缓存的数据 : {},{}", menu.getItemName(), url);
            if (StringUtils.isBlank(url)) {
                menuService.update(Wrappers.lambdaUpdate(KqZzsfwMenu.class)
                        .eq(KqZzsfwMenu::getId, menu.getId())
                        .set(KqZzsfwMenu::getWebapplyurl, null)
                        .set(KqZzsfwMenu::getHasUrl, CommonEnum.NO.getCode()));
            } else {
                menuService.update(Wrappers.lambdaUpdate(KqZzsfwMenu.class)
                        .eq(KqZzsfwMenu::getId, menu.getId())
                        .set(KqZzsfwMenu::getWebapplyurl, url)
                        .set(KqZzsfwMenu::getHasUrl, CommonEnum.YES.getCode()));
            }
        }
    }

    public String synEliminate(List<String> keys) {
        // 添加剔除信息
        List<ComponentsMatterEliminateEntity> entityList = new ArrayList<>();
        keys.forEach(key -> {
            ComponentsMatterEliminateEntity one = componentsMatterEliminateService.getOne(Wrappers.lambdaQuery(ComponentsMatterEliminateEntity.class)
                    .eq(ComponentsMatterEliminateEntity::getQlName, key));
            if (Objects.isNull(one)) {
                entityList.add(new ComponentsMatterEliminateEntity(key, "1"));
            }
            // 删除缓存
            DscSxAdsShareItemQltQlsxCommonIDVKq matter = getSynUrl(key);
            String url = KQ_ZZS_BASE_URL.replace("localInnerCode=", "localInnerCode=" + matter.getQlInnerCode());
            MatterKey matterKey = MatterKey.of(matter.getQlName(), url);
            try {
                mattersDupCache.invalidate(matterKey);
            } catch (Exception e) {
                log.error("mattersDupCache is null", e.getMessage());
            }
        });
        componentsMatterEliminateService.saveBatch(entityList);

        // 删除menu表
        menuService.remove(new LambdaQueryWrapper<KqZzsfwMenu>()
                .in(KqZzsfwMenu::getItemName, keys));

        // 删除deduplicate表
        matterDeduplicateService.remove(new LambdaQueryWrapper<KqZzsfwMattersDeduplicate>()
                .in(KqZzsfwMattersDeduplicate::getQlName, keys));

        return "剔除成功";
    }

    public DscSxAdsShareItemQltQlsxCommonIDVKq getSynUrl(String key) {
        DscSxAdsShareItemQltQlsxCommonIDVKq matter = kqService
                .getOne(Wrappers.lambdaQuery(DscSxAdsShareItemQltQlsxCommonIDVKq.class)
                        .select(DscSxAdsShareItemQltQlsxCommonIDVKq::getRowguid,
                                DscSxAdsShareItemQltQlsxCommonIDVKq::getQlName,
                                DscSxAdsShareItemQltQlsxCommonIDVKq::getQlState,
                                DscSxAdsShareItemQltQlsxCommonIDVKq::getQlInnerCode,
                                DscSxAdsShareItemQltQlsxCommonIDVKq::getWebapplyurl)
                        .eq(DscSxAdsShareItemQltQlsxCommonIDVKq::getQlName, key)
                        .eq(DscSxAdsShareItemQltQlsxCommonIDVKq::getQlState, "1")
                        .isNotNull(DscSxAdsShareItemQltQlsxCommonIDVKq::getWebapplyurl)
                        // 确保getQlInnerCodeItem字段不为null
                        .isNotNull(DscSxAdsShareItemQltQlsxCommonIDVKq::getQlInnerCode)
                        .orderByDesc(DscSxAdsShareItemQltQlsxCommonIDVKq::getUpdateDate)
                        .last(BizConst.LIMIT_1));
        return matter;
    }

    public void synSingle(String key) {
        DscSxAdsShareItemQltQlsxCommonIDVKq matter = getSynUrl(key);
        String url = KQ_ZZS_BASE_URL.replace("localInnerCode=", "localInnerCode=" + matter.getQlInnerCode());
        List<KqZzsfwMenu> menus = menuService.list(Wrappers.lambdaQuery(KqZzsfwMenu.class)
                .eq(KqZzsfwMenu::getItemName, key));
        menus.forEach(menu -> menuService.update(Wrappers.lambdaUpdate(KqZzsfwMenu.class)
                .eq(KqZzsfwMenu::getId, menu.getId())
                .set(KqZzsfwMenu::getWebapplyurl, url)
                .set(KqZzsfwMenu::getHasUrl, CommonEnum.YES.getCode())));
        // 更新缓存
        MatterKey matterKey = MatterKey.of(matter.getQlName(), url);
        mattersDupCache.invalidate(matterKey);
        mattersDupCache.put(matterKey, KqZzsfwMattersDeduplicate.of(matter.getQlName(), url));
    }
}
