package com.sz.admin.monitor.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.sz.admin.monitor.pojo.dto.dataModel.CanvasCfgDTO;
import com.sz.admin.monitor.pojo.dto.dataModel.DataModelDTO;
import com.sz.admin.monitor.pojo.dto.dataModel.GridCfgDTO;
import com.sz.admin.monitor.pojo.dto.dataModel.ModelContentDTO;
import com.sz.admin.monitor.pojo.po.CanvasCfgDO;
import com.sz.admin.monitor.pojo.po.GridCfgDO;
import com.sz.admin.monitor.pojo.po.ModelContentDO;
import com.sz.admin.monitor.pojo.po.UserModelContentDO;
import com.sz.admin.monitor.pojo.que.dataModel.DataModelQue;
import com.sz.admin.monitor.service.CanvasCfgService;
import com.sz.admin.monitor.service.GridCfgService;
import com.sz.admin.monitor.service.ModelContentService;
import com.sz.admin.monitor.service.UserModelContentService;
import com.sz.core.common.entity.ApiResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @author xq
 * @description:
 * @date 2026/1/29 10:51
 */
@Service
public class DataModelServiceImpl {
    @Autowired
    private CanvasCfgService canvasCfgService; // 画板

    @Autowired
    private GridCfgService gridCfgService; // 网格

    @Autowired
    private ModelContentService modelContentService;  //模型

    @Autowired
    private UserModelContentService userModelContentService; //用户模型中间表

    private static final String userId = "1";

    public ApiResult<DataModelDTO> getModelData(DataModelQue que) {
        if (StrUtil.isEmpty(que.getUserId()))
            que.setUserId(userId);

        QueryWrapper queryWrapper = QueryWrapper.create()
            .from(CanvasCfgDO.class)
            .where(CanvasCfgDO.USER_ID, que.getUserId())
            .limit(1);

        // 获取画板数据
        CanvasCfgDO canvasCfgDO = canvasCfgService.getOne(queryWrapper);

//        CanvasCfgDO canvasCfgDO = canvasCfgService.getOne(new QueryWrapper<CanvasCfgDO>()
//                .eq(CanvasCfgDO.USER_ID, que.getUserId())
//                .last("limit 1")
//        );
        if (ObjectUtil.isEmpty(canvasCfgDO)) {
            canvasCfgDO = initCanvasCfg();
            canvasCfgService.saveOrUpdate(canvasCfgDO);
        }

        // 获取网格数据
        GridCfgDO gridCfgDO = gridCfgService.getOne(QueryWrapper.create()
            .from(GridCfgDO.class)
            .where(GridCfgDO.USER_ID, que.getUserId())
            .limit(1)
        );
//        GridCfgDO gridCfgDO = gridCfgService.getOne(new QueryWrapper<GridCfgDO>()
//                .eq(GridCfgDO.USER_ID, userId)
//                .last("limit 1")
//        );
        if (ObjectUtil.isEmpty(gridCfgDO)) {
            gridCfgDO = initGridCfg();
            gridCfgService.saveOrUpdate(gridCfgDO);
        }

        //中间表
        List<UserModelContentDO> userModelList = userModelContentService.list(QueryWrapper.create()
            .from(UserModelContentDO.class)
            .where(UserModelContentDO.USER_ID, userId)
            .limit(1)
        );
//        List<UserModelContentDO> userModelList = userModelContentService.list(new QueryWrapper<UserModelContentDO>()
//            .eq(UserModelContentDO.USER_ID, userId)
//            .eq(UserModelContentDO.MENU_TYPE, que.getMenuType())
//        );

        ArrayList<ModelContentDTO> objects = new ArrayList<>();

        if (CollectionUtil.isEmpty(userModelList)) {
            DataModelDTO build = DataModelDTO.builder()
                .canvasCfg(CanvasCfgDO.doConvertDTO(canvasCfgDO))
                .gridCfg(GridCfgDO.doConvertDTO(gridCfgDO))
                .json(objects)
                .build();
            return ApiResult.success(build);
        }

        List<String> collect = userModelList.stream()
            .map(item -> item.getModelContentId())
            .collect(Collectors.toList());

        List<ModelContentDO> modelContentDOS = modelContentService.listByIds(collect);
        for (ModelContentDO modelContentDO : modelContentDOS) {
            objects.add(ModelContentDO.doConvertDTO(modelContentDO));
        }
        DataModelDTO build = DataModelDTO.builder()
            .canvasCfg(CanvasCfgDO.doConvertDTO(canvasCfgDO))
            .gridCfg(GridCfgDO.doConvertDTO(gridCfgDO))
            .json(objects)
            .build();
        return ApiResult.success(build);
    }

    /**
     * 初始化网格数据
     *
     * @return
     */
    public GridCfgDO initGridCfg() {
        return GridCfgDO.builder()
            .userId(userId)
            .enabled(true)
            .align(true)
            .size(10)
            .build();
    }

    /**
     * 初始化画板数据
     *
     * @return
     */
    public CanvasCfgDO initCanvasCfg() {
        return CanvasCfgDO.builder()
            .width(1920)
            .userId(userId)
            .height(1080)
            .scale(1D)
            .color("")
            .img("")
            .guide(true)
            .adsorp(true)
            .adsorpDiff(5D)
            .transformOrigin("{\"x\":0,\"y\":0}")
            .dragOffset("{\"x\":0,\"y\":0}")
            .build();
    }

    /**
     * 保存模型数据
     *
     * @param dataModelDTO
     * @param request
     * @param response
     * @return
     */
    @Transactional
    public ApiResult saveOrUpdateModelData(DataModelDTO dataModelDTO, HttpServletRequest request, HttpServletResponse response) {
        if (ObjectUtil.isEmpty(dataModelDTO))
            throw new IllegalArgumentException("传值错误");
        CanvasCfgDTO canvasCfg = dataModelDTO.getCanvasCfg();
        GridCfgDTO gridCfg = dataModelDTO.getGridCfg();
        List<ModelContentDTO> json = dataModelDTO.getJson();

        //保存、更新面板
        canvasCfg.setUserId(userId);
        canvasCfgService.saveOrUpdateCanvas(canvasCfg);

        //保存、更新网格
        gridCfg.setUserId(userId);
        gridCfgService.saveOrUpdateGrid(gridCfg);

        //保存数据模型
        HashMap<String, List<String>> map = modelContentService.saveOrUpdateModel(json, dataModelDTO.getMenuType());

        //获取中间表
        List<UserModelContentDO> list = userModelContentService.list(QueryWrapper.create()
            .from(UserModelContentDO.class)
            .where(UserModelContentDO.USER_ID, userId) //先写死
            .eq(UserModelContentDO.MENU_TYPE, dataModelDTO.getMenuType())
        );
//        List<UserModelContentDO> list = userModelContentService.list(new QueryWrapper<UserModelContentDO>()
//            .eq(UserModelContentDO.USER_ID, userId) //先写死
//            .eq(UserModelContentDO.MENU_TYPE, dataModelDTO.getMenuType())
//        );

        if (CollectionUtil.isEmpty(map)) {
            List<String> modelIds = list.stream()
                .map(item -> item.getModelContentId())
                .collect(Collectors.toList());
            modelContentService.removeByIds(modelIds);

            userModelContentService.remove(QueryWrapper.create()
                .from(UserModelContentDO.class)
                .where(UserModelContentDO.USER_ID, userId)
                .eq(UserModelContentDO.MENU_TYPE, dataModelDTO.getMenuType()));


//            userModelContentService.remove(new QueryWrapper<UserModelContentDO>()
//                .eq(UserModelContentDO.USER_ID, userId) //先写死
//                .eq(UserModelContentDO.MENU_TYPE, dataModelDTO.getMenuType()));
            return ApiResult.success();
        }

        //增加的id集合
        List<String> addIdModels = map.get("addIdModels");
        //跟新的id集合
        List<String> updateIdModels = map.get("updateIdModels");
        if (CollectionUtil.isEmpty(addIdModels))
            return ApiResult.success();

        //中间表没有数据，直接添加
        if (CollectionUtil.isEmpty(list)) {
            List<String> allModelIds = Stream.concat(addIdModels.stream(), updateIdModels.stream())
                .distinct()
                .collect(Collectors.toList());

            for (String modelId : allModelIds) {
                UserModelContentDO build = UserModelContentDO.builder()
                    .userId(userId)
                    .menuType(dataModelDTO.getMenuType())
                    .modelContentId(modelId)
                    .build();
                userModelContentService.save(build);
            }
            return ApiResult.success();
        } else { //中间表有数据
            List<String> collect = list.stream().map(UserModelContentDO::getModelContentId).collect(Collectors.toList());
            collect.removeAll(updateIdModels);
            modelContentService.removeByIds(collect);
            List<String> targetCollect = list.stream()
                .filter(item -> collect.contains(item.getModelContentId()))
                .map(UserModelContentDO::getId)
                .collect(Collectors.toList());
            userModelContentService.removeByIds(targetCollect);
            for (String addIdModel : addIdModels) {
                UserModelContentDO build = UserModelContentDO.builder()
                    .userId(userId)
                    .menuType(dataModelDTO.getMenuType())
                    .modelContentId(addIdModel)
                    .build();
                userModelContentService.save(build);
            }
        }
        return ApiResult.success();
    }

    public List<UserModelContentDO> getList() {
        return null;
    }

}
