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.RoomRegionMapper;
import org.dromara.system.service.*;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.Region;
import org.dromara.system.mapper.RegionMapper;

import java.util.*;

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

    private final RegionMapper baseMapper;

    private final IRegionFacilitiesService regionFacilitiesService;

    private final IImgTypeService imgTypeService;

    private final ISysImgService sysImgService;

    private final RoomRegionMapper roomRegionMapper;

    private final ISysDictDataService dictDataService;

    private final IFacilitiesService facilitiesService;

    private final ISysOssService sysOssService;

    /**
     * 查询【请填写功能名称】
     */
    @Override
    public RegionVo queryById(String regionId){
        RegionVo vo = baseMapper.selectVoById(regionId);
        //获取设施
        RegionFacilitiesBo faVo = new RegionFacilitiesBo();
        faVo.setRegionId(regionId);
        List<RegionFacilitiesVo> list = regionFacilitiesService.queryList(faVo);
        String[] a = new String[list.size()];
        List<FacilitiesVo> regList = new ArrayList();
        for (int i=0; i<list.size(); i++){
            FacilitiesBo vo1 = new FacilitiesBo();
            vo1.setFacilitiesId(list.get(i).getFacilitiesId());
            List<FacilitiesVo> listBo = facilitiesService.queryList(vo1);
            for(FacilitiesVo v: listBo){
                List<SysImgVo> sysimg = this.querySysImg(v.getFacilitiesId()); //设施图片
                v.setSysimg(sysimg);
            }
            regList.addAll(listBo);
        }
        vo.setRegionFacilities(regList);
        //获取图片
        List<SysImgVo> sysList = this.querySysImg(regionId);
        vo.setSysimg(sysList);
        return vo;
    }

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

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

    private LambdaQueryWrapper<Region> buildQueryWrapper(RegionBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Region> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getRegionId()), Region::getRegionId, bo.getRegionId());
        lqw.like(StringUtils.isNotBlank(bo.getRegionName()), Region::getRegionName, bo.getRegionName());
        lqw.eq(StringUtils.isNotBlank(bo.getRegionTitle()), Region::getRegionTitle, bo.getRegionTitle());
        lqw.eq(StringUtils.isNotBlank(bo.getRegionDesc()), Region::getRegionDesc, bo.getRegionDesc());
        return lqw;
    }

    /**
     * 新增【请填写功能名称】
     */
    @Override
    public Boolean insertByBo(RegionBo bo) {
        Region add = MapstructUtils.convert(bo, Region.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setRegionId(add.getRegionId());

            //关联设施
            for (FacilitiesBo regionFacility : bo.getRegionFacilities()) {
                RegionFacilitiesBo rfBo = new RegionFacilitiesBo();
                rfBo.setRegionId(add.getRegionId());
                rfBo.setFacilitiesId(regionFacility.getFacilitiesId());
                regionFacilitiesService.insertByBo(rfBo);
            }

            // 图片
            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.getRegionId());
                    types.setTypeC("2");           // 图片类型
                    boolean typeImg = imgTypeService.insertByBo(types);
                    if(typeImg){
                        SysImgBo img = new SysImgBo();
                        img.setImgType("2"); // 图片类型
                        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(RegionBo bo) {
        Region update = MapstructUtils.convert(bo, Region.class);
        validEntityBeforeSave(update);
        boolean status = baseMapper.updateById(update) > 0;

        if(status){
            //更新设施
            regionFacilitiesService.batchDelete(List.of(bo.getRegionId()));
            for (FacilitiesBo regionFacility : bo.getRegionFacilities()) {
                RegionFacilitiesBo rfBo = new RegionFacilitiesBo();
                rfBo.setRegionId(bo.getRegionId());
                rfBo.setFacilitiesId(regionFacility.getFacilitiesId());
                regionFacilitiesService.insertByBo(rfBo);
            }

            imgTypeService.batchDelete(List.of(bo.getRegionId()));
            //图片更新
            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.getRegionId());
                types.setTypeC("2");           // 图片类型
                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("2"); // 图片类型
                    sysImgService.insertByBo(img);
                }
            }

        }
        return status;
    }

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

    /**
     * 批量删除【请填写功能名称】
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        boolean status = baseMapper.deleteBatchIds(ids) > 0;
        if(status){
            //删除数据字典
            for(String str: ids){
                SysDictDataVo vo = dictDataService.selectDictDataById(Long.valueOf(str));
                if(vo != null){
                    //Long[] longArray = ids.stream().map(Long::parseLong).toArray(Long[]::new);
                    //dictDataService.deleteDictDataByIds(longArray);
                    dictDataService.deleteDictDataByIds(new Long[]{Long.valueOf(str)});
                }
            }

            //删除关联关系
            roomRegionMapper.batchDeleteByRegionId(new ArrayList(ids));
            //删除图片
            this.deleteImg(ids);
        }
        return status;
    }

    @Override
    public List<RegionVo> selectByRoomId(String roomId) {
        return baseMapper.selectByRoomId(roomId);
    }

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