package com.cpop.jambox.business.service.impl;

import com.cpop.common.utils.StringUtils;
import com.cpop.core.base.entity.BaseEntity;
import com.cpop.core.utils.SpringUtils;
import com.cpop.jambox.business.entity.Plug;
import com.cpop.jambox.business.entity.StorePlug;
import com.cpop.jambox.business.mapper.StorePlugMapper;
import com.cpop.jambox.business.service.PlugService;
import com.cpop.jambox.business.service.StorePlugService;
import com.cpop.jambox.business.vo.StorePlugListVo;
import com.mybatisflex.core.datasource.DataSourceKey;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.row.Db;
import com.mybatisflex.core.row.Row;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.cpop.jambox.business.entity.table.PlugTableDef.PLUG;
import static com.cpop.jambox.business.entity.table.StorePlugTableDef.STORE_PLUG;

/**
 * 校区-插件记录表 服务层实现。
 *
 * @author DB
 * @since 2023-12-29
 */
@Service("storePlugService")
public class StorePlugServiceImpl extends ServiceImpl<StorePlugMapper, StorePlug> implements StorePlugService {

    /**
     * 查询校区插件列表
     *
     * @param brandId 品牌
     * @param storeId 校区
     * @return List<StorePlugListVo>
     * @author DB
     * @since 2023/12/29
     */
    @Override
    public List<StorePlugListVo> getStorePlugList(String brandId, String storeId) {
        if (StringUtils.isBlank(brandId) || StringUtils.isBlank(storeId)) {
            return new ArrayList<>();
        }
        //获取所有插件
        List<StorePlugListVo> plugList = SpringUtils.getBean(PlugService.class).listAs(QueryWrapper.create(), StorePlugListVo.class);
        if (!plugList.isEmpty()) {
            Map<String, LocalDateTime> plugTagMap = this.list(QueryWrapper.create()
                    .where(STORE_PLUG.STORE_ID.eq(storeId))).stream().collect(Collectors.toMap(StorePlug::getPlugTag, BaseEntity::getCreateTime));
            plugList.forEach(item -> {
                if (plugTagMap.get(item.getPlugTag()) != null) {
                    item.setIsOpen(true);
                    item.setOpenTime(plugTagMap.get(item.getPlugTag()));
                } else {
                    item.setIsOpen(false);
                }
                item.setStoreId(storeId);
            });
            return plugList;
        } else {
            return new ArrayList<>();
        }
    }
}
