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

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author Lion Li
 * @date 2025-03-24
 */
@RequiredArgsConstructor
@Service
public class CommunityServiceImpl implements ICommunityService {

    private final CommunityMapper baseMapper;

    private final ICommunityRoomService communityRoomService;

    private final ISysImgService sysImgService;

    private final IImgTypeService imgTypeService;

    private final IRoomService roomService;

    /**
     * 查询社区信息
     */
    @Override
    public CommunityVo queryById(String communityId){
        CommunityVo vo =baseMapper.selectVoById(communityId);
        CommunityRoomBo cRoomBo = new CommunityRoomBo();
        // 社区房型
        cRoomBo.setCommunityId(communityId);
        List<CommunityRoomVo> list = communityRoomService.queryList(cRoomBo);
        List<RoomVo> regList = new ArrayList();
        for (int i=0; i<list.size(); i++) {
            RoomBo bo = new RoomBo();
            bo.setRoomId(list.get(i).getRoomId());
            List<RoomVo> listBo = roomService.queryList(bo); // 房型
            for(RoomVo v: listBo){
                List<SysImgVo> sysimg = this.querySysImg(v.getRoomId()); //房型图片
                v.setSysimg(sysimg);
            }
            regList.addAll(listBo);
        }
        vo.setRoom(regList);
        // 社区图片
        List<SysImgVo> sysimg = this.querySysImg(communityId);
        vo.setSysimg(sysimg);
        return vo;
    }

    /**
     * 查询社区列表
     */
    @Override
    public TableDataInfo<CommunityVo> queryPageList(CommunityBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Community> lqw = buildQueryWrapper(bo);
        Page<CommunityVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<CommunityVo> list = result.getRecords();
        for (CommunityVo coVo: list){
            List<SysImgVo> sysimg = this.querySysImg(coVo.getCommunityId());
            for (SysImgVo sysImgVo: sysimg){
                if(StringUtils.isNotBlank(sysImgVo.getEnumC()) && sysImgVo.getEnumC().equals("0")){
                    coVo.setUrl(sysImgVo.getUrl());
                    break;
                }
            }
            coVo.setSysimg(sysimg);
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询社区列表
     */
    @Override
    public List<CommunityVo> queryList(CommunityBo bo) {
        LambdaQueryWrapper<Community> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Community> buildQueryWrapper(CommunityBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Community> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getCommunityId()), Community::getCommunityId, bo.getCommunityId());
        lqw.like(StringUtils.isNotBlank(bo.getCommunityName()), Community::getCommunityName, bo.getCommunityName());
        lqw.eq(StringUtils.isNotBlank(bo.getCommunityTitle()), Community::getCommunityTitle, bo.getCommunityTitle());
        lqw.eq(StringUtils.isNotBlank(bo.getCommunityDesc()), Community::getCommunityDesc, bo.getCommunityDesc());
        lqw.eq(bo.getIsMaster() != null, Community::getIsMaster, bo.getIsMaster());
        lqw.orderByDesc(Community::getIsMaster);
        return lqw;
    }

    /**
     * 新增社区
     */
    @Override
    public Boolean insertByBo(CommunityBoStr bo) {
        CommunityBo addVo = new CommunityBo();
        addVo.setCommunityName(bo.getCommunityName());
        addVo.setCommunityTitle(bo.getCommunityTitle());
        addVo.setCommunityDesc(bo.getCommunityDesc());
        addVo.setIsMaster(bo.getIsMaster());
        Community add = MapstructUtils.convert(addVo, Community.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setCommunityId(add.getCommunityId());

            // 关联房型信息
            bo.getRoom().forEach(room -> {
                CommunityRoomBo vo = new CommunityRoomBo();
                vo.setCommunityId(add.getCommunityId());
                vo.setRoomId(room.getRoomId());
                communityRoomService.insertByBo(vo);     // 新增房型信息
            });

            //图片
            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.getCommunityId());
                        types.setTypeC("5");           // 图片类型
                        boolean typeImg = imgTypeService.insertByBo(types);
                        if(typeImg){
                            SysImgBo img = new SysImgBo();
                            img.setImgType("5"); // 图片类型
                            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(CommunityBoStr bo) {
        CommunityBo communityBo = new CommunityBo();
        BeanUtils.copyProperties(bo, communityBo);
        Community update = MapstructUtils.convert(communityBo, Community.class);
        validEntityBeforeSave(update);
        boolean status = baseMapper.updateById(update) > 0;
        if(status){
            // 房型更新
            communityRoomService.batchDelete(List.of(bo.getCommunityId()));
            for (int i=0; i<bo.getRoom().size(); i++){
                CommunityRoomBo communityRoomBo = new CommunityRoomBo();
                communityRoomBo.setCommunityId(bo.getCommunityId());
                communityRoomBo.setRoomId(String.valueOf(bo.getRoom().get(i).getRoomId()));
                communityRoomService.insertByBo(communityRoomBo);
            }

            imgTypeService.batchDelete(List.of(bo.getCommunityId()));
            //图片更新
            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.getCommunityId());
                types.setTypeC("5");           // 图片类型
                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());
                        img.setEnumC(String.valueOf(voq.getEnumC()) == "null" ? null : voq.getEnumC()); //主图标识
                    }
                    img.setImgType("5"); // 图片类型
                    sysImgService.insertByBo(img);
                }
            }
        }
        return status;
    }

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

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

    @Override
    public List<CommunityVo> queryAll(CommunityBo bo) {
        List<CommunityVo> list = new ArrayList<>();
        PageQuery pageQuery = new PageQuery();
        if(bo.getCommunityId() != null){
            CommunityVo vo =baseMapper.selectVoById(bo.getCommunityId());
            list.add(vo);
        }else{
            LambdaQueryWrapper<Community> lqw = buildQueryWrapper(bo);
            Page<CommunityVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
            list = result.getRecords();
            list = list.stream().filter(item -> item.getIsMaster() != null && "1".equals(item.getIsMaster())).toList();
        }
        return 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;
    }

}
