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.stereotype.Service;
import shop.alien.entity.second.SecondGoods;
import shop.alien.entity.second.SecondGoodsRecord;
import shop.alien.entity.store.StoreImg;
import shop.alien.mapper.StoreImgMapper;
import shop.alien.mapper.second.SecondGoodsRecordMapper;
import shop.alien.second.service.SecondGoodsOperationRecordService;
import shop.alien.util.common.Constants;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 二手商品操作历史记录服务实现类
 * 负责记录商品的各种操作历史
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SecondGoodsOperationRecordServiceImpl implements SecondGoodsOperationRecordService {

    /**
     * 商品操作历史记录Mapper
     */
    private final SecondGoodsRecordMapper secondGoodsRecordMapper;

    /**
     * 店铺图片Mapper
     */
    private final StoreImgMapper storeImgMapper;

    /**
     * 记录商品操作历史
     * @param goods 商品信息
     * @param operationName 操作名称
     */
    @Override
    public void recordGoodsOperation(SecondGoods goods, String operationName) {
        try {
            log.warn("开始创建操作历史: {},{} ", goods, operationName);
            SecondGoodsRecord record = new SecondGoodsRecord();
            record.setOperationName(operationName);
            record.setGoodsId(goods.getId());
            record.setUserId(goods.getUserId());
            record.setTitle(goods.getTitle());
            record.setDescription(goods.getDescription());
            
            // 价格转换
            if (goods.getAmount() != null) {
                record.setPrice(goods.getAmount());
            } else if (goods.getPrice() != null && !goods.getPrice().isEmpty()) {
                try {
                    record.setPrice(new BigDecimal(goods.getPrice()));
                } catch (Exception e) {
                    log.warn("转换商品价格时出错: {}", e.getMessage());
                }
            }
            
            record.setPosition(goods.getPosition());
            record.setLikeCount(goods.getLikeCount());
            record.setCollectCount(goods.getCollectCount());
            record.setCategoryOneId(goods.getCategoryOneId());
            record.setCategoryTwoId(goods.getCategoryTwoId());
            record.setLabel(goods.getLabel());
            record.setTopic(goods.getTopic());
            record.setTradeId(goods.getTradeId());
            record.setReleaseTime(goods.getReleaseTime());
            record.setGoodsStatus(goods.getGoodsStatus());
            record.setFailedReason(goods.getFailedReason());
            record.setHomeImage(goods.getHomeImage());
            record.setVideoTaskId(goods.getVideoTaskId());
            record.setVideoFirstFrame(goods.getVideoFirstFrame());
            record.setDeleteFlag(goods.getDeleteFlag());
            record.setCreatedTime(goods.getCreatedTime());
            record.setCreatedUserId(goods.getCreatedUserId());
            record.setUpdatedTime(goods.getUpdatedTime());
            record.setUpdatedUserId(goods.getUpdatedUserId());
            record.setAddressText(goods.getAddressText());
            
            secondGoodsRecordMapper.insert(record);
            log.warn("创建操作历史结束: {} ", record);
            
            // 保存图片信息
            saveRecordGoodsImages(record);
        } catch (Exception e) {
            log.error("记录商品操作历史时发生异常", e);
        }
    }

    /**
     * 保存二手商品记录图片类型信息
     * @param record 保存后的商品记录
     */
    private void saveRecordGoodsImages(SecondGoodsRecord record) {
        log.info("创建操作历图片史开始: {} ", record);
        // 获取商品图片列表
        QueryWrapper<StoreImg> query = new QueryWrapper<>();
        query.lambda().eq(StoreImg::getStoreId, record.getGoodsId())
                .eq(StoreImg::getImgType, Constants.ImageType.SECOND_HAND_GOODS);
        List<StoreImg> storeImgs = storeImgMapper.selectList(query);
        
        // 保存前先把原有的删除
        storeImgs.forEach(storeImgModel -> {
            StoreImg storeImg = new StoreImg();
            storeImg.setStoreId(record.getId());
            storeImg.setImgType(Constants.ImageType.SECOND_HAND_RECORD);
            storeImg.setImgSort(storeImgModel.getImgSort());
            storeImg.setImgDescription("二手商品记录图片类型");
            storeImg.setDeleteFlag(Constants.DeleteFlag.NOT_DELETED);
            storeImg.setCreatedTime(new Date());
            storeImg.setUpdatedTime(new Date());
            storeImg.setCreatedUserId(1);
            storeImg.setUpdatedUserId(1);
            storeImg.setImgUrl(storeImgModel.getImgUrl());
            // 保存图片 插入store_img数据库
            storeImgMapper.insert(storeImg);
            log.info("创建操作历图片结束: {} ", storeImg);
        });
    }
}

