package com.spider.quartz.controller;

import com.spider.common.annotation.Log;
import com.spider.common.core.controller.BaseController;
import com.spider.common.core.domain.AjaxResult;
import com.spider.common.core.page.TableDataInfo;
import com.spider.common.enums.BusinessType;
import com.spider.common.utils.StringUtils;
import com.spider.common.utils.poi.ExcelUtil;
import com.spider.quartz.domain.JapanUnqualifiedGoods;
import com.spider.quartz.service.IJapanUnqualifiedGoodsService;
import com.spider.quartz.task.JapanTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 日本不合格商品展示Controller
 * 
 * @author ruoyi
 * @date 2025-11-26
 */
@RestController
@Slf4j
@RequestMapping("/bus/japan")
public class JapanUnqualifiedGoodsController extends BaseController
{
    @Autowired
    private IJapanUnqualifiedGoodsService japanUnqualifiedGoodsService;
    @Autowired
    private JapanTask japanTask;
    /**
     * 查询日本不合格商品展示列表
     */
    @PreAuthorize("@ss.hasPermi('bus:japan:list')")
    @GetMapping("/list")
    public TableDataInfo list(JapanUnqualifiedGoods japanUnqualifiedGoods)
    {
        startPage();
        List<JapanUnqualifiedGoods> list = japanUnqualifiedGoodsService.selectJapanUnqualifiedGoodsList(japanUnqualifiedGoods);
        return getDataTable(list);
    }

    /**
     * 导出日本不合格商品展示列表
     */
    @PreAuthorize("@ss.hasPermi('bus:japan:export')")
    @Log(title = "日本不合格商品展示", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, JapanUnqualifiedGoods japanUnqualifiedGoods)
    {
        List<JapanUnqualifiedGoods> list = japanUnqualifiedGoodsService.selectJapanUnqualifiedGoodsList(japanUnqualifiedGoods);
        ExcelUtil<JapanUnqualifiedGoods> util = new ExcelUtil<JapanUnqualifiedGoods>(JapanUnqualifiedGoods.class);
        util.exportExcel(response, list, "日本不合格商品展示数据");
    }

    /**
     * 获取日本不合格商品展示详细信息
     */
    @PreAuthorize("@ss.hasPermi('bus:japan:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(japanUnqualifiedGoodsService.selectJapanUnqualifiedGoodsById(id));
    }

    /**
     * 新增日本不合格商品展示
     */
    @PreAuthorize("@ss.hasPermi('bus:japan:add')")
    @Log(title = "日本不合格商品展示", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody JapanUnqualifiedGoods japanUnqualifiedGoods)
    {
        return toAjax(japanUnqualifiedGoodsService.insertJapanUnqualifiedGoods(japanUnqualifiedGoods));
    }

    /**
     * 修改日本不合格商品展示
     */
    @PreAuthorize("@ss.hasPermi('bus:japan:edit')")
    @Log(title = "日本不合格商品展示", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody JapanUnqualifiedGoods japanUnqualifiedGoods)
    {
        return toAjax(japanUnqualifiedGoodsService.updateJapanUnqualifiedGoods(japanUnqualifiedGoods));
    }

    /**
     * 删除日本不合格商品展示
     */
    @PreAuthorize("@ss.hasPermi('bus:japan:remove')")
    @Log(title = "日本不合格商品展示", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(japanUnqualifiedGoodsService.deleteJapanUnqualifiedGoodsByIds(ids));
    }

    @PostMapping("/manual")
    @PreAuthorize("@ss.hasPermi('bus:japan:manual')")
    public String manualCrawl() {
        new Thread(() -> {
            japanTask.startCrawl();
        }).start();
        return "手动爬取任务已启动";
    }

    @PostMapping("/scheduled")
    public String scheduledCrawl() {
        new Thread(() -> {
            japanTask.startCrawl();
        }).start();
        return "定时爬取任务已启动";
    }

    /**
     * 单条数据爬取
     */
    @Log(title = "美国不合格商品展示", businessType = BusinessType.OTHER)
    @PostMapping("/crawlSingle/{id}")
    public AjaxResult crawlSingle(@PathVariable Long id) {
        try {
            JapanUnqualifiedGoods goods = japanUnqualifiedGoodsService.selectJapanUnqualifiedGoodsById(id);
            if (goods == null) {
                return AjaxResult.error("数据不存在");
            }
            if (goods.getStatus() == null || goods.getStatus() != 1) {
                return AjaxResult.error("数据状态异常，无法爬取。只有状态为1的数据可以手动更新");
            }
            if (StringUtils.isEmpty(goods.getDetailsUrl())) {
                return AjaxResult.error("详情页地址为空，无法爬取");
            }

            System.out.println("开始单条数据爬取，ID: " + id + ", URL: " + goods.getDetailsUrl());

            // 调用爬虫任务处理单条数据
            boolean success = japanTask.crawlSingleItem(goods.getDetailsUrl(), id);
            if (success) {
                return AjaxResult.success("数据更新成功");
            } else {
                return AjaxResult.error("数据更新失败");
            }
        } catch (Exception e) {
            log.error("单条数据爬取异常，ID: " + id, e);
            return AjaxResult.error("数据更新异常: " + e.getMessage());
        }
    }
}
