package org.dromara.system.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import org.dromara.common.core.constant.GlobalConstants;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.system.domain.bo.*;
import org.dromara.system.domain.vo.*;
import org.dromara.system.mapper.FacilitiesMapper;
import org.dromara.system.mapper.RegionMapper;
import org.dromara.system.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.Room;
import org.dromara.system.mapper.RoomMapper;

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

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author Lion Li
 * @date 2024-12-13
 */
@RequiredArgsConstructor
@Service
public class RoomServiceImpl implements IRoomService {

    private final RoomMapper baseMapper;

    private final RegionMapper regionMapper;

    private final FacilitiesMapper facilitiesMapper;

    private final ISysImgService sysImgService;

    private final IImgTypeService imgTypeService;

    private final ISysOssService sysOssService;

    private final IRoomRegionService roomRegionService;

    private final IRegionService regionService;

    private final IFacilitiesService facilitiesService;

    private final IRegionFacilitiesService regionFacilitiesService;

    /**
     * 查询【请填写功能名称】
     */
    @Override
    public RoomVo queryById(String roomId){
        RoomVo vo = baseMapper.selectVoById(roomId);
        // 房型设施
        RoomRegionBo regionBo = new RoomRegionBo();
        regionBo.setRoomId(roomId);
        List<RoomRegionVo> list = roomRegionService.queryList(regionBo);
        List<RegionVo> regList = new ArrayList();
        for (int i=0; i<list.size(); i++) {
            RegionBo bo = new RegionBo();
            bo.setRegionId(list.get(i).getRegionId());
            List<RegionVo> listBo = regionService.queryList(bo); // 区域
            for(RegionVo v: listBo){
                List<SysImgVo> sysimg = this.querySysImg(v.getRegionId()); //区域图片
                v.setSysimg(sysimg);
            }
            regList.addAll(listBo);
        }
        vo.setRegion(regList);
        // 户型图片
        List<SysImgVo> sysimg = this.querySysImg(roomId);
        vo.setSysimg(sysimg);
        return vo;
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @Override
    public TableDataInfo<RoomVo> queryPageList(RoomBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Room> lqw = buildQueryWrapper(bo);
        Page<RoomVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<RoomVo> list = result.getRecords();
        for (RoomVo roomVo: list){
            List<SysImgVo> sysimg = this.querySysImg(roomVo.getRoomId());
            for (SysImgVo sysImgVo: sysimg){
                if(StringUtils.isNotBlank(sysImgVo.getEnumC()) && sysImgVo.getEnumC().equals("0")){
                    roomVo.setUrl(sysImgVo.getUrl());
                    break;
                }
            }
            roomVo.setSysimg(sysimg);
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @Override
    public List<RoomVo> queryList(RoomBo bo) {
        LambdaQueryWrapper<Room> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Room> buildQueryWrapper(RoomBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Room> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getRoomId()), Room::getRoomId, bo.getRoomId());
        lqw.like(StringUtils.isNotBlank(bo.getRoomName()), Room::getRoomName, bo.getRoomName());
        lqw.eq(StringUtils.isNotBlank(bo.getRoomTitle()), Room::getRoomTitle, bo.getRoomTitle());
        lqw.eq(StringUtils.isNotBlank(bo.getRoomDesc()), Room::getRoomDesc, bo.getRoomDesc());
        lqw.eq(StringUtils.isNotBlank(bo.getIsHot()), Room::getIsHot, bo.getIsHot());
        lqw.eq(StringUtils.isNotBlank(bo.getRoomSize()), Room::getRoomSize, bo.getRoomSize());
        lqw.eq(StringUtils.isNotBlank(bo.getDirection()), Room::getDirection, bo.getDirection());
        lqw.eq(bo.getFloorNum() != null, Room::getFloorNum, bo.getFloorNum());
        lqw.orderByDesc(Room::getCreateTime);
        return lqw;
    }

    /**
     * 新增【请填写功能名称】
     */
    @Override
    public Boolean insertByBo(RoomBoStr bo) {
        RoomBo vo = new RoomBo();
        vo.setRoomId(bo.getRoomId());
        vo.setRoomName(bo.getRoomName());
        vo.setRoomTitle(bo.getRoomTitle());
        vo.setRoomDesc(bo.getRoomDesc());
        vo.setDirection(bo.getDirection());
        vo.setFloorNum(bo.getFloorNum());
        vo.setRoomSize(bo.getRoomSize());
        vo.setIsHot(bo.getIsHot());
        Room add = MapstructUtils.convert(vo, Room.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setRoomId(add.getRoomId());
            // 关联区域
            if(!bo.getRegion().isEmpty() &&  bo.getRegion().size() > 0){
                for (int i=0; i<bo.getRegion().size(); i++){
                    RoomRegionBo roomRegionBo = new RoomRegionBo();
                    roomRegionBo.setRoomId(add.getRoomId());
                    roomRegionBo.setRegionId(String.valueOf(bo.getRegion().get(i).getRegionId()));
                    roomRegionService.insertByBo(roomRegionBo);
                }
            }
            //图片
            for (SysImgBo voq : bo.getSysimg()){
                if(voq.getResponse() != null && voq.getResponse().getCode() == 200){
                    //关联图片
                    ResponseBo res = voq.getResponse();
                    if(res != null && res.getCode() == 200){
                        ImgTypeBo types = new ImgTypeBo();
                        types.setImgId(res.getData().getOssId());
                        types.setTypeId(add.getRoomId());
                        types.setTypeC("1");           // 图片类型
                        boolean typeImg = imgTypeService.insertByBo(types);
                        if(typeImg){
                            SysImgBo img = new SysImgBo();
                            img.setImgType("1"); // 图片类型
                            if(StringUtils.isNotBlank(res.getData().getUrl())){
                                String str = res.getData().getUrl().substring(8);
                                img.setUrl(str);
                            }
                            img.setOssId(res.getData().getOssId());
                            img.setFileName(res.getData().getFileName());
                            img.setEnumC(voq.getEnumC()); //主图标识
                            sysImgService.insertByBo(img);
                        }
                    }
                }
            }
        }
        return flag;
    }

    /**
     * 修改【请填写功能名称】
     */
    @Override
    public Boolean updateByBo(RoomBoStr bo) {
        RoomBo roomBo = new RoomBo();
        BeanUtils.copyProperties(bo, roomBo);
        Room update = MapstructUtils.convert(roomBo, Room.class);
        validEntityBeforeSave(update);
        boolean status = baseMapper.updateById(update) > 0;
        if(status){
            // 区域更新
            roomRegionService.batchDelete(List.of(bo.getRoomId()));
            for (int i=0; i<bo.getRegion().size(); i++){
                RoomRegionBo roomRegionBo = new RoomRegionBo();
                roomRegionBo.setRoomId(bo.getRoomId());
                roomRegionBo.setRegionId(String.valueOf(bo.getRegion().get(i).getRegionId()));
                roomRegionService.insertByBo(roomRegionBo);
            }

            imgTypeService.batchDelete(List.of(bo.getRoomId()));
            //图片更新
            String[] ossId = new String[bo.getSysimg().size()];
            for (int i=0; i<bo.getSysimg().size(); i++){
                if(StringUtils.isNotBlank(bo.getSysimg().get(i).getOssId())){
                    ossId[i] = bo.getSysimg().get(i).getOssId();
                }
                if(bo.getSysimg().get(i).getResponse() != null){
                    ossId[i] = bo.getSysimg().get(i).getResponse().getData().getOssId();
                }
            }

            sysImgService.batchDelete(List.of(ossId));
            for (SysImgBo voq : bo.getSysimg()){
                //关联图片
                ImgTypeBo types = new ImgTypeBo();
                ResponseBo res = voq.getResponse();
                if(res != null){
                    types.setImgId(res.getData().getOssId());
                }else{
                    types.setImgId(voq.getOssId());
                }
                types.setTypeId(bo.getRoomId());
                types.setTypeC("1");           // 图片类型
                boolean typeImg = imgTypeService.insertByBo(types);
                if(typeImg){
                    SysImgBo img = new SysImgBo();
                    if(res != null && res.getCode() == 200){
                        img.setOssId(res.getData().getOssId());
                        img.setUrl(res.getData().getUrl().substring(8));
                        img.setFileName(res.getData().getFileName());
                        img.setEnumC(voq.isDefaults() == true ? "0" : null); //主图标识
                    }else{
                        img.setUrl(voq.getUrl());
                        img.setOssId(voq.getOssId());
                        img.setFileName(voq.getFileName());
                        String c = String.valueOf(voq.getEnumC());
                        img.setEnumC(String.valueOf(voq.getEnumC()) == "null" ? null : voq.getEnumC()); //主图标识
                    }
                    img.setImgType("1"); // 图片类型
                    sysImgService.insertByBo(img);
                }
            }
        }
        return status;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Room entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除【请填写功能名称】
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        boolean status = baseMapper.deleteBatchIds(ids) > 0;
        if(status){
            roomRegionService.batchDelete(new ArrayList(ids));
            this.deleteImg(ids);
        }
        return status;
    }

    @Override
    public TableDataInfo<RoomVo> queryPage(RoomBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Room> lqw = buildQueryWrapper(bo);
        Page<RoomVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<RoomVo> list = result.getRecords();

        for (RoomVo roomVo: list){
            // 区域
//            List<RegionVo> regionList = regionService.selectByRoomId(roomVo.getRoomId());
//            for(RegionVo r: regionList ){
//                // 区域图片
////                List<SysImgVo> imgList = sysImgService.selectByRoomId(roomVo.getRoomId(), r.getRegionId());
////                r.setSysimg(imgList);
//            }
//
//            roomVo.setRegion(regionList);

            System.out.println(roomVo.getRoomId()+"---------户型id---------");
            RoomRegionBo regionBo = new RoomRegionBo();
            regionBo.setRoomId(roomVo.getRoomId());
            List<RoomRegionVo> list2 = roomRegionService.queryList(regionBo);

            List<String> regionIds = list2.stream().map(RoomRegionVo::getRegionId).collect(Collectors.toList());
            System.out.println(regionIds+"--------户型区域关联id-------");

            List<RegionVo> regionList = regionMapper.selectByRegionId(regionIds);
            System.out.println(regionList.toString()+"-----------区域数据----------");

            if(!regionList.isEmpty() && regionList.size() > 0){
                for(RegionVo r: regionList){
                    List<SysImgVo> sysimg = this.querySysImg(r.getRegionId());
                    r.setSysimg(sysimg);//区域图片

                    RegionFacilitiesBo rfBo = new RegionFacilitiesBo();
                    rfBo.setRegionId(r.getRegionId());
                    List<RegionFacilitiesVo> regFacList = regionFacilitiesService.queryList(rfBo);
                    if(!regFacList.isEmpty() && regFacList.size() > 0){
                        List<String> facilitiesIds = regFacList.stream().map(RegionFacilitiesVo::getFacilitiesId).collect(Collectors.toList());

                        List<FacilitiesVo> facilitiesList = facilitiesMapper.selectByFacilitiesId(facilitiesIds);
                        System.out.println(facilitiesList.toString()+"-----------设施数据----------");

                        for(FacilitiesVo fv: facilitiesList){
                            List<SysImgVo> sysimgF = this.querySysImg(fv.getFacilitiesId()); //设施图片
                            fv.setSysimg(sysimgF);
                        }
                        r.setRegionFacilities(facilitiesList);
                    }
                }
            }
            roomVo.setRegion(regionList);

            List<SysImgVo> sysimg = this.querySysImg(roomVo.getRoomId());
            roomVo.setSysimg(sysimg);
        }

        return TableDataInfo.build(list);
    }

    public List<SysImgVo> querySysImg(String typeId) {
        ImgTypeBo imgTypeBo = new ImgTypeBo();
        imgTypeBo.setTypeId(typeId);
        List<SysImgVo> sysimg = new ArrayList();

        List<ImgTypeVo> typeList = imgTypeService.queryList(imgTypeBo);
        for (ImgTypeVo imgTypeVo : typeList) {
            SysImgBo sysImgBo = new SysImgBo();
            sysImgBo.setOssId(imgTypeVo.getImgId());
            sysImgBo.setImgType(imgTypeVo.getTypeC());
            sysimg.addAll(sysImgService.queryList(sysImgBo));
        }
        return sysimg;
    }

    public void deleteImg(Collection<String> ids) {
        ImgTypeBo bo = new ImgTypeBo();
        for (String i: ids){
            bo.setTypeId(i);
        }

        List<ImgTypeVo> list = imgTypeService.queryList(bo);
        imgTypeService.batchDelete(new ArrayList(ids));
        String[] ossId = new String[list.size()];
        List<Long> longs = new ArrayList();
        for (int i=0; i<list.size(); i++){
            ossId[i] = list.get(i).getImgId();
            longs.add(Long.valueOf(list.get(i).getImgId()));
        }
        if(ossId.length > 0){
            sysImgService.batchDelete(List.of(ossId));
            //删除图片服务器图片
            sysOssService.deleteWithValidByIds(longs, true);
        }
    }

}
