package org.dromara.zhishu.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaIgnore;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pdd.pop.sdk.common.util.JsonUtil;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.web.core.BaseController;
import org.dromara.system.service.ISysConfigService;
import org.dromara.zhishu.domain.Task;
import org.dromara.zhishu.domain.bo.*;
import org.dromara.zhishu.domain.dto.BookBaseInfoDto;
import org.dromara.zhishu.domain.excel.BaseInfoExcel;
import org.dromara.zhishu.domain.vo.BaseInfoPricingVo;
import org.dromara.zhishu.domain.vo.BookBaseInfoVo;
import org.dromara.zhishu.domain.vo.ProductForm;
import org.dromara.zhishu.domain.vo.ShopVo;
import org.dromara.zhishu.mapper.BookBaseInfoMapper;
import org.dromara.zhishu.service.IBookBaseInfoService;
import org.dromara.zhishu.service.IRunningTaskByShopService;
import org.dromara.zhishu.service.IShopService;
import org.dromara.zhishu.util.InterfaceUtils;
import org.dromara.zhishu.util.UrlMultipartFile;
import org.dromara.zhishu.util.WxPayUtil;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static cn.dev33.satoken.SaManager.log;
import static org.dromara.zhishu.util.InterfaceUtils.getInterface;

/**
 * 基础信息
 *
 * @author Lion Li
 * @date 2025-03-08
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/zhishu/baseInfo")
public class BookBaseInfoController extends BaseController {

    private final BookBaseInfoMapper baseMapper;


    private final IBookBaseInfoService bookBaseInfoService;
    private final ISysConfigService configService;
    private final IShopService shopService;
    private final IRunningTaskByShopService runningTaskByShopService;

    private final Set<String> failedIsbns = Collections.synchronizedSet(new HashSet<>());

    /**
     * 查询基础信息列表
     */
    @SaCheckPermission("zhishu:baseInfo:list")
    @GetMapping("/list")
    @SaIgnore
    public TableDataInfo<BookBaseInfoVo> list(BookBaseInfoDto bo, BookNumberRageBo number, PageQuery pageQuery) {
        return bookBaseInfoService.queryPageList(bo, number, pageQuery);
    }

    /**
     * 导出基础信息列表
     */
    @SaCheckPermission("zhishu:baseInfo:export")
    @Log(title = "基础信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(BookBaseInfoBo bo, HttpServletResponse response) {
        List<BookBaseInfoVo> list = bookBaseInfoService.queryList(bo);
        ExcelUtil.exportExcel(list, "基础信息", BookBaseInfoVo.class, response);
    }

    /**
     * 获取基础信息详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("zhishu:baseInfo:query")
    @SaIgnore
    @GetMapping("/{id}")
    public R<BookBaseInfoVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable String id) {
        return R.ok(bookBaseInfoService.queryById(id));
    }


    /**
     * 获取基础信息详细信息
     *
     * @param isbn isbn
     */
    @SaCheckPermission("zhishu:baseInfo:query")
    @GetMapping("/getBookByIsbn/{isbn}")
    @SaIgnore
    public R<BookBaseInfoVo> getIsbnList(@NotNull(message = "主键不能为空")
                                         @PathVariable String isbn) {
        return R.ok(bookBaseInfoService.getBookByIsbn(isbn));
    }

    /**
     * 调取爬虫接口获取书籍数据
     */
    @SaCheckPermission("zhishu:baseInfo:getBookData")
    @PostMapping("/getBookData/{isbn}")
    public R<BookBaseInfoVo> getBookData(@NotNull(message = "主键不能为空")
                                   @PathVariable String isbn) {
        return R.ok(bookBaseInfoService.getBookData(isbn));
    }

    /**
     * 新增基础信息
     */
    @SaCheckPermission("zhishu:baseInfo:add")
    @Log(title = "基础信息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody BookBaseInfoBo bo) {
        return toAjax(bookBaseInfoService.insertByBo(bo));
    }

    /**
     * 修改基础信息
     */
    @SaCheckPermission("zhishu:baseInfo:edit")
    @Log(title = "基础信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody EditBookInfoBo bo) {
        return toAjax(bookBaseInfoService.updateByBo(bo));
    }

    /**
     * 删除基础信息
     *
     * @param ids 主键串
     */
    @SaCheckPermission("zhishu:baseInfo:remove")
    @Log(title = "基础信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable String[] ids) {


        return toAjax(bookBaseInfoService.deleteWithValidByIds(List.of(ids), true));
    }
    /**
     *  根据isbn查询书籍详情数据
     */
    @SaIgnore
    @GetMapping("/getBookDataByIsbn/{isbn}")
    public R<TableDataInfo<BookBaseInfoVo>> getBookDataByIsbn(@PathVariable String isbn){
        return R.ok(bookBaseInfoService.getBookDataByIsbn(isbn));
    }

    /**
     * 更新选品中心单条数据
     */
    @SaIgnore
    @PostMapping("/updateBookData")
    public R<Boolean> updateBookData(@RequestBody BookUpdateInfoBo bo) {
//        System.out.println("更新选品中心单条数据"+bo);
        return R.ok(bookBaseInfoService.updateCentBookByIsbn(bo));
    }

    /**
     * 文件信息
     * 导入 模板（预留字段）
     */
//    @Log(title = "商品信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PostMapping("/importExcel")
    public R<Void> importExcel(@RequestParam("file") MultipartFile file, @RequestParam("type") Integer type) {

        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {


        }
//         throw new RuntimeException("系统错误");

        List<BaseInfoExcel> list = ExcelUtil.importExcel(inputStream, BaseInfoExcel.class);
        bookBaseInfoService.importExcel(list);
        return R.ok();
    }


    /**
     * 获取图书列表
     */
//    @Log(title = "商品信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PostMapping("/getList")
    public R getList() {
        return R.ok(bookBaseInfoService.getList());
    }



    /**
     * 书名获取列表
     */
    @RepeatSubmit
    @PostMapping("/getBookByName")
    @SaIgnore
    public R<List<BookBaseInfoVo>> getBookName(@RequestBody Map<String, String> request) {
        String bookName = request.get("bookName");
        List<BookBaseInfoVo> list = bookBaseInfoService.getBookListByBookName(bookName);
        return R.ok(list);
    }

    @SaIgnore
    @PostMapping("/addBookCatId")
    public void addBookCatId(@RequestBody Map<String, String> request) {
        BookBaseInfoBo bo = new BookBaseInfoBo();
        bo.setIsbn(request.get("isbn"));
        bo.setCatId(Long.parseLong(request.get("catId")));
        bookBaseInfoService.updateByIsbn(bo);
    }

    /**
     * 重新生成图书数据
     */
    @SaIgnore
    @PostMapping("/regenerateBookData")
    public R<String> regenerateBookData() {
        try {
            System.out.println("=== 开始重新生成图书数据 ===");
            log.info("=== 开始重新生成图书数据 ===");
            long startTime = System.currentTimeMillis();

            // 读取txt文件
            String fileName = "112233.txt";
            // 创建失败记录文件
            String failFileName = "failed_isbn_" + System.currentTimeMillis() + ".txt";

            int totalProcessed = 0;
            int totalSuccess = 0;
            int totalFail = 0;
            Set<String> failedIsbns = new HashSet<>();

            // 读取文件内容
            try (BufferedReader reader = Files.newBufferedReader(Paths.get(fileName))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    String isbn = extractIsbn(line);
                    if (isbn != null) {
                        totalProcessed++;
                        try {
                            // 调用PHP爬虫接口
                            String kongfzIp = configService.selectConfigByKey("kongfz.ip");
                            String bookinfoStr = getInterface(kongfzIp, "/api/kfz/getBookInfoF/" + isbn);

                            if (bookinfoStr != null && !bookinfoStr.isEmpty()) {
                                Map bookinfoMap = JsonUtil.transferToObj(bookinfoStr, Map.class);
                                if (bookinfoMap.get("code").toString().equals("200")) {
                                    Map data = (Map) bookinfoMap.get("data");
                                    String bookInfoListStr = JsonUtil.transferToJson(data.get("product"));
                                    List bookInfoList = JsonUtil.transferToObj(bookInfoListStr, List.class);

                                    if (!bookInfoList.isEmpty()) {
                                        String bookInfo = JsonUtil.transferToJson(bookInfoList.get(0));
                                        BookBaseInfoVo newData = JsonUtil.transferToObj(bookInfo, BookBaseInfoVo.class);
                                        if (newData != null) {
                                            totalSuccess++;
                                            System.out.println("成功处理ISBN: " + isbn);
                                            log.info("成功处理ISBN: {}", isbn);
                                        } else {
                                            throw new Exception("数据转换失败");
                                        }
                                    } else {
                                        throw new Exception("商品列表为空");
                                    }
                                } else {
                                    throw new Exception("接口返回错误码: " + bookinfoMap.get("code"));
                                }
                            } else {
                                throw new Exception("接口返回数据为空");
                            }
                        } catch (Exception e) {
                            totalFail++;
                            failedIsbns.add(isbn);
                            System.out.println("处理失败ISBN: " + isbn + ", 错误: " + e.getMessage());
                            log.error("处理失败ISBN: {}, 错误: {}", isbn, e.getMessage());
                        }

                        // 每处理一个ISBN后等待5秒
//                        Thread.sleep(5000);
                    }
                }
            }

            // 将失败的ISBN写入文件
            if (!failedIsbns.isEmpty()) {
                try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(failFileName),
                        StandardCharsets.UTF_8, StandardOpenOption.CREATE)) {
                    for (String isbn : failedIsbns) {
                        writer.write("isbn:" + isbn);
                        writer.newLine();
                    }
                }
            }

            long endTime = System.currentTimeMillis();
            double duration = (endTime - startTime) / 1000.0;

            String message = String.format("处理完成 - 总数: %d, 成功: %d, 失败: %d, 耗时: %.2f秒, 失败记录已保存到: %s",
                    totalProcessed, totalSuccess, totalFail, duration, failFileName);

            System.out.println("=== 重新生成图书数据完成 ===");
            System.out.println(message);
            log.info("=== 重新生成图书数据完成 ===");
            log.info(message);

            return R.ok(message);

        } catch (Exception e) {
            String errorMsg = "重新生成图书数据时发生错误: " + e.getMessage();
            System.out.println(errorMsg);
            log.error(errorMsg, e);
            return R.fail(errorMsg);
        }
    }

    /**
     * 从文本行中提取ISBN的辅助方法
     */
    private String extractIsbn(String line) {
        try {
            java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("ISBN: (\\d+)");
            java.util.regex.Matcher matcher = pattern.matcher(line);
            if (matcher.find()) {
                return matcher.group(1);
            }
        } catch (Exception e) {
            log.error("提取ISBN时发生错误: {}", e.getMessage());
        }
        return null;
    }

    /**
     * 批量设置违规信息
     *
     * @param bo
     * @return
     */
    @Log(title = "基础信息", businessType = BusinessType.DELETE)
    @PutMapping("batchUpdateIll")
    public R<Void> batchUpdateIll(@RequestBody IllBaseInfoBo bo) {
        System.out.println(bo);
        return toAjax(bookBaseInfoService.updateByIllge(bo));
//        return toAjax(bookBaseInfoService.deleteWithValidByIds(List.of(ids), true));
//        return null;
    }


    /**
     * 查询基础信息列表
     */
    @GetMapping("/pricing/list")
    @SaIgnore
    public TableDataInfo<BaseInfoPricingVo> listPricing(BookBaseInfoDto bo, BookNumberRageBo number, PageQuery pageQuery) {
        return bookBaseInfoService.queryPagePricingList(bo, number, pageQuery);
    }


    /**
     * 核价链接加密
     */
    @GetMapping("/pricingLink")
    @SaIgnore
    public String pricingLink(BookBaseInfoBo bo, BookNumberRageBo number, PageQuery pageQuery) {
        String link = bookBaseInfoService.pricingLink(bo, pageQuery);
        return link;
    }


    /**
     * 核价链接解密
     */
    @GetMapping("/pricingLinkDec")
    @SaIgnore
    public Map pricingLinkDecrypt(String link) {
        Map pricingLink = bookBaseInfoService.pricingLinkDec(link);
        return pricingLink;
    }

    /**
     * 获取用户是否是会员
     *
     * @return
     */
    @GetMapping("/user/vipInfo/{type}")
    @SaIgnore
    public Boolean getUserIsVip(@PathVariable Integer type) {
        Boolean isVip = bookBaseInfoService.getUserVip(type);
        return isVip;
    }

    /**
     * 根据ISBN获取官图
     * @param isbn ISBN号
     * @return 官图信息
     */
    @GetMapping("/getBookPicByISBN")
    @SaIgnore
    public R<Map<String, String>> getBookPicByISBN(@RequestParam String isbn) {
        try {
            if (StringUtils.isEmpty(isbn)) {
                return R.fail("ISBN不能为空");
            }
            Map<String, String> result = new HashMap<>();
            result.put("isbn", isbn);
            log.info("开始获取官图，ISBN: {}", isbn);
            String goUrl = configService.selectConfigByKey("centerBook.url");
//            String goUrl = "http://localhost:9009/api";

            String apiUrl = "/es/searchByISBN?isbn=" + isbn;
            String responseStr = getInterface(goUrl, apiUrl);

            JSONObject responseJson = JSONObject.parseObject(responseStr);

            if (StringUtils.isNotEmpty(responseJson.getString("data"))  ){
                JSONObject dataJson = responseJson.getJSONObject("data");
                System.out.println(dataJson.getJSONObject("book_pic_s"));
                ObjectMapper objectMapper = new ObjectMapper();
                Map<String, String> picData = objectMapper.readValue(dataJson.getString("book_pic_s"), Map.class);
                String localPathpdd = picData.get("localPath");
                String pddResponse = picData.get("pddResponse");
                System.out.println("localPath: " + localPathpdd);
                System.out.println("pddResponse: " + pddResponse);

                if (pddResponse != null){
                    result.put("localPath", pddResponse);
                }else if(localPathpdd != null) {
                    result.put("localPath", localPathpdd);
                }else {
                    result.put("localPath", "");
                    log.warn("接口返回数据格式异常，ISBN: {}", isbn);
                }


            }else {
                result.put("localPath", "");
                log.warn("接口返回数据为空，ISBN: {}", isbn);
            }

            return R.ok(result);

        } catch (Exception e) {
            log.error("获取官图失败，ISBN: {}, 错误: {}", isbn, e.getMessage(), e);
            Map<String, String> result = new HashMap<>();
            result.put("localPath", "");
            result.put("isbn", isbn);
            return R.ok(result);
        }
    }



    /**
     * 创建任务
     *
     * @param bo
     * @return
     */
    @PostMapping("/task")
    @SaIgnore
    public Map getTask(@RequestBody TaskBo bo) {
        return bookBaseInfoService.insertTask(bo);
    }


    @PostMapping("/addNewTask")
    @SaIgnore
    public Map addNewTask(String taskType,String shopId,String fileName){
        Map result = new HashMap();
        ShopVo shopVo = shopService.queryById(Long.parseLong(shopId));
        if (shopVo == null){
            result.put("code",500);
            result.put("msg","店铺不存在");
            return result;
        }
        // 根据shopId查询数据表是否存在
        int checkMark = runningTaskByShopService.checkTableExists("t_running_task_" + shopId);
        if (checkMark == 0) {
            // 不存在则创建表
            runningTaskByShopService.createTable("t_running_task_" + shopId);
        }
        Task task = new Task();
        task.setTaskType(taskType);
        task.setShopIds(shopId);
        task.setShopNames(shopVo.getShopName());
        task.setFileName(fileName);
        task.setDataNum(0L);
        task.setTaskStatus("0");
        task.setStatus("0");
        task.setCreateBy(shopVo.getCreateBy());
        int mark = bookBaseInfoService.addNewTask(task);
        if (mark > 0){
            result.put("code",200);
            result.put("msg","任务创建成功");
            result.put("taskId",task.getId());
        }else{
            result.put("code",500);
            result.put("msg","任务创建失败");
        }
        return result;
    }

    //扣除余额
    @GetMapping("/setBalance")
    @SaIgnore
    public Map setBalance(){
     return  bookBaseInfoService.setBalance();
    }

    //页面支付
    @PostMapping("/userRecharge")
    @SaIgnore
    public R<Map> userRecharge(@RequestBody UserRechargeBo bo){
        //支付方式 1 微信
        String type = bo.getRechargType();
        //获取登录用户id
        String userId = LoginHelper.getUserId().toString();
        if (userId.equals("1")){
            bo.setRechargPrice(BigDecimal.valueOf(1));
        }
        if(type.equals("1")){
            //换算手续费为 分
            bo.setUserId(Long.parseLong(userId));
            bo.setStatus("0");
            // 插入erp订单
//            userRechargeService.insertByBo(bo);
            String title = "页面展示会员";
            Integer payType=1;
            // 插入新后台会员记录
//            bookBaseInfoService.insertUserInfo(bo,title,payType,198000);
            // 新增新后台服务表插入
            Map<String, String> params = new HashMap<>();
            params.put("service_name", title);
            params.put("price", String.valueOf(bo.getRechargPrice()));
            params.put("unit", "年");
            params.put("length", String.valueOf(1));
            params.put("type", "centerBookPage");
            params.put("sort", "1");
            String service = InterfaceUtils.postForm("https://go.order.service.buzhiyushu.cn/", "/api/createService", params);
            System.out.println("service:"+service);
            if (service != null) {
                JSONObject jsonObject = JSONObject.parseObject(service);
                if (jsonObject != null && jsonObject.containsKey("data")) {
                    String serviceId = jsonObject.getString("data");
                    params.put("serviceId", serviceId);
                }
            }
            // 新增新后台订单表插入
            Map<String, String> params1 = new HashMap<>();
            params1.put("orderType", "centerBookPage");
            params1.put("userId", userId);
            params1.put("goodsId", params.get("serviceId"));
            params1.put("count", "1");
            String orderId = null;
            String order = InterfaceUtils.postForm("https://go.order.service.buzhiyushu.cn/", "/api/orders/createOrder", params1);
            System.out.println("order:"+order);
            if (order != null) {
                JSONObject jsonObject = JSONObject.parseObject(order);
                if (jsonObject != null && jsonObject.containsKey("data")) {
                    JSONObject dataObject = jsonObject.getJSONObject("data");
                    // 再从data对象中获取orderId
                    orderId = dataObject.getString("orderId");
                    System.out.println("orderId:"+orderId);
                    params1.put("orderId", orderId);
                }
            }
            String data = WxPayUtil.wxPay(bo.getId(), bo.getRechargPrice().setScale(0, RoundingMode.HALF_UP).intValue(), bo.getRechargPrice().toString(),orderId,userId);
            String base64Str = WxPayUtil.generateQRCode(data);
            Map map = new HashMap();
            map.put("img",base64Str);
            map.put("id", bo.getId());
            return R.ok(map);
        }
        return R.fail("充值订单生成失败，请联系管理员");
    }


    //高级按钮支付
    @PostMapping("/buttonUserRecharge")
    @SaIgnore
    public R<Map> buttonUserRecharge(@RequestBody UserRechargeBo bo){
        //支付方式 1 微信
        String type = bo.getRechargType();
        String userId = LoginHelper.getUserId().toString();
        if (userId.equals("1")){
            bo.setRechargPrice(BigDecimal.valueOf(1));
        }
        //获取登录用户id
        Integer intValue = bo.getRechargPrice().setScale(0, RoundingMode.HALF_UP).intValue(); // 124
        if(type.equals("1")){
            //换算手续费为 分
            bo.setUserId(Long.parseLong(userId));
            bo.setStatus("0");
            // 插入 erp 订单表
//            userRechargeService.insertByBo(bo);
            String title = "高级搜索会员";
            Integer payType=0;
            // 插入 newAErp 订单表
//            bookBaseInfoService.insertUserInfo(bo,title,payType,9800);
            // 新增新后台服务表插入
            Map<String, String> params = new HashMap<>();
            params.put("service_name", title);
            params.put("price", String.valueOf(bo.getRechargPrice()));
            params.put("unit", "月");
            params.put("length", String.valueOf(1));
            params.put("type", "centerBookSearch");
            params.put("sort", "1");
            String orderUrl = configService.selectConfigByKey("order.url");
            String service = InterfaceUtils.postForm(orderUrl, "/api/createService", params);
//            String service = InterfaceUtils.postForm("https://go.order.service.buzhiyushu.cn/", "/api/createService", params);
            if (service != null) {
                JSONObject jsonObject = JSONObject.parseObject(service);
                if (jsonObject != null && jsonObject.containsKey("data")) {
                    String serviceId = jsonObject.getString("data");
                    params.put("serviceId", serviceId);
                }
            }
            // 新增新后台订单表插入
            Map<String, String> params1 = new HashMap<>();
            params1.put("orderType", "centerBookSearch");
            params1.put("userId", userId);
            params1.put("goodsId", params.get("serviceId"));
            params1.put("count", "1");
            String orderId = null;
            String order = InterfaceUtils.postForm(orderUrl, "/api/orders/createOrder", params1);
//            String order = InterfaceUtils.postForm("https://go.order.service.buzhiyushu.cn/", "/api/orders/createOrder", params1);
            if (order != null) {
                JSONObject jsonObject = JSONObject.parseObject(order);
                if (jsonObject != null && jsonObject.containsKey("data")) {
                    JSONObject dataObject = jsonObject.getJSONObject("data");
                    // 再从data对象中获取orderId
                    orderId = dataObject.getString("orderId");
                    params1.put("orderId", orderId);
                }
            }
            String data = WxPayUtil.wxPay(bo.getId(),intValue,bo.getRechargPrice().toString(),orderId,userId);
            String base64Str = WxPayUtil.generateQRCode(data);
            Map map = new HashMap();
            map.put("img",base64Str);
            map.put("id", bo.getId());
            return R.ok(map);
        }
        return R.fail("充值订单生成失败，请联系管理员");
    }


    /**
     * 获取图片详情  从选品中心获取图片
     * @param isbn
     * @return
     */
    @GetMapping("/getImageDeit/{isbn}")
    @SaIgnore
    public  R<Map<String, String>>  getImageDeit(@PathVariable String isbn){
        try {
            if (StringUtils.isEmpty(isbn)) {
                return R.fail("ISBN不能为空");
            }
            log.info("开始获取官图，ISBN: {}", isbn);
            String goUrl = configService.selectConfigByKey("centerBook.url");
//            String goUrl = "http://localhost:9009";
            String apiUrl = "/es/searchByISBN?isbn=" + isbn;
            String responseStr = getInterface(goUrl, apiUrl);

            Map<String, String> result = new HashMap<>();
            result.put("isbn", isbn);

            if (StringUtils.isNotEmpty(responseStr)) {
                try {
                    // 解析返回的JSON数据
                    Map responseMap = JsonUtil.transferToObj(responseStr, Map.class);
                    if (responseMap != null && responseMap.containsKey("data")) {
                        String localPath=null ;
                        Object dataObj = responseMap.get("data");
                        if (dataObj instanceof Map) {
                            Map dataMap = (Map) dataObj;
                            Object bookPicObj = dataMap.get("book_pic");
                            if (bookPicObj instanceof String) {
                                localPath = (String) bookPicObj;
                            } else if (bookPicObj instanceof Map) {

                                Map bookPicMap = (Map) bookPicObj;
                                localPath = (String) bookPicMap.get("pddPath");
                            } else {
                                // 其他情况，比如为null或者不是我们预期的类型，可以设置一个默认值或者抛出异常
                                localPath = null; // 或者默认值
                            }
                        }

                        result.put("localPath", localPath != null ? localPath : "");
                        log.info("成功获取官图，ISBN: {}, book_pic_new: {}", isbn, localPath);
                    } else {
                        result.put("localPath", "");
                        log.warn("接口返回数据格式异常，ISBN: {}", isbn);
                    }
                } catch (Exception parseException) {
                    result.put("localPath", "");
                    log.error("解析接口返回数据失败，ISBN: {}, 错误: {}", isbn, parseException.getMessage());
                }
            } else {
                result.put("localPath", "");
                log.warn("接口返回数据为空，ISBN: {}", isbn);
            }

            return R.ok(result);

        } catch (Exception e) {
            log.error("获取官图失败，ISBN: {}, 错误: {}", isbn, e.getMessage(), e);
            Map<String, String> result = new HashMap<>();
            result.put("localPath", "");
            result.put("isbn", isbn);
            return R.ok(result);
        }



     // Map map =   bookBaseInfoService.getImageDite(isbn);
     // return map;
    }

    /**
     * 检查订单状态
     * @return
     */
    @GetMapping("/checkStatus")
    @SaIgnore
    public R<Map> checkStatus(String type) throws JsonProcessingException {
        String userId = String.valueOf(LoginHelper.getUserId());
        Map map = new HashMap();
        map.put("type",type);
        map.put("userId",userId);
        String orderUrl = configService.selectConfigByKey("order.url");
        String status = InterfaceUtils.postForm(orderUrl, "/api/orders/checkStatus", map);
//        String status = InterfaceUtils.postForm("https://go.order.service.buzhiyushu.cn/", "/api/orders/checkStatus", map);
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(status);

        // 构建返回结果
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", rootNode.get("code"));
        resultMap.put("isVip", rootNode.get("data").get("isVip"));
        resultMap.put("expirationDate", rootNode.get("data").get("expirationDate"));
        resultMap.put("msg", rootNode.get("message"));

        // 返回成功响应
        return R.ok(resultMap);
    }

    /**
     *  xcx查询选品中心数据并同步
     */
    @PostMapping("/getXcxData")
    @SaIgnore
    public R<String> getXcxData(@RequestBody ProductForm form) {
        /**
         * 添加选品中心查询
         */
        String centerBookUrl = configService.selectConfigByKey("centerBook.url");
//        String centerBookUrl = "http://192.168.101.213:9009/api";
        String path = "/es/addBookToES";
        Map<String, Object> params = new HashMap<>();
        params.put("isbn", form.getBarcode());

        params.put("book_name",form.getName());
//        params.put("fix_price", form.getPrice());
        params.put("author", form.getAuthor());
        params.put("publication_time", form.getPublishTime());
        params.put("publisher", form.getPublisher());
        params.put("sell_counts", form.getSellCount());
        params.put("buy_counts", form.getBuyCount());

        Map<String, String> book_pic = new HashMap<>();
        Map<String, String> book_pic_s = new HashMap<>();

        String pddResponse = "";
        if (form.getFiles() != null && !form.getFiles().isEmpty() && form.getFiles().get(0).getUrl() != null && form.getFiles().get(0).getUrl().startsWith("http")) {
            pddResponse = form.getFiles().get(0).getUrl();
        }
        book_pic_s.put("localPath", "");
        book_pic_s.put("pddResponse", pddResponse);

        // 处理 kfzBookPic 图片上传获取 pddUrl
        String pddUrl = "";
        if (form.getKfzBookPic() != null && !form.getKfzBookPic().isEmpty()) {
            // 调用 processImage 处理图片URL
            try {
                log.info("开始处理图片URL: {}", form.getKfzBookPic());

                // 从URL下载图片并转换为MultipartFile
                String fileName = form.getBarcode() != null ? form.getBarcode() + ".jpg" : "image.jpg";
                UrlMultipartFile urlFile = new UrlMultipartFile(form.getKfzBookPic(), fileName);

                // 构建请求参数 - 使用文件而不是URL
                Map<String, Object> imageRequest = new HashMap<>();
                imageRequest.put("goodsName", form.getName());
                imageRequest.put("isbn", form.getBarcode());
                imageRequest.put("isKW", "true"); // 标记为孔网图片
                imageRequest.put("autoUpload", "true"); // 自动上传到PDD

                // 将文件转换为base64
                byte[] bytes = urlFile.getBytes();
                String base64File = java.util.Base64.getEncoder().encodeToString(bytes);
                imageRequest.put("imageData", base64File);
                imageRequest.put("fileName", fileName);

                // 调用 processImageAndExtractPddUrl 方法获取 pddUrl
                pddUrl = InterfaceUtils.processImageAndExtractPddUrl(imageRequest);

                log.info("图片处理成功,获取到 pddUrl: {}", pddUrl);

            } catch (Exception e) {
                log.error("图片处理失败: {}, 错误: {}", form.getKfzBookPic(), e.getMessage(), e);
                // 处理失败时 pddUrl 为空
                pddUrl = "";
            }
        }

        // 将获取到的 pddUrl 放入 bookPic.pddPath
        book_pic.put("pddPath", pddUrl);

        params.put("book_pic", book_pic);
        params.put("book_pic_s", book_pic_s);
        System.out.println("传递的参数"+params);
        String interfacePost = InterfaceUtils.getInterfacePost(centerBookUrl, path, params);
        return R.ok(interfacePost);
    }

    @PostMapping("/processImage")
    @SaIgnore
    @RepeatSubmit(interval = 2, timeUnit = TimeUnit.SECONDS, message = "图片处理中，请稍后再试")
    public R<String> processImage(@RequestParam(value = "filepath", required = false) MultipartFile file,
                                  @RequestParam(value = "goodsName", required = false) String goodsName,
                                  @RequestParam(value = "isbn", required = false) String isbn,
                                  @RequestParam(value = "isKW", required = false, defaultValue = "false") String isKW,
                                  @RequestParam(value = "autoUpload", required = false, defaultValue = "false") String autoUpload) {
        try {
            // 构建请求数据
            Map<String, Object> requestData = new HashMap<>();
            requestData.put("goodsName", goodsName);
            requestData.put("isbn", isbn);
            requestData.put("isKW", isKW);
            requestData.put("autoUpload", autoUpload);

            // 如果有文件，优先使用文件
            if (file != null && !file.isEmpty()) {
                // 将文件转换为base64用于传递给工具类
                byte[] bytes = file.getBytes();
                String base64File = java.util.Base64.getEncoder().encodeToString(bytes);
                requestData.put("imageData", base64File);
                requestData.put("fileName", file.getOriginalFilename());
            } else {
                return R.fail("请提供图片文件或图片URL");
            }

            // 调用InterfaceUtils中的processImageAndExtractPddUrl方法获取PDD URL
            // 现在直接传递Map对象，而不是JSON字符串
            String pddUrl = InterfaceUtils.processImageAndExtractPddUrl(requestData);

            // 返回提取的URL
            return R.ok(pddUrl);

        } catch (Exception e) {
            return R.fail("图片处理失败: " + e.getMessage());
        }
    }

    @PostMapping("/detectById/{id}")
    @SaIgnore
    public R<String> detectById(@PathVariable("id") Integer id) {
        String centerBookUrl = configService.selectConfigByKey("centerBook.url");
//        String centerBookUrl = "http://localhost:9009/api";
        String path = "/es/DeleteBookByID?id=" + id;
        String result = InterfaceUtils.getInterface(centerBookUrl, path);
        System.out.println("删除结果：" + result);
        return R.ok(result);
    }


}
