package org.dromara.system.service.impl;

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.system.domain.bo.*;
import org.dromara.system.domain.vo.*;
import org.dromara.system.mapper.*;
import org.dromara.system.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.Facilities;

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

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

    private final FacilitiesMapper baseMapper;

    private final IImgTypeService imgTypeService;

    private final ISysImgService sysImgService;

    private final RegionFacilitiesMapper regionFacilitiesMapper;

    private final ISysDictDataService dictDataService;

    private final ISysOssService sysOssService;

    private final IRegionFacilitiesService regionFacilitiesService;

    private final RegionMapper regionMapper;

    private final CommunityMapper communityMapper;

    private final RoomMapper roomMapper;

    private final CommunityRoomServiceImpl communityRoomService;
//    private final IRoomService roomService;

//    private final IRoomRegionService roomRegionService;

    private final CommunityRoomMapper communityRoomMapper;

    private final PositionMapper positionMapper;

    private final RoomRegionServiceImpl roomRegionService;

    /**
     * 查询【请填写功能名称】
     */
    @Override
    public FacilitiesVo queryById(String facilitiesId){
        FacilitiesVo vo = baseMapper.selectVoById(facilitiesId);
        List<SysImgVo> list = this.querySysImg(facilitiesId);
        vo.setSysimg(list);
        return vo;
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @Override
    public TableDataInfo<FacilitiesVo> queryPageList(FacilitiesBo bo, PageQuery pageQuery) {
        Page<FacilitiesVo> result = new Page<>();
        if("0".equals(bo.getDictType()) || org.apache.commons.lang3.StringUtils.isBlank(bo.getDictType())){
            LambdaQueryWrapper<Facilities> lqw = buildQueryWrapper(bo);
            result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        }else {
            RegionBo s = new RegionBo();
            s.setRegionType(bo.getDictType());
            List<String> regionVoList = regionMapper.selectByRegionType(bo.getDictType());
            if(regionVoList.size() > 0){
                bo.setFacilitiesIds(regionVoList);
                LambdaQueryWrapper<Facilities> lqw = buildQueryWrapper(bo);
                result = baseMapper.selectVoPage(pageQuery.build(), lqw);
            }
        }
        if(result != null){
            List<FacilitiesVo> list = result.getRecords();
            for (FacilitiesVo facilitiesVo: list){
                List<SysImgVo> sysimg = this.querySysImg(facilitiesVo.getFacilitiesId());
                for (SysImgVo sysImgVo: sysimg){
                    if(StringUtils.isNotBlank(sysImgVo.getEnumC()) && sysImgVo.getEnumC().equals("0")){
                        facilitiesVo.setUrl(sysImgVo.getUrl());
                        break;
                    }
                }
                facilitiesVo.setSysimg(sysimg);
            }
            return TableDataInfo.build(result);
        }
        return TableDataInfo.build(result);
    }

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

    private LambdaQueryWrapper<Facilities> buildQueryWrapper(FacilitiesBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Facilities> lqw = Wrappers.lambdaQuery();
        if(bo.getFacilitiesIds() != null && bo.getFacilitiesIds().size() > 0){
            lqw.in(true, Facilities::getFacilitiesId, bo.getFacilitiesIds());
        }
        lqw.like(StringUtils.isNotBlank(bo.getFacilitiesId()), Facilities::getFacilitiesId, bo.getFacilitiesId());
        lqw.like(StringUtils.isNotBlank(bo.getFacilitiesName()), Facilities::getFacilitiesName, bo.getFacilitiesName());
        lqw.like(StringUtils.isNotBlank(bo.getFacilitiesTitle()), Facilities::getFacilitiesTitle, bo.getFacilitiesTitle());
        lqw.eq(StringUtils.isNotBlank(bo.getFacilitiesDesc()), Facilities::getFacilitiesDesc, bo.getFacilitiesDesc());
        return lqw;
    }

    /**
     * 新增【请填写功能名称】
     */
    @Override
    public Boolean insertByBo(FacilitiesBo bo) {
        Facilities add = MapstructUtils.convert(bo, Facilities.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setFacilitiesId(add.getFacilitiesId());
            // 图片
            for (SysImgBo voq : bo.getSysimg()){
                //关联图片
                ResponseBo res = voq.getResponse();
                if(res != null && res.getCode() == 200){
                    ImgTypeBo types = new ImgTypeBo();
                    types.setImgId(res.getData().getOssId());
                    types.setTypeId(add.getFacilitiesId());
                    types.setTypeC("3");           // 图片类型
                    boolean typeImg = imgTypeService.insertByBo(types);
                    if(typeImg){
                        SysImgBo img = new SysImgBo();
                        img.setImgType("3"); // 图片类型
                        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(FacilitiesBo bo) {
        Facilities update = MapstructUtils.convert(bo, Facilities.class);
        validEntityBeforeSave(update);
        boolean status = baseMapper.updateById(update) > 0;
        if(status){
            imgTypeService.batchDelete(List.of(bo.getFacilitiesId()));
            //图片更新
            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.getFacilitiesId());
                types.setTypeC("3");           // 图片类型
                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("3"); // 图片类型
                    sysImgService.insertByBo(img);
                }
            }
        }
        return status;
    }

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

    /**
     * 批量删除【请填写功能名称】
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        boolean status = baseMapper.deleteBatchIds(ids) > 0;
        if(status){
            // 删除数据字典
            for(String str: ids){
                SysDictDataVo vo = dictDataService.selectDictDataById(Long.valueOf(str));
                if(vo != null){
                    dictDataService.deleteDictDataByIds(new Long[]{Long.valueOf(str)});
                }
            }
            //删除关联设施
            //regionFacilitiesMapper.batchDeleteByFacilitiesId(new ArrayList(ids));
            regionFacilitiesService.batchDelete(new ArrayList(ids));
            //删除图片
            this.deleteImg(ids);
        }
        return status;
    }

    @Override
    public TableDataInfo<FacilitiesVo> queryPageListByWeixin(FacPageBo bo, PageQuery pageQuery) {
        List<FacilitiesVo> returnList = null;
        List<RegionVo> rgList = null;
        Page<FacilitiesVo> result = new Page<>();
        PositionVo vo = new PositionVo();
        if(bo.getPositionId() == null){
            List<PositionVo> list = positionMapper.selectAll();
            for(PositionVo item: list){
                vo = positionMapper.selectVoById(item.getPositionId());
                break;
            }
            rgList = getRegionList(vo, 1, bo);
        }else{
            vo = positionMapper.selectVoById(bo.getPositionId());
            rgList = getRegionList(vo, 2, bo);
        }

        pageQuery.setPageNum(bo.getPageNum());
        pageQuery.setPageSize(bo.getPageSize());
        if(rgList != null && rgList.size() > 0){
            List<String> regionids = new ArrayList();
            for(RegionVo rg: rgList){
                regionids.add(rg.getRegionId());
            }
//            RegionFacilitiesBo rfBo = new RegionFacilitiesBo();
//            rfBo.setRegionId(bo.getRegionId() == null ? rgList.get(0).getRegionId() : bo.getRegionId());
//            List<RegionFacilitiesVo> rfList = regionFacilitiesService.queryList(rfBo);
            List<RegionFacilitiesVo> fList = regionFacilitiesMapper.selectListByFacilitiesBoByRegionId(regionids);
            if(fList != null && fList.size() > 0){
                List<String> faIds = fList.stream().map(RegionFacilitiesVo:: getFacilitiesId).collect(Collectors.toList());
                bo.setFacilitiesIds(faIds);
                FacilitiesBo bo1 = new FacilitiesBo();
                BeanUtils.copyProperties(bo, bo1);
                LambdaQueryWrapper<Facilities> lqw = buildQueryWrapper(bo1);
                result = baseMapper.selectVoPage(pageQuery.build(), lqw);

                if(result != null){
                    List<FacilitiesVo> list = result.getRecords();
                    for (FacilitiesVo facilitiesVo: list){
                        List<SysImgVo> sysimg = this.querySysImg(facilitiesVo.getFacilitiesId());
                        for (SysImgVo sysImgVo: sysimg){
                            if(StringUtils.isNotBlank(sysImgVo.getEnumC()) && sysImgVo.getEnumC().equals("0")){
                                facilitiesVo.setUrl(sysImgVo.getUrl());
                                break;
                            }
                        }
                        facilitiesVo.setSysimg(sysimg);
                    }
                    return TableDataInfo.build(result);
                }
            }
//            List<String> regionIds = rfList.stream().map(RegionFacilitiesVo:: getFacilitiesId).collect(Collectors.toList());
//            bo.setFacilitiesIds(regionIds);
//            LambdaQueryWrapper<Facilities> lqw = buildQueryWrapper(bo);
//            result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        }
        return TableDataInfo.build(result);
    }

    // type 1 空 2 非空
    private List<RegionVo> getRegionList(PositionVo vo, int type, FacPageBo bo){
        List<RegionVo> rgList = null;
        if (vo != null){
            List<CommunityVo> comList = communityMapper.selectByPositionId(vo.getPositionId());
            if(comList != null && comList.size() > 0){
                List<CommunityVo> commList = comList.stream().filter(item -> item.getIsMaster() != null && "1".equals(item.getIsMaster())).toList();

                for(CommunityVo cv: commList){
                    // 房型
                    CommunityRoomBo crBo = new CommunityRoomBo();
                    crBo.setCommunityId(type == 1 ? cv.getCommunityId() : bo.getCommunityId());
                    List<CommunityRoomVo> crList = communityRoomService.queryList(crBo);
                    List<String> communityIds = crList.stream().map(CommunityRoomVo:: getRoomId).collect(Collectors.toList());
                    if(communityIds.size() > 0){
                        List<RoomVo> rList =roomMapper.selectListByRoomBoByCommunityId(communityIds);
                        List<RoomVo> rList2 = rList.stream().filter(r -> r.getIsMaster() != null && "1".equals(r.getIsMaster())).toList();
                        for(RoomVo r: rList2){
                            // 区域
                            RoomRegionBo rrBo = new RoomRegionBo();
                            rrBo.setRoomId(type == 1 ? r.getRoomId() : bo.getRoomId());
                            List<RoomRegionVo> rrList = roomRegionService.queryList(rrBo);
                            List<String> roomIds = rrList.stream().map(RoomRegionVo:: getRegionId).collect(Collectors.toList());
                            if(roomIds.size() > 0){
                                rgList = regionMapper.selectListByRegionBoByRoomId(roomIds);
                                // 设施
                                r.setRegion(rgList);
                            }
                        }
                        cv.setRoom(rList2);
                    }
                }
                vo.setCommunity(commList);
            }
        }
        return rgList;
    }

    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);
        }
    }
}
