package shop.alien.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import shop.alien.entity.store.*;
import shop.alien.entity.store.dto.GroupRes;
import shop.alien.entity.store.dto.StoreEvaluationDto;
import shop.alien.mapper.EvaluationLabelMapper;
import shop.alien.mapper.StoreEvaluationMapper;
import shop.alien.mapper.StoreImgMapper;
import shop.alien.mapper.StoreLabelMapper;
import shop.alien.store.service.EvaluationLabelService;
import shop.alien.store.service.LifeUserService;
import shop.alien.store.service.StoreEvaluationService;
import shop.alien.store.service.StoreImgService;
import shop.alien.util.common.netease.TextCheckUtil;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

import static shop.alien.util.common.constant.Constant.SEQUENCE_NUM_1;
import static shop.alien.util.common.constant.Constant.SYMBOL_1;

/**
 * @Author: fcw
 * @CreateTime: 2025-04-24
 * @Description: 用户评价
 */
@Service
@RequiredArgsConstructor
public class StoreEvaluationServiceImpl extends ServiceImpl<StoreEvaluationMapper, StoreEvaluation> implements StoreEvaluationService {

    private final StoreEvaluationMapper storeEvaluationMapper;
    private final StoreLabelMapper storeLabelMapper;
    private final StoreImgMapper storeImgMapper;
    private final EvaluationLabelService evaluationLabelService;
    private final StoreImgService storeImgService;
    private final LifeUserService lifeUserService;
    private final EvaluationLabelMapper evaluationLabelMapper;

    @Override
    public boolean saveStoreEvaluation(StoreEvaluation storeEvaluation) {
        int insert = storeEvaluationMapper.insert(storeEvaluation);
        if (insert > 0) {
            //计算星级餐厅
            //查询label表是否存在该店铺
            QueryWrapper<StoreLabel> storeLabelQueryWrapper = new QueryWrapper<>();
            storeLabelQueryWrapper.eq("storeId", storeEvaluation.getStoreId());
            StoreLabel storeLabel = storeLabelMapper.selectOne(storeLabelQueryWrapper);
            if (null != storeLabel) {
                //已存在该店铺
                //计算
            }

            //计算餐厅排行榜

        }
        return false;
    }

    /**
     * 新增评价
     */
    @Override
    public Integer saveEvaluation(StoreEvaluationDto dto) {

        try {
            Map<String, String> checkText = TextCheckUtil.check(dto.getEvaluationContent());
            if (null == checkText || checkText.get("result").equals("1")) {
                return 3;
            }

            StoreEvaluation se = new StoreEvaluation();
            BeanUtils.copyProperties(dto, se);
            se.setCreatedUserId(Integer.valueOf(dto.getUserId()));
            se.setCreatedTime(new Date());
            se.setLevels("1");
            se.setLikes(0);
            if (!CollectionUtils.isEmpty(dto.getEvaluationImageList())) {
                se.setEvaluationImage("exist");
            }


            // 其他评分
            Optional.ofNullable(dto.getOtherScoreList()).
                    ifPresent(otherScoreList ->
                            se.setOtherScore(String.join(SYMBOL_1, dto.getOtherScoreList()))
                    );


            int res = storeEvaluationMapper.insert(se);

            // 评价标签
            Optional.ofNullable(dto.getEvaluationTagsList()).
                    ifPresent(evaluationTagsList ->
                            evaluationTagsList.forEach(e -> {
                                EvaluationLabel label = new EvaluationLabel();
                                label.setEvaluationId(se.getId().toString());
                                label.setStoreId(se.getStoreId());
                                label.setLabel(e);
                                label.setType("1");
                                evaluationLabelService.save(label);
                            })
                    );


            // 图片
            AtomicInteger serialNumber = new AtomicInteger(SEQUENCE_NUM_1);
            Optional.ofNullable(dto.getEvaluationImageList()).
                    ifPresent(evaluationImageList ->
                            evaluationImageList.forEach(image -> {
                                StoreImg storeImg = new StoreImg();
                                storeImg.setStoreId(se.getId());
                                storeImg.setImgType(8);
                                storeImg.setImgSort(serialNumber.getAndIncrement());
                                storeImg.setImgUrl(image);
                                storeImgMapper.insert(storeImg);

                            })
                    );


            return res;

        } catch (Exception e) {
            return 2;
        }


    }

    @Override
    public Integer saveLev(Integer id, String content, String userId) {

        try {

            Map<String, String> checkText = TextCheckUtil.check(content);
            if (null == checkText || checkText.get("result").equals("1")) {
                return 3;
            }


            StoreEvaluation storeEvaluation = storeEvaluationMapper.selectById(id);
            StoreEvaluation se = new StoreEvaluation();
            se.setEvaluationContent(content);
            se.setStoreId(storeEvaluation.getStoreId());
            se.setUserId(userId);
            se.setLevels("2");
            se.setPid(id.toString());
            int res = storeEvaluationMapper.insert(se);

            return res;
        } catch (Exception e) {
            return 2;
        }

    }

    @Override
    public Integer like(Integer id) {
        StoreEvaluation storeEvaluation = storeEvaluationMapper.selectById(id);
        storeEvaluation.setLikes(storeEvaluation.getLikes() + 1);

        EvaluationLabel label = new EvaluationLabel();
        label.setEvaluationId(id.toString());
        label.setStoreId(storeEvaluation.getStoreId());
        label.setType("2");
        label.setUserId(storeEvaluation.getUserId());
        evaluationLabelService.save(label);

        return storeEvaluationMapper.updateById(storeEvaluation);

    }

    @Override
    public Map<String, String> title(String storeId) {
        Map<String, String> res = new HashMap<>();
        QueryWrapper<StoreEvaluation> wrapper = new QueryWrapper<>();
        wrapper.eq(nonNull(storeId), "store_id", storeId).
                eq("evaluation_image", "exist");
        Integer imgCount = storeEvaluationMapper.selectCount(wrapper);


        QueryWrapper<StoreEvaluation> wrapper2 = new QueryWrapper<>();
        wrapper2.le("score", 2);
        Integer differ = storeEvaluationMapper.selectCount(wrapper2);


        QueryWrapper<StoreEvaluation> wrapper3 = new QueryWrapper<>();
        wrapper.eq(nonNull(storeId), "store_id", storeId);
        Integer count = storeEvaluationMapper.selectCount(wrapper3);


        String avgSource = storeEvaluationMapper.avgSource(storeId);


        res.put("count", count.toString());
        res.put("imgCount", imgCount.toString());
        res.put("differCount", differ.toString());
        res.put("avgSource", avgSource);

        return res;

    }

    @Override
    public IPage<StoreEvaluationDto> page(int page, int size, String storeId, String evaluationImage, String score, List<String> lable, String userId, String id) {
        IPage<StoreEvaluation> iPage = new Page<>(page, size);
        QueryWrapper<StoreEvaluation> queryWrapper = new QueryWrapper<>();


        queryWrapper.eq(nonNull(storeId), "store_id", storeId)
                .eq(nonNull(evaluationImage), "evaluation_image", evaluationImage)
                .eq("levels", "1")
                .eq(nonNull(id), "id", id)
                .le(nonNull(score), "score", score);


        if (!CollectionUtils.isEmpty(lable)) {
            Set<String> res = evaluationLabelService.getLabel(storeId, lable);
            queryWrapper.in("id", res);
        }

        IPage<StoreEvaluation> pageRes = storeEvaluationMapper.selectPage(iPage, queryWrapper);
        IPage<StoreEvaluationDto> res = pageRes.convert(e -> {
            StoreEvaluationDto StoreEvaluationDto = new StoreEvaluationDto();
            BeanUtils.copyProperties(e, StoreEvaluationDto);

            // 图片
            List<String> ims = storeImgService.getUrl(e.getId().toString(), 8);
            StoreEvaluationDto.setEvaluationImageList(ims);

            // 子评论
            List<StoreEvaluation> subEva = storeEvaluationMapper.selectList(new QueryWrapper<StoreEvaluation>().eq("pid", e.getId()));
            StoreEvaluationDto.setSubEva(subEva);
            StoreEvaluationDto.setSubEvaCount(subEva.size());

            LifeUser lifeUser = lifeUserService.getById(e.getUserId());
            StoreEvaluationDto.setUserName(lifeUser.getUserName());
            StoreEvaluationDto.setUserImage(lifeUser.getUserImage());
            StoreEvaluationDto.setPhoneId("user_" + lifeUser.getUserPhone());


            // 是否评论
            String isLike = evaluationLabelMapper.isLike(userId);
            if (Objects.nonNull(isLike)) {
                int count = Integer.valueOf(isLike);
                boolean f = count > 0 ? true : false;
                StoreEvaluationDto.setIslike(f);
            } else {
                StoreEvaluationDto.setIslike(false);
            }
            return StoreEvaluationDto;

        });
        return res;
    }

    @Override
    public List<GroupRes> groupCount(String storeId) {
        return storeEvaluationMapper.groupCount(storeId);
    }


    private boolean nonNull(String str) {
        return (str != null && str != "") ? true : false;
    }

}
