package cn.pluss.platform.mswitch.impl;

import cn.pluss.platform.api.PageInfo;
import cn.pluss.platform.dict.DictService;
import cn.pluss.platform.entity.CommonSwitch;
import cn.pluss.platform.entity.Dict;
import cn.pluss.platform.mapper.CommonSwitchMapper;
import cn.pluss.platform.mapper.DictMapper;
import cn.pluss.platform.mswitch.CommonSwitchService;
import cn.pluss.platform.util.PageUtils;
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.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@RequiredArgsConstructor
@Service
public class CommonSwitchServiceImpl extends ServiceImpl<CommonSwitchMapper, CommonSwitch> implements CommonSwitchService {

    private final DictService dictService;

    @Override
    public PageInfo<CommonSwitch> pageData(Page<CommonSwitch> page, CommonSwitch commonSwitch) {
        QueryWrapper<CommonSwitch> queryWrapper = new QueryWrapper<>(commonSwitch).orderByAsc("sort");
        IPage<CommonSwitch> pageData = getBaseMapper().selectPage(page, queryWrapper);

        List<String> codeList = new ArrayList<>();
        for (CommonSwitch item: pageData.getRecords()) {
            codeList.add(item.getCode());
        }

        List<Dict> dictList = dictService.getByCode(codeList);

        // dict 分组塞入开关选项
        for (CommonSwitch item: pageData.getRecords()) {
            Iterator<Dict> iterator = dictList.iterator();

            while (iterator.hasNext()) {
                Dict next = iterator.next();
                if (item.getCode().equals(next.getCode())) {
                    List<Dict> alterList = item.getAlterList();
                    if (alterList == null) {
                        alterList = new ArrayList<>();
                        item.setAlterList(alterList);
                    }

                    alterList.add(next);
                    iterator.remove();
                }
            }
        }

        return PageUtils.page(pageData);
    }
}