package shop.alien.second.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import shop.alien.entity.second.SecondGoods;
import shop.alien.entity.second.vo.SecondReportingVo;
import shop.alien.entity.store.*;
import shop.alien.mapper.LifeNoticeMapper;
import shop.alien.mapper.LifeUserMapper;
import shop.alien.mapper.LifeUserViolationMapper;
import shop.alien.mapper.StoreDictionaryMapper;
import shop.alien.mapper.second.SecondGoodsMapper;
import shop.alien.second.service.SecondGoodsReportingService;

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;

    @Autowired
    private final LifeUserViolationMapper lifeUserViolationMapper;

    @Autowired
    private final StoreDictionaryMapper StoreDictionaryMapper;

    @Autowired
    private final LifeUserMapper lifeUserMapper;

    @Autowired
    private final SecondGoodsMapper secondGoodsMapper;

    @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")) {
            // 获取商品信息
            SecondGoods secondGoods = secondGoodsMapper.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);
        }

        secondReportingVo.setFeedbackContext("平台已受理，感谢您的反馈！");
        secondReportingVo.setReportingTime(lifeNotice.getCreatedTime());
        secondReportingVo.setFeedbackTime(lifeNotice.getCreatedTime());
        List<Map<String, Object>> list = new ArrayList<>();
        List<String> urlList = Arrays.asList(lifeUserViolation.getReportEvidenceImg().split(","));
        // 存放已存在文件list
        List<String> videoList = new ArrayList<>();

        for (int i = 0; i < urlList.size(); i++) {
            Map<String, Object> map = new HashMap<>();

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

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

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

        }

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

    }
}