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.PositionList;
import org.dromara.system.domain.RegionList;
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.Position;

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

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

    private final PositionMapper baseMapper;

    private final IPositionCommunityService positionCommunityService;

    private final ISysImgService sysImgService;

    private final IImgTypeService imgTypeService;

    private final ICommunityService communityService;

    private final ICommunityRoomService communityRoomService;

    private final IRoomService roomService;

    private final CommunityMapper communityMapper;

    private final RoomMapper roomMapper;

    private final RoomRegionServiceImpl roomRegionService;

    private final RegionMapper regionMapper;

    private final SysImgMapper sysImgMapper;

    private final ImgTypeMapper imgTypeMapper;


    /**
     * 查询【请填写功能名称】
     */
    @Override
    public PositionVo queryById(String positionId){
        PositionVo vo = baseMapper.selectVoById(positionId);
        PositionCommunityBo pcBo = new PositionCommunityBo();
        // 社区房型
        pcBo.setPositionId(positionId);
        List<PositionCommunityVo> list = positionCommunityService.queryList(pcBo);
        List<CommunityVo> comList = new ArrayList();
        for (int i=0; i<list.size(); i++) {
            CommunityBo bo = new CommunityBo();
            bo.setCommunityId(list.get(i).getCommunityId());
            List<CommunityVo> listBo = communityService.queryList(bo); // 社区
            for(CommunityVo v: listBo){
                List<SysImgVo> sysimg = this.querySysImg(v.getCommunityId()); //房型图片
                v.setSysimg(sysimg);
            }
            comList.addAll(listBo);
        }
        vo.setCommunity(comList);
        // 社区图片
        List<SysImgVo> sysimg = this.querySysImg(positionId);
        vo.setSysimg(sysimg);
        return vo;
    }

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

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

    private LambdaQueryWrapper<Position> buildQueryWrapper(PositionBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Position> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getPositionId()), Position::getPositionId, bo.getPositionId());
        lqw.like(StringUtils.isNotBlank(bo.getPositionName()), Position::getPositionName, bo.getPositionName());
        lqw.eq(StringUtils.isNotBlank(bo.getPositionTitle()), Position::getPositionTitle, bo.getPositionTitle());
        lqw.eq(StringUtils.isNotBlank(bo.getPositionDesc()), Position::getPositionDesc, bo.getPositionDesc());
        return lqw;
    }

    /**
     * 新增【请填写功能名称】
     */
    @Override
    public Boolean insertByBo(PositionBoStr bo) {
        PositionBo addVo = new PositionBo();
        addVo.setPositionName(bo.getPositionName());
        addVo.setPositionTitle(bo.getPositionName());
        addVo.setPositionDesc(bo.getPositionDesc());
        Position add = MapstructUtils.convert(addVo, Position.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setPositionId(add.getPositionId());

            // 关联社区信息
            bo.getCommunity().forEach(community -> {
                PositionCommunityBo vo = new PositionCommunityBo();
                vo.setPositionId(add.getPositionId());
                vo.setCommunityId(community.getCommunityId());
                positionCommunityService.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.getPositionId());
                        types.setTypeC("4");           // 图片类型
                        boolean typeImg = imgTypeService.insertByBo(types);
                        if(typeImg){
                            SysImgBo img = new SysImgBo();
                            img.setImgType("4"); // 图片类型
                            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(PositionBoStr bo) {
        PositionBo positionBo = new PositionBo();
        BeanUtils.copyProperties(bo, positionBo);
        Position update = MapstructUtils.convert(positionBo, Position.class);
        validEntityBeforeSave(update);
        boolean status = baseMapper.updateById(update) > 0;
        if(status){
            // 小区更新
            positionCommunityService.batchDelete(List.of(bo.getPositionId()));
            for (int i=0; i<bo.getCommunity().size(); i++){
                PositionCommunityBo pcBo = new PositionCommunityBo();
                pcBo.setPositionId(bo.getPositionId());
                pcBo.setCommunityId(String.valueOf(bo.getCommunity().get(i).getCommunityId()));
                positionCommunityService.insertByBo(pcBo);
            }

//            imgTypeService.batchDelete(List.of(bo.getPositionId()));
            imgTypeMapper.batchDeleteByTypeC(List.of(bo.getPositionId()));
            //图片更新
            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));
            sysImgMapper.batchDeleteByType(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.getPositionId());
                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(Position entity){
        //TODO 做一些数据校验,如唯一约束
    }

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

    @Override
    public List<PositionVo> selectAll() {
        return baseMapper.selectAll();
    }

    @Override
    public PositionVo selectByPositionId(String positionId) {
        PositionVo vo = queryById(positionId);
        if(vo != null){
            if(vo.getCommunity() != null && vo.getCommunity().size() > 0){
                List<CommunityVo> commList = vo.getCommunity().stream().filter(item -> item.getIsMaster() != null && "1".equals(item.getIsMaster())).toList();
                commList.forEach(cv ->{
                    CommunityVo cvo = communityService.queryById(cv.getCommunityId());
                    if(cvo != null){
                        cv.setRoom(cvo.getRoom());
                    }
                });
                vo.setCommunity(commList);
            }
        }
        return vo;
    }

    @Override
    public PositionDetailVo selectByRoomDetail(String positionId, String commodityId, String roomId) {
        PositionVo vo = queryById(positionId);
        PositionDetailVo detailVo = new PositionDetailVo();
        BeanUtils.copyProperties(vo, detailVo);

        if(vo != null){
            if(vo.getCommunity() != null && vo.getCommunity().size() > 0){
                CommunityVo cvo = communityService.queryById(commodityId);
                CommunityDetailVo commDetailVo = new CommunityDetailVo();
                BeanUtils.copyProperties(cvo, commDetailVo);
                if(cvo != null){
                    RoomVo rvo = roomService.queryById(roomId);
                    RoomDetailVo roomDetailVo = new RoomDetailVo();
                    BeanUtils.copyProperties(rvo, roomDetailVo);
                    commDetailVo.setRoom(roomDetailVo);
                }
                detailVo.setCommunity(commDetailVo);
            }
        }
        return detailVo;
    }

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



    @Override
    public List<PositionList> ficationBtn(){
        List<PositionList> btnList = new ArrayList<>();
        List<PositionVo> list =baseMapper.selectAll();
        if(list != null && list.size() > 0){
            for (PositionVo positionVo : list) {

                List<RegionList> regionList = new ArrayList<>();
                PositionList btn = new PositionList();
                btn.setPositionId(positionVo.getPositionId());
                btn.setPositionName(positionVo.getPositionName());

                List<CommunityVo> comList = communityMapper.selectByPositionId(positionVo.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){

                        btn.setCommunityId(cv.getCommunityId());
                        // 房型
                        CommunityRoomBo crBo = new CommunityRoomBo();
                        crBo.setCommunityId(cv.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){

                                btn.setRoomId(r.getRoomId());
                                // 区域
                                RoomRegionBo rrBo = new RoomRegionBo();
                                rrBo.setRoomId(r.getRoomId());
                                List<RoomRegionVo> rrList = roomRegionService.queryList(rrBo);
                                List<String> roomIds = rrList.stream().map(RoomRegionVo:: getRegionId).collect(Collectors.toList());
                                if(roomIds.size() > 0){
                                    List<RegionVo> rgList = regionMapper.selectListByRegionBoByRoomId(roomIds);

                                    if(rgList != null &&rgList.size() > 0){
                                        for(RegionVo rg: rgList){
                                            RegionList item = new RegionList();
                                            item.setRegionId(rg.getRegionId());
                                            item.setRegionName(rg.getRegionName());
                                            item.setPositionId(positionVo.getPositionId());
                                            regionList.add(item);
                                        }
                                        btn.setRegionList(regionList);
                                    }
//                                    r.setRegion(rgList);
                                }
                            }
                            //cv.setRoom(rList2);
                        }
                    }
                    //positionVo.setCommunity(commList);

                }
                btnList.add(btn);
            }
        }
        return btnList;
    }

}
