package com.jsc.oscm.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jsc.oscm.entity.TargetWebsite;
import com.jsc.oscm.model.ReturnT;
import com.jsc.oscm.service.TargetWebsiteService;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@RestController
public class TargetWebsiteController {

    @Resource
    TargetWebsiteService targetWebsiteService;

    @PostMapping("/open/target/website/queryAllInfo")
    public String queryAllInfo(@RequestBody TargetWebsite targetWebsite) {
        ReturnT<List<TargetWebsite>> returnT;
        try {
            List<TargetWebsite> resultList = targetWebsiteService.queryAllInfo(targetWebsite);
            returnT = new ReturnT<>(200, String.valueOf(resultList.size()), resultList);
        } catch (Exception e) {
            returnT = new ReturnT<>(500, e.getMessage(), null);
        }
        return JSON.toJSONString(returnT, SerializerFeature.DisableCircularReferenceDetect);
    }

    @PostMapping("/open/target/website/queryAll")
    public String queryAll(@RequestBody TargetWebsite targetWebsite) {
        ReturnT<List<Map<String, Object>>> returnT;
        try {
            List<Map<String, Object>> resultList = targetWebsiteService.queryAll(targetWebsite);
            returnT = new ReturnT<>(200, String.valueOf(resultList.size()), resultList);
        } catch (Exception e) {
            returnT = new ReturnT<>(500, e.getMessage(), null);
        }
        return JSON.toJSONString(returnT, SerializerFeature.DisableCircularReferenceDetect);
    }

    @GetMapping("/open/target/website/{id}")
    public String queryOne(@PathVariable("id") Integer id) {
        ReturnT<Map<String, Object>> returnT;
        try {
            returnT = new ReturnT<>(200, "", targetWebsiteService.queryOne(id));
        } catch (Exception e) {
            returnT = new ReturnT<>(500, e.getMessage(), null);
        }
        return JSON.toJSONString(returnT);
    }

    @PostMapping({"/target/website/add", "/target/website/update", "/open/target/website/update"})
    public String save(@RequestBody TargetWebsite targetWebsite) {
        ReturnT<TargetWebsite> returnT;
        try {
            returnT = new ReturnT<>(200, "", targetWebsiteService.save(targetWebsite));
        } catch (Exception e) {
            returnT = new ReturnT<>(500, e.getMessage(), null);
        }
        return JSON.toJSONString(returnT);
    }

    @PostMapping("/target/website/delete")
    public String delete(@RequestBody TargetWebsite targetWebsite) {
        ReturnT<String> returnT;
        try {
            targetWebsiteService.delete(targetWebsite);
            returnT = new ReturnT<>(200, "", null);
        } catch (Exception e) {
            returnT = new ReturnT<>(500, e.getMessage(), null);
        }
        return JSON.toJSONString(returnT);
    }

    @PostMapping("/target/website/deleteAll")
    public String deleteAll(@RequestBody List<TargetWebsite> targetWebsiteList) {
        ReturnT<String> returnT;
        try {
            targetWebsiteService.deleteAll(targetWebsiteList);
            returnT = new ReturnT<>(200, "", null);
        } catch (Exception e) {
            returnT = new ReturnT<>(500, e.getMessage(), null);
        }
        return JSON.toJSONString(returnT);
    }

    @PostMapping("/target/website/queryPageable/{index}/{size}")
    public String query(@PathVariable("index") Integer index,
                        @PathVariable("size") Integer size,
                        @RequestBody TargetWebsite targetWebsite) {
        ReturnT<List<TargetWebsite>> returnT;
        try {
            returnT = new ReturnT<>(200,
                    String.valueOf(targetWebsiteService.queryCount(targetWebsite)),
                    targetWebsiteService.queryPageable(targetWebsite, index, size));
        } catch (Exception e) {
            returnT = new ReturnT<>(500, e.getMessage(), null);
        }
        return JSON.toJSONString(returnT);
    }


    @PostMapping("/target/query/common/{index}/{size}")
    public String queryCommonCrawlRules(@PathVariable(value = "index") Integer index, @PathVariable(value = "size") Integer size, @RequestBody TargetWebsite targetWebsite) {
        ReturnT<JSONArray> returnT;
        try {
            JSONObject res = targetWebsiteService.getCommonCrawlRules(index, size, targetWebsite);
            JSONArray data = ObjectUtils.isEmpty(res) ? new JSONArray() : res.getJSONArray("data");
            returnT = new ReturnT<>(200, res.getOrDefault("total", "0").toString(), data);
        } catch (Exception e) {
            returnT = new ReturnT<>(500, "查询失败", null);
        }
        return JSON.toJSONString(returnT);
    }

    @GetMapping("/target/website/export")
    public ResponseEntity<byte[]> exportWebsites() throws IOException {
        String jsonData = targetWebsiteService.exportAllWebsites();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setContentDispositionFormData("attachment", "target_websites.json");

        return ResponseEntity.ok()
                .headers(headers)
                .body(jsonData.getBytes());
    }

    /**
     * 从JSON文件导入目标网站数据
     *
     * @param file 上传的JSON文件
     * @return 导入结果消息
     */
    @PostMapping("/target/website/import")
    public ResponseEntity<String> importWebsites(@RequestParam("file") MultipartFile file) {
        try {
            int count = targetWebsiteService.importWebsites(file);
            return ResponseEntity.ok("成功导入 " + count + " 条记录");
        } catch (IOException e) {
            return ResponseEntity.badRequest().body("导入失败: " + e.getMessage());
        }
    }


}
