package com.backendsys.modules.material.service.impl;

import com.backendsys.exception.CustException;
import com.backendsys.modules.material.dao.MaterialCategoryDao;
import com.backendsys.modules.material.dao.MaterialFeedbackDao;
import com.backendsys.modules.material.dao.MaterialLoraDao;
import com.backendsys.modules.material.entity.MaterialCategory;
import com.backendsys.modules.material.entity.MaterialFeedback;
import com.backendsys.modules.material.entity.MaterialLora;
import com.backendsys.modules.material.service.MaterialFeedbackService;
import com.backendsys.utils.response.PageEntity;
import com.backendsys.utils.response.PageInfoResult;
import com.backendsys.utils.v2.PageUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
public class MaterialFeedbackServiceImpl implements MaterialFeedbackService {

    @Autowired
    private MaterialLoraDao materialLoraDao;
    @Autowired
    private MaterialCategoryDao materialCategoryDao;
    @Autowired
    private MaterialFeedbackDao materialFeedbackDao;


    /**
     * 获取素材需求反馈列表
     */
    @Override
    public PageEntity selectMaterialFeedbackList(MaterialFeedback materialFeedback) {
        PageUtils.startPage();  // 分页
        List<Map<String, Object>> list = materialFeedbackDao.selectMaterialFeedbackList(materialFeedback);
        return new PageInfoResult(list).toEntity();
    }


    /**
     * 发送素材需求反馈
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> sendMaterialFeedback(MaterialFeedback materialFeedback) {

        // [DB] 判断素材风格是否存在
        Long lora_id = materialFeedback.getLora_id();
        LambdaQueryWrapper<MaterialLora> wrapperLora = new LambdaQueryWrapper<>();
        wrapperLora.eq(MaterialLora::getLora_id, lora_id);
        Boolean is_lora_exist = materialLoraDao.exists(wrapperLora);
        if (!is_lora_exist) throw new CustException("素材风格不存在");

        // [DB] 判断素材分类是否存在
        Long category_id = materialFeedback.getCategory_id();
        LambdaQueryWrapper<MaterialCategory> wrapperCategory = new LambdaQueryWrapper<>();
        wrapperCategory.eq(MaterialCategory::getCategory_id, category_id);
        Boolean is_category_exist = materialCategoryDao.exists(wrapperCategory);
        if (!is_category_exist) throw new CustException("素材分类不存在");

        // [DB] 新增 素材需求反馈
        materialFeedbackDao.insert(materialFeedback);

        return Map.of("feedback_id", materialFeedback.getId());
    }

}
