package cn.ysk.cashier.mybatis.service.impl;

import cn.ysk.cashier.exception.BadRequestException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ysk.cashier.mybatis.mapper.TbShopExtendMapper;
import cn.ysk.cashier.mybatis.entity.TbShopExtend;
import cn.ysk.cashier.mybatis.service.TbShopExtendService;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.StringUtils;
import cn.ysk.cashier.dto.shop.TbShopExtendQueryCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import cn.ysk.cashier.utils.PageUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 店铺扩展信息(TbShopExtend)表服务实现类
 *
 * @author ww
 * @since 2024-07-18 10:57:39
 */
@Service("tbShopExtendService")
public class TbShopExtendServiceImpl extends ServiceImpl<TbShopExtendMapper, TbShopExtend> implements TbShopExtendService {

    @Autowired
    private TbShopExtendMapper tbShopExtendmapper;

    @Override
    public Map<String, Object> queryAll(TbShopExtendQueryCriteria criteria) {
        Page<TbShopExtend> page = new Page<>(criteria.getPage(), criteria.getSize());
        QueryWrapper<TbShopExtend> wrapper = new QueryWrapper<>();
        wrapper.eq("shop_id", criteria.getShopId());
        if (StringUtils.isNotBlank(criteria.getType())) {
            wrapper.eq("type",criteria.getType());
        }
        if (StringUtils.isNotBlank(criteria.getAutokey())) {
            wrapper.like("autokey",criteria.getAutokey());
        }
        wrapper.orderByDesc("create_time");
        Page<TbShopExtend> ipage = tbShopExtendmapper.selectPage(page, wrapper);
        ipage = checkAndInitialize(ipage,criteria.getShopId());
        return PageUtil.toPage(ipage.getRecords(), ipage.getTotal());
    }

    @Override
    public void saveInfo(TbShopExtend tbShopExtend) {
        QueryWrapper<TbShopExtend> wrapper = new QueryWrapper<>();
        wrapper.eq("shop_id", tbShopExtend.getShopId());
        wrapper.like("autokey",tbShopExtend.getAutokey());
        if(tbShopExtendmapper.exists(wrapper)){
            throw new BadRequestException("该自定义key已存在");
        }
        tbShopExtendmapper.insert(tbShopExtend);
    }

    public Page<TbShopExtend> checkAndInitialize(Page<TbShopExtend> ipage, Integer shopId) {
        List<TbShopExtend> newRecords = new ArrayList<>();
        List<String> requiredAutokeys = Arrays.asList("index_bg", "my_bg", "member_bg", "shopinfo_bg");

        if (ipage == null || ipage.getRecords() == null || ipage.getRecords().isEmpty()) {
            // ipage 为空，直接创建包含四种类型数据的新 Page 对象
            for (String key : requiredAutokeys) {
                TbShopExtend newRecord = new TbShopExtend();
                newRecord.initAutoKey(key, shopId);
                newRecords.add(newRecord);
            }
            return new Page<TbShopExtend>(1, newRecords.size(), newRecords.size())  // pageNum, pageSize, total
                    .setRecords(newRecords);
        } else {
            // ipage 不为空，补充缺失的数据
            List<TbShopExtend> shopExtends = ipage.getRecords();
            Set<String> existingAutokeys = shopExtends.stream()
                    .map(TbShopExtend::getAutokey)
                    .collect(Collectors.toSet());

            List<String> missingAutokeys = requiredAutokeys.stream()
                    .filter(key -> !existingAutokeys.contains(key))
                    .collect(Collectors.toList());

            for (String key : missingAutokeys) {
                TbShopExtend newRecord = new TbShopExtend();
                newRecord.initAutoKey(key, shopId);
                newRecords.add(newRecord);
            }

            // 更新现有记录并将新记录添加到原来的列表中
            shopExtends.addAll(newRecords);

            return new Page<TbShopExtend>(ipage.getCurrent(), ipage.getSize(), ipage.getTotal() + newRecords.size())
                    .setRecords(shopExtends);
        }
    }
}

