package io.modules.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.common.service.impl.CrudServiceImpl;
import io.modules.item.dao.DoctorsDao;
import io.modules.item.dao.FrontUserDao;
import io.modules.item.dao.ItemDao;
import io.modules.item.dao.UserBehaviorDao;
import io.modules.item.dto.ItemDTO;
import io.modules.item.entity.ItemEntity;
import io.modules.item.entity.UserBehaviorEntity;
import io.modules.item.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 主表
 */
@Service
public class ItemServiceImpl extends CrudServiceImpl<ItemDao, ItemEntity, ItemDTO> implements ItemService {


    @Autowired
    private FrontUserDao frontUserDao;

    @Autowired
    private UserBehaviorDao userBehaviorDao;

    @Autowired
    private DoctorsDao doctorsDao;

    @Override
    public QueryWrapper<ItemEntity> getWrapper(Map<String, Object> params){
        String title = (String)params.get("title");
        String status = (String)params.get("status");
        String view = (String)params.get("view");

        QueryWrapper<ItemEntity> wrapper = new QueryWrapper<>();

        if (StrUtil.isNotBlank(status)){

            switch (status){
                case "0":
                    wrapper.eq("status", 0);
                    break;
                case "1":
                    wrapper.eq("status", 1);
                    break;
                case "2":
                    wrapper.lt("stock_quantity", 100);
                    break;
                case "3":
                    wrapper.eq("stock_quantity", 0);
                    break;
            }
        }
        wrapper.like(StrUtil.isNotBlank(title), "title", title);
        wrapper.orderByDesc(StrUtil.isNotBlank(view), "view");


        return wrapper;
    }


    @Override
    public List<ItemEntity> score() {
        LambdaQueryWrapper<ItemEntity> lwq = new LambdaQueryWrapper<>();
        lwq.orderByDesc(ItemEntity::getView);


    // 创建 Page 对象，设置当前页和每页大小
            Page<ItemEntity> page = new Page<>(1, 10);  // 第1页，每页10条

    // 执行分页查询
            IPage<ItemEntity> result = baseDao.selectPage(page, lwq);

    // 获取查询结果
            List<ItemEntity> list = result.getRecords();
        return list;
    }

    @Override
    public List<Object> query() {
        ArrayList<Object> res = new ArrayList<>();
        Long item_total = frontUserDao.selectCount(null);
        //查询数据总和
        HashMap<String, Object> a1 = new HashMap<>();
        a1.put("name", "患者总量");
        a1.put("value", item_total);
        a1.put("tag", "位");
        res.add(a1);

        HashMap<String, Object> a2 = new HashMap<>();
        a2.put("name", "医生总量");
        a2.put("value", doctorsDao.selectCount(null));
        a2.put("tag", "位");
        res.add(a2);

        return res;
    }

    @Override
    public  List<Map<String, Object>> view() {

        QueryWrapper<ItemEntity> queryWrapper = Wrappers.query();

        // 使用 SELECT 和 COUNT 聚合函数，按 year 分组
        queryWrapper.select("year", "COUNT(*) as count")
                .groupBy("year");

        // 执行查询
        List<Map<String, Object>> result = baseDao.selectMaps(queryWrapper);

        // 格式化结果并排除空值
        List<Map<String, Object>> formattedResult = result.stream()
                .filter(row -> row.get("year") != null && row.get("count") != null)  // 过滤掉 year 或 count 为 null 的记录
                .map(row -> {
                    Map<String, Object> formattedRow = new HashMap<>();
                    formattedRow.put("name", row.get("year"));
                    formattedRow.put("value", row.get("count"));
                    return formattedRow;
                })
                .collect(Collectors.toList());

        return result;
    }

    @Override
    public List<ItemEntity> commit() {
        LambdaQueryWrapper<ItemEntity> lwq = new LambdaQueryWrapper<>();
        lwq.orderByDesc(ItemEntity::getView);

        // 创建 Page 对象，设置当前页和每页大小
        Page<ItemEntity> page = new Page<>(1, 10);  // 第1页，每页10条

        // 执行分页查询
        IPage<ItemEntity> result = baseDao.selectPage(page, lwq);

        // 获取查询结果
        List<ItemEntity> list = result.getRecords();
        return list;
    }

    @Override
    public List<ItemEntity> listUser( Long userId) {

        LambdaQueryWrapper<UserBehaviorEntity> lwq = new LambdaQueryWrapper<>();
        lwq.eq(UserBehaviorEntity::getUserId,userId);
        List<UserBehaviorEntity> list = userBehaviorDao.selectList(lwq);
        if (list.isEmpty()){
            return new ArrayList<>();
        }

        List<ItemEntity> res = new ArrayList<>();
        for (UserBehaviorEntity userBehaviorEntity : list) {
            res.add(baseDao.selectById(userBehaviorEntity.getItemId()));
        }
        return res;
    }
}
