package com.mingzuozhibi.modules.spider;

import com.mingzuozhibi.commons.base.BaseKeys.Name;
import com.mingzuozhibi.commons.base.PageController;
import com.mingzuozhibi.commons.logger.LoggerBind;
import com.mingzuozhibi.modules.disc.DiscRepository;
import com.mingzuozhibi.modules.record.RecordCompute;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;

import static com.mingzuozhibi.support.ChecksUtils.paramNotExists;
import static com.mingzuozhibi.support.ModifyUtils.*;

@RestController
@LoggerBind(Name.SERVER_USER)
public class SpiderController extends PageController {

    @Autowired
    private RecordCompute recordCompute;

    @Autowired
    private ContentService contentService;

    @Autowired
    private DiscRepository discRepository;

    @Autowired
    private HistoryRepository historyRepository;

    @Transactional
    @GetMapping(value = "/api/spider/discShelfs", produces = MEDIA_TYPE)
    public String discShelfs(@RequestParam(defaultValue = "1") int page,
                             @RequestParam(defaultValue = "20") int size) {
        if (size > 40) {
            return errorResult("Size不能大于40");
        }
        var pageRequest = PageRequest.of(page - 1, size, Sort.by(Order.desc("id")));
        var pageResult = historyRepository.findAll(pageRequest);
        return pageResult(pageResult);
    }

    @Transactional
    @PreAuthorize("hasRole('BASIC')")
    @GetMapping(value = "/api/spider/fetchCount", produces = MEDIA_TYPE)
    public String fetchCount() {
        return dataResult(discRepository.countActiveDiscs());
    }

    @Transactional
    @PreAuthorize("hasRole('BASIC')")
    @GetMapping(value = "/api/spider/searchDisc/{asin}", produces = MEDIA_TYPE)
    public String searchDisc(@PathVariable String asin) {
        var byAsin = discRepository.findByAsin(asin);
        if (byAsin.isPresent()) {
            // 碟片已存在
            return dataResult(byAsin.get().toJson());
        }
        var result = contentService.doGet(asin);
        if (result.hasError()) {
            // 查询失败
            return errorResult(result.getMessage());
        }
        var disc = contentService.createWith(result.getData());
        if (disc.getReleaseDate() == null) {
            // 检查日期
            bind.warning("[创建碟片时缺少发售日期][碟片=%s]".formatted(disc.getLogName()));
            disc.setReleaseDate(LocalDate.now());
        }
        // 创建碟片
        discRepository.save(disc);
        historyRepository.setTracked(asin, true);
        bind.success(logCreate("碟片(查询)", disc.getLogName(), disc.toJson().toString()));
        return dataResult(disc.toJson());
    }

    @Transactional
    @PreAuthorize("hasRole('BASIC')")
    @PostMapping(value = "/api/spider/computePt/{id}", produces = MEDIA_TYPE)
    public String computePt(@PathVariable Long id) {
        var byId = discRepository.findById(id);
        if (byId.isEmpty()) {
            return paramNotExists("碟片ID");
        }
        var disc = byId.get();
        var pt1 = disc.getTotalPt();
        recordCompute.computeDisc(disc);
        var pt2 = disc.getTotalPt();
        bind.info(logUpdate("碟片PT", pt1, pt2, disc.getLogName()));
        return dataResult("compute: " + pt1 + "->" + pt2);
    }

}

@@ -298,16 +298,68 @@
 ompute;%0A
+import com.mingzuozhibi.modules.vultr.VultrContext;%0A
 import o
@@ -995,16 +995,71 @@
 ller %7B%0A%0A
+    @Autowired%0A    private VultrContext vultrContext;%0A%0A
     @Aut
@@ -3677,10 +3677,416 @@
 %0A    %7D%0A%0A
+    @Transactional%0A    @GetMapping(value = %22/admin/setDisable/%7Bdisable%7D%22)%0A    public void setDisable(@PathVariable Boolean disable) %7B%0A        var bean = vultrContext.getDisable();%0A        var value = bean.getValue();%0A        bean.setValue(disable);%0A        if (!value.equals(disable)) %7B%0A            amqpSender.bind(Name.SERVER_CORE).notify(%22Change Vultr Disable = %25b%22.formatted(disable));%0A        %7D%0A    %7D%0A%0A
 %7D%0A

Add /admin/setDisable api