package com.fs.handwrite.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.DateUtils;
import com.fs.fastgptApi.param.ChatImgParam;
import com.fs.fastgptApi.result.ChatDetailTStreamFResult;
import com.fs.fastgptApi.service.ChatService;
import com.fs.handwrite.domain.HandwriteCollection;
import com.fs.handwrite.mapper.HandwriteCollectionMapper;
import com.fs.handwrite.service.IHandwriteCollectionService;
import com.fs.his.domain.FsOrcAiRecord;
import com.fs.his.param.CollectionOrcParam;
import com.fs.his.service.IFsOrcAiRecordService;
import com.fs.his.vo.CollectionOrcVO;
import com.fs.hisStore.domain.FsStoreOrderScrm;
import com.fs.hisStore.mapper.FsStoreOrderItemScrmMapper;
import com.fs.hisStore.mapper.FsStoreOrderScrmMapper;
import com.fs.hisStore.vo.FsStoreOrderItemVO;
import com.fs.qw.vo.FsStoreOrderScrmIdVo;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.core.util.UuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 手写信息采集表Service业务层处理
 * 
 * @author fs
 * @date 2024-01-01
 */
@Slf4j
@Service
public class HandwriteCollectionServiceImpl implements IHandwriteCollectionService
{
    @Autowired
    private HandwriteCollectionMapper handwriteCollectionMapper;

    @Autowired
    private FsStoreOrderScrmMapper storeOrderScrmMapper;

    @Autowired
    private FsStoreOrderItemScrmMapper itemScrmMapper;

    @Autowired
    private ChatService chatService;

    @Autowired
    private IFsOrcAiRecordService orcAiRecordService;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public HandwriteCollection selectHandwriteCollectionById(Integer id)
    {
        return handwriteCollectionMapper.selectHandwriteCollectionById(id);
    }

    @Override
    public List<HandwriteCollection> selectHandwriteCollectionList(HandwriteCollection handwriteCollection) {
        List<HandwriteCollection> handwriteCollections = handwriteCollectionMapper.selectHandwriteCollectionList(handwriteCollection);
        if (CollectionUtils.isEmpty(handwriteCollections)) {
            return Collections.emptyList();
        }

        // 1. 获取所有手写采集ID
        List<Long> handwriteCollectionIds = handwriteCollections.stream()
                .map(HandwriteCollection::getId)
                .collect(Collectors.toList());

        // 2. 查出关联的订单信息
        List<FsStoreOrderScrmIdVo> orderScrmList = storeOrderScrmMapper.selectIdListByHandleCollectionIds(handwriteCollectionIds);
        if (CollectionUtils.isEmpty(orderScrmList)) {
            return handwriteCollections;
        }

        // 3. 构建 Map：Key = handle_collection_id, Value = order_id
        Map<Long, Long> collectionToOrderMap = orderScrmList.stream()
                .filter(o -> o.getHandleCollectionId() != null && o.getId() != null)
                .collect(Collectors.toMap(
                        FsStoreOrderScrmIdVo::getHandleCollectionId,
                        FsStoreOrderScrmIdVo::getId,
                        (v1, v2) -> v1
                ));

        // 4. 获取所有订单ID，并查出订单商品明细
        List<Long> orderScrmIds = new ArrayList<>(collectionToOrderMap.values());
        List<FsStoreOrderItemVO> fsStoreOrderItemVOS = itemScrmMapper.selectByOrderIds(orderScrmIds);

        // 5. 解析 JSON 提取商品名称
        for (FsStoreOrderItemVO item : fsStoreOrderItemVOS) {
            if (StringUtils.isNotBlank(item.getJsonInfo())) {
                try {
                    JsonNode jsonNode = objectMapper.readTree(item.getJsonInfo());
                    String productName = jsonNode.has("productName") ? jsonNode.get("productName").asText() : null;
                    item.setProductName(productName);
                } catch (Exception e) {
                    log.error("解析商品JSON失败, itemId: {}", item.getItemId(), e);
                }
            }
        }

        // 6. 【核心】按订单ID分组，并将商品名称用逗号拼接
        // Key: orderId, Value: "商品A,商品B"
        Map<Long, String> orderProductMap = fsStoreOrderItemVOS.stream()
                .filter(item -> item.getOrderId() != null && StringUtils.isNotBlank(item.getProductName()))
                .collect(Collectors.groupingBy(
                        FsStoreOrderItemVO::getOrderId,
                        Collectors.mapping(FsStoreOrderItemVO::getProductName, Collectors.joining(","))
                ));

        // 7. 将拼接好的商品名称回填到 HandwriteCollection 中
        for (HandwriteCollection collection : handwriteCollections) {
            Long orderId = collectionToOrderMap.get(collection.getId());
            if (orderId != null) {
                String productNames = orderProductMap.get(orderId);
                collection.setProductName(productNames); // 如果没有商品，设为 null
            }
        }

        return handwriteCollections;
    }

    @Override
    public int insertHandwriteCollection(HandwriteCollection handwriteCollection)
    {
        Date currentTime = DateUtils.getNowDate();
        handwriteCollection.setCreateTime(currentTime);
        handwriteCollection.setUpdateTime(currentTime);
        handwriteCollection.setCreateBy(handwriteCollection.getCompanyUserId());
        handwriteCollection.setUpdateBy(handwriteCollection.getCompanyUserId());
        try {
            return handwriteCollectionMapper.insertHandwriteCollection(handwriteCollection);
        } catch (DuplicateKeyException e) {
            throw new CustomException("订单号已存在，请勿重复添加");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addCollectionAndUpdateOrderStatus(HandwriteCollection handwriteCollection)
    {
        if (handwriteCollection.getPatientPhone()!=null&&handwriteCollection.getPatientPhone().contains("*")){
            handwriteCollection.setPatientPhone(null);
        }
        Date currentTime = DateUtils.getNowDate();
        handwriteCollection.setCreateTime(currentTime);
        handwriteCollection.setUpdateTime(currentTime);
        handwriteCollection.setCreateBy(handwriteCollection.getCompanyUserId());
        handwriteCollection.setUpdateBy(handwriteCollection.getCompanyUserId());
        try {
            handwriteCollectionMapper.insertHandwriteCollection(handwriteCollection);
        } catch (DuplicateKeyException e) {
            throw new CustomException("订单号已存在，请勿重复添加");
        }
        // 修改商城订单状态并设置手写信息采集主键id
        FsStoreOrderScrm fsStoreOrder=new FsStoreOrderScrm();
        fsStoreOrder.setOrderCode(handwriteCollection.getOrderCode());
        fsStoreOrder.setHandleCollectionId(handwriteCollection.getId());
        return storeOrderScrmMapper.updateFsStoreOrderByOrderCode(fsStoreOrder);
    }

    @Override
    public int updateHandwriteCollection(HandwriteCollection handwriteCollection)
    {
        handwriteCollection.setUpdateTime(new Date());
        if (handwriteCollection.getPatientPhone()!=null&&handwriteCollection.getPatientPhone().contains("*")){
            handwriteCollection.setPatientPhone(null);
        }
        return handwriteCollectionMapper.updateHandwriteCollection(handwriteCollection);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteHandwriteCollectionByIds(Integer[] ids)
    {
        //删除之前先去查询订单信息，将订单关联的的手写信息采集id设置为空
        List<HandwriteCollection> handwriteCollectionList = handwriteCollectionMapper.selectHandwriteCollectionListByIds(ids);
        if (CollectionUtils.isEmpty(handwriteCollectionList)){
            return 0;
        }
        List<String> orderCodeList = handwriteCollectionList.stream().map(HandwriteCollection::getOrderCode).collect(Collectors.toList());
        int result=storeOrderScrmMapper.updateStoreOrderScrmHandIdIsNullByOrderCodeList(orderCodeList);
        return handwriteCollectionMapper.deleteHandwriteCollectionByIds(ids);
    }

    @Override
    public int deleteHandwriteCollectionById(Integer id)
    {
        Integer[] ids = new Integer[]{id};
        //删除之前先去查询订单信息，将订单关联的的手写信息采集id设置为空
        List<HandwriteCollection> handwriteCollectionList = handwriteCollectionMapper.selectHandwriteCollectionListByIds(ids);
        if (CollectionUtils.isEmpty(handwriteCollectionList)){
            return 0;
        }
        List<String> orderCodeList = handwriteCollectionList.stream().map(HandwriteCollection::getOrderCode).collect(Collectors.toList());
        int result=storeOrderScrmMapper.updateStoreOrderScrmHandIdIsNullByOrderCodeList(orderCodeList);
        return handwriteCollectionMapper.deleteHandwriteCollectionByIds(ids);
    }

    @Override
    public FsStoreOrderScrm getOrderCodeInfo(String orderCode) {
        return storeOrderScrmMapper.selectFsStoreOrderByOrderCode(orderCode);
    }

    @Override
    public AjaxResult checkOrderCode(String orderCode) {
        // 首先查询订单表是否存在该订单号
        FsStoreOrderScrm fsStoreOrderScrm = storeOrderScrmMapper.selectFsStoreOrderByOrderCode(orderCode);
        if (fsStoreOrderScrm == null) {
            log.error("商城订单不存在！orderCode:{}", orderCode);
            return AjaxResult.error("商城订单不存在！");
        }
        // 其次查询手写信息采集表中是否已存在此订单号
        HandwriteCollection queryCondition = new HandwriteCollection();
        queryCondition.setOrderCode(orderCode);
        List<HandwriteCollection> handwriteCollections = handwriteCollectionMapper.selectHandwriteCollectionList(queryCondition);
        if (CollectionUtils.isNotEmpty(handwriteCollections)) {
            log.error("订单号已上传，请勿重复添加！orderCode:{}", orderCode);
            return AjaxResult.error("订单号已上传，请勿重复添加！");
        }
        return AjaxResult.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CollectionOrcVO imageProcess(CollectionOrcParam collectionOrcParam) {
        if (StringUtils.isEmpty(collectionOrcParam.getImgUrl())) {
            log.error("图片地址不能为空！");
            throw new CustomException("图片地址不能为空！");
        }
        ChatImgParam param=new ChatImgParam();
        param.setChatId(UuidUtil.getTimeBasedUuid().toString());
        param.setStream(false);
        param.setDetail(true);
        List<ChatImgParam.Message> messageList=new ArrayList<ChatImgParam.Message>();
        ChatImgParam.Message message = new ChatImgParam.Message();
        message.setRole("user");
        List<ChatImgParam.Message.content> contents = new ArrayList<>();

        ChatImgParam.Message.content content = new ChatImgParam.Message.content();
        content.setType("text");
        content.setText("请根据提示词识别图片内容");
        contents.add(content);

        //设置上传的图片
        ChatImgParam.Message.content contentImg = new ChatImgParam.Message.content();
        contentImg.setType("image_url");
        ChatImgParam.Message.ImageUrl imageUrl = new ChatImgParam.Message.ImageUrl();
        imageUrl.setUrl(collectionOrcParam.getImgUrl());
        contentImg.setImage_url(imageUrl);
        contents.add(contentImg);

        message.setContent(contents);
        messageList.add(message);
        param.setMessages(messageList);

        R r = chatService.initiatingTakeChatNew(param, "http://129.28.170.206:3000/api", "fastgpt-vHaXxiy4g5pfQyFFwUsAAtqDHDpztftrVzXyh5hgMtcUjaE6dFupgKz");
        if(!r.get("code").equals(200)){
            CollectionOrcVO vo = new CollectionOrcVO();
            vo.setIsParse(0);
        }
        ChatDetailTStreamFResult result=(ChatDetailTStreamFResult)r.get("data");

        String contentKh = result.getChoices().get(0).getMessage().getContent();
        System.out.println("模型解析图片结果："+contentKh);
        Gson gson = new Gson();
        CollectionOrcVO fromJson = gson.fromJson(contentKh, CollectionOrcVO.class);

        //解析记录
        FsOrcAiRecord record = new FsOrcAiRecord();
        record.setCompanyUserId(collectionOrcParam.getCompanyUserId());
        record.setImgUrl(collectionOrcParam.getImgUrl());
        record.setCreateTime(new Date());
        record.setUpdateTime(new Date());
        orcAiRecordService.insertFsOrcAiRecord(record);
        return fromJson;
    }
}