package shop.alien.second.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import shop.alien.entity.second.SecondGoodsRecord;
import shop.alien.entity.second.vo.SecondReportingVo;
import shop.alien.entity.second.vo.SecondUserViolationVo;
import shop.alien.entity.store.*;
import shop.alien.entity.store.vo.WebSocketVo;
import shop.alien.mapper.*;
import shop.alien.mapper.second.SecondGoodsRecordMapper;
import shop.alien.second.feign.AlienStoreFeign;
import shop.alien.second.service.SecondGoodsReportingService;
import shop.alien.second.util.AiUserViolationUtils;
import shop.alien.second.util.JsonUtils;
import shop.alien.util.common.Constants;
import shop.alien.util.common.JwtUtil;
import shop.alien.util.type.LifeNoticeUtil;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 二手商品服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SecondGoodsReportingServiceImpl implements SecondGoodsReportingService {

    List<String> videoFileType = Arrays.asList("mp4", "avi", "flv", "mkv", "rmvb", "wmv", "3gp", "mov");

    @Autowired
    private final LifeNoticeMapper lifeNoticeMapper;

    private final LifeNoticeUtil lifeNoticeUtil;

    @Autowired
    private final LifeUserViolationMapper lifeUserViolationMapper;

    @Autowired
    private final StoreDictionaryMapper StoreDictionaryMapper;

    @Autowired
    private final LifeUserMapper lifeUserMapper;

    @Autowired
    private final SecondGoodsRecordMapper secondGoodsRecordMapper;

    private final AlienStoreFeign alienStoreFeign;

    @Autowired
    private final StoreImgMapper storeImgMapper;

    private final AiUserViolationUtils aiUserViolationUtils;

    @Override
    public SecondReportingVo queryReportingDetail (Integer id) {
        SecondReportingVo secondReportingVo = new SecondReportingVo();

        // 获取举报信息
        LifeNotice lifeNotice = lifeNoticeMapper.selectById(id);

        // 获取举报内容
        LifeUserViolation lifeUserViolation = lifeUserViolationMapper.selectById(lifeNotice.getBusinessId());

        // 获取举报类型
        QueryWrapper<StoreDictionary> query = new QueryWrapper<>();
        query.lambda()
                .eq(StoreDictionary::getTypeName, lifeUserViolation.getDictType())
                .eq(StoreDictionary::getDictId, lifeUserViolation.getDictId());
        // 获取枚举
        StoreDictionary storeDictionary =StoreDictionaryMapper.selectOne(query);

        // 定义原始格式
        DateTimeFormatter originalFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 定义目标格式
        DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        // 创建格式化器
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 执行格式化
        String formattedDate = formatter.format(lifeNotice.getCreatedTime());
        // 解析为 LocalDateTime 对象
        LocalDateTime dateTime = LocalDateTime.parse(formattedDate, originalFormatter);

        if (lifeUserViolation.getReportContextType().equals("4")) {
            // 获取商品信息
            SecondGoodsRecord secondGoods = secondGoodsRecordMapper.selectById(lifeUserViolation.getBusinessId());
            secondReportingVo.setPrice(secondGoods.getPrice() != null ? secondGoods.getAmount().setScale(2, BigDecimal.ROUND_HALF_UP).toString() : null);
            secondReportingVo.setHomeImage(secondGoods.getHomeImage());
            secondReportingVo.setTitle(secondGoods.getTitle());
            secondReportingVo.setDescription(secondGoods.getDescription());
            String context = "您于" + dateTime.format(targetFormatter) + "举报“" + secondGoods.getTitle() + "”“" + storeDictionary.getDictDetail() + "”举报内容为“"
                    + lifeUserViolation.getOtherReasonContent()  + "”";
            secondReportingVo.setReportingContext(context);
        } else if (lifeUserViolation.getReportContextType().equals("5")) {
            // 获取用户信息
            LifeUser lifeUser = lifeUserMapper.selectById(lifeUserViolation.getReportedUserId());
            String context = "您于" + dateTime.format(targetFormatter) + "举报“" + lifeUser.getUserName() + "”“" + storeDictionary.getDictDetail() + "”举报内容为“"
                    + lifeUserViolation.getOtherReasonContent()  + "”";
            secondReportingVo.setReportingContext(context);
        } else if (lifeUserViolation.getReportContextType().equals("1") || lifeUserViolation.getReportContextType().equals("2") || lifeUserViolation.getReportContextType().equals("3")) {
            // 用户信息
            if (StringUtils.isNotBlank(lifeNotice.getContext())) {
                String context = JsonUtils.getJsonValue(lifeNotice.getContext(), "message");
                secondReportingVo.setReportingContext(context);
            }
        }
        secondReportingVo.setFeedbackContext("平台已受理，感谢您的反馈！");
        secondReportingVo.setReportingTime(lifeNotice.getCreatedTime());
        secondReportingVo.setFeedbackTime(lifeNotice.getCreatedTime());
        List<Map<String, Object>> list = new ArrayList<>();

        // 存放已存在文件list
        List<String> videoList = new ArrayList<>();

        if (lifeUserViolation.getReportContextType().equals("1") || lifeUserViolation.getReportContextType().equals("2") || lifeUserViolation.getReportContextType().equals("3")) {
            if (StringUtils.isNotBlank(lifeUserViolation.getReportEvidenceImg())) {
                List<String> urlList = Arrays.asList(lifeUserViolation.getReportEvidenceImg().split(","));
                for (int i = 0; i < urlList.size(); i++) {
                    String url = urlList.get(i);
                    // 过滤掉空的URL
                    if (StringUtils.isBlank(url)) {
                        continue;
                    }

                    Map<String, Object> map = new HashMap<>();

                    // 查找最后一个点的位置
                    int lastDotIndex = url.lastIndexOf('.');

                    String fileType = url.substring(url.lastIndexOf(".") + 1);
                    String contains = null;
                    if (lastDotIndex != -1) { // 确保存在
                        contains = url.substring(0, lastDotIndex);
                    }

                    if (!videoList.contains(contains)) {
                        videoList.add(contains);
                        if (videoFileType.contains(fileType.toLowerCase())) {
                            map.put("type", "video");
                            if (i + 1 < urlList.size() && StringUtils.isNotBlank(urlList.get(i + 1))) {
                                map.put("imgUrl", urlList.get(i + 1));
                                map.put("videoUrl", url);
                                list.add(map);
                            }
                        } else {
                            map.put("type", "image");
                            map.put("imgUrl", url);
                            list.add(map);
                        }
                    }

                }
            }
        } else {
            LambdaQueryWrapper<StoreImg> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(StoreImg::getStoreId, lifeUserViolation.getId());
            wrapper.eq(StoreImg::getImgType, Constants.ImageType.SECOND_HAND_REPORT);
            List<StoreImg> imgList = storeImgMapper.selectList(wrapper);
            for (int i = 0; i < imgList.size(); i++) {
                StoreImg storeImg = imgList.get(i);
                // 过滤掉imgUrl为空或null的记录
                if (storeImg == null || StringUtils.isBlank(storeImg.getImgUrl())) {
                    continue;
                }

                Map<String, Object> map = new HashMap<>();

                String fileType = storeImg.getImgUrl().substring(storeImg.getImgUrl().lastIndexOf(".") + 1);

                if (videoFileType.contains(fileType.toLowerCase())) {
                    map.put("type", "video");
                } else {
                    map.put("type", "image");
                }
                map.put("imgUrl", storeImg.getImgUrl());
                list.add(map);
            }
            secondReportingVo.setVideoFirstFrame(lifeUserViolation.getVideoFirstFrame());
        }

        secondReportingVo.setImgList(list);
        secondReportingVo.setReportContextType(lifeUserViolation.getReportContextType());
        secondReportingVo.setId(id);
        return secondReportingVo;

    }

    @Override
    public int reporting(SecondUserViolationVo lifeuserViolation) throws Exception  {
        try {
//            if ("4".equals(lifeuserViolation.getReportContextType())) {
//                lifeuserViolation.setGoodsId(lifeuserViolation.getBusinessId());
//                LambdaQueryWrapper<SecondGoodsRecord> goodsWrapper = new LambdaQueryWrapper<>();
//                goodsWrapper.eq(SecondGoodsRecord::getGoodsId, lifeuserViolation.getBusinessId());
//                goodsWrapper.eq(SecondGoodsRecord::getGoodsStatus, "3");
//                goodsWrapper.orderByDesc(SecondGoodsRecord::getCreatedTime);
//                goodsWrapper.last(" limit 1 ");
//                SecondGoodsRecord goodsRecord = secondGoodsRecordMapper.selectOne(goodsWrapper);
//                if (null != goodsRecord) lifeuserViolation.setBusinessId(goodsRecord.getId());
//            }
            List<String> imgList = lifeuserViolation.getImgUrl();
            String imgStr = "";
            if (imgList != null && !imgList.isEmpty()) {
                imgStr = StringUtils.join(imgList, ",");
            }
            lifeuserViolation.setReportEvidenceImg(imgStr);
            int result = lifeUserViolationMapper.insert(lifeuserViolation);
            if (result > 0) {

                if ("5".equals(lifeuserViolation.getReportContextType())) {
                    // AI审核
                    //登录获取token
                    String token = aiUserViolationUtils.getAccessToken();
                    //调用AI接口
                    String taskId = aiUserViolationUtils.createTask(token, lifeuserViolation);
                    if (org.springframework.util.StringUtils.isEmpty(taskId)) {
                        log.warn("Failed to create AI task for second round review, lifeuserViolation id={}", lifeuserViolation.getId());
                        return 0;
                    }
                    lifeuserViolation.setAiTaskId(taskId);
                    lifeUserViolationMapper.updateById(lifeuserViolation);
                }
                if ("4".equals(lifeuserViolation.getReportContextType())) {
                    // AI审核
                    //登录获取token
                    String token = aiUserViolationUtils.getAccessToken();
                    //调用AI接口
                    String taskId = aiUserViolationUtils.createGoodsTask(token, lifeuserViolation);
                    if (org.springframework.util.StringUtils.isEmpty(taskId)) {
                        log.warn("Failed to create AI task for second round review, lifeuserViolation id={}", lifeuserViolation.getId());
                        return 0;
                    }
                    lifeuserViolation.setAiTaskId(taskId);
                    lifeUserViolationMapper.updateById(lifeuserViolation);
                }

                if (lifeuserViolation.getReportContextType().equals("4") || lifeuserViolation.getReportContextType().equals("5")) {
                    String phoneId = Objects.requireNonNull(JwtUtil.getCurrentUserInfo()).getString("userType") + "_" + JwtUtil.getCurrentUserInfo().getString("phone");
                    // 举报通知
                    LifeNotice lifeNotice = getLifeNotice(lifeuserViolation);
                    lifeNoticeUtil.fillUserTypeAndRefId(lifeNotice);
                    lifeNoticeMapper.insert(lifeNotice);

                    // 保存图片
                    saveStoreImages(lifeuserViolation.getId(), lifeuserViolation);

                    WebSocketVo websocketVo = new WebSocketVo();
                    websocketVo.setSenderId("system");
                    websocketVo.setReceiverId(phoneId);
                    websocketVo.setCategory("notice");
                    websocketVo.setNoticeType("1");
                    websocketVo.setIsRead(0);
                    websocketVo.setText(com.alibaba.fastjson2.JSONObject.from(lifeNotice).toJSONString());
                    alienStoreFeign.sendMsgToClientByPhoneId(lifeNotice.getReceiverId(), com.alibaba.fastjson2.JSONObject.from(websocketVo).toJSONString());
                }
                return result;
            }
        } catch (Exception e) {
            log.error("SecondGoodsReportingServiceImpl_reporting Error Stack={}", e.getMessage());
            throw new Exception(e);
        }
        return 0;
    }

    private static LifeNotice getLifeNotice(LifeUserViolation lifeuserViolation)  {
        JSONObject data = JwtUtil.getCurrentUserInfo();
        String phoneId = null;
        if (data != null) {
            phoneId = data.getString("phone");
        }
        LifeNotice lifeNotice = new LifeNotice();
        lifeNotice.setSenderId("system");
        lifeNotice.setReceiverId("user_" + phoneId);
        lifeNotice.setBusinessId(lifeuserViolation.getId());
        lifeNotice.setTitle("举报通知");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("title", "平台已受理");
        jsonObject.put("message", "平台已受理，感谢您的反馈！");
        lifeNotice.setContext(jsonObject.toJSONString());
        lifeNotice.setNoticeType(1);
        return lifeNotice;
    }

    /**
     * 保存商品图片信息
     * @param id 举报ID
     * @param goods .getimgUrl 图片URL列表
     * @return 保存结果
     */
    private boolean saveStoreImages(Integer id, SecondUserViolationVo goods ) {
        if (CollectionUtil.isEmpty(goods.getImgUrl())) {
            return true; // 如果没有图片，则返回成功
        }
        // 批量保存图片信息
        for(int i = 0; i < goods.getImgUrl().size(); i++){
            StoreImg storeImg = new StoreImg();
            storeImg.setStoreId(id);
            storeImg.setImgType(Constants.ImageType.SECOND_HAND_REPORT);
            storeImg.setImgSort(i);
            storeImg.setImgDescription("二手举报图片");
            storeImg.setDeleteFlag(Constants.DeleteFlag.NOT_DELETED);
            storeImg.setCreatedTime(new Date());
            storeImg.setUpdatedTime(new Date());
            storeImg.setCreatedUserId(1);
            storeImg.setUpdatedUserId(1);
            storeImg.setImgUrl(goods.getImgUrl().get(i));
            // 保存图片 插入store_img数据库
            storeImgMapper.insert(storeImg);
        }
        return true;
    }
}