package com.srs.dormitory.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.srs.common.core.domain.AjaxResult;
import com.srs.dormitory.domain.DmsCampus;
import com.srs.dormitory.domain.DmsDormitoryBuilding;
import com.srs.dormitory.domain.DmsDormitoryPark;
import com.srs.dormitory.domain.Dto.CampusDto;
import com.srs.dormitory.domain.Vo.CampusCascadingList;
import com.srs.dormitory.domain.Vo.CampusVo;
import com.srs.dormitory.domain.Vo.ParkCascadingList;
import com.srs.dormitory.mapper.DmsCampusMapper;
import com.srs.dormitory.service.IDmsCampusService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.srs.dormitory.service.IDmsDormitoryBuildingService;
import com.srs.dormitory.service.IDmsDormitoryParkService;
import com.srs.dormitory.utils.BeanCopyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

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

/**
 * <p>
 * 校区表 服务实现类
 * </p>
 *
 * @author 猪油骨
 * @since 2023-07-14
 */
@Service
public class IDmsCampusServiceImpl extends ServiceImpl<DmsCampusMapper, DmsCampus> implements IDmsCampusService {

    @Autowired
    private IDmsDormitoryParkService iDmsDormitoryParkService;
    @Autowired
    private IDmsDormitoryBuildingService iDmsDormitoryBuildingService;


    @Override
    @Transactional
    public AjaxResult addCampus(CampusDto dto, String username) {
        DmsCampus dmsCampus = new DmsCampus();
        dmsCampus.setName(dto.getName());
        dmsCampus.setCreateBy(username);
        if (StringUtils.isBlank(dmsCampus.getName())) {
            return AjaxResult.error("名称不能为空");
        }
        // 校验 createBy 是否为空或空白字符串
        if (StringUtils.isBlank(dmsCampus.getCreateBy())) {
            return AjaxResult.error("创建者不能为空");
        }
        DmsCampus campus = baseMapper.selectOne(new QueryWrapper<DmsCampus>().lambda().eq(DmsCampus::getName, dmsCampus.getName()));
        Assert.isNull(campus, "添加失败，校区已存在");
        int insert = baseMapper.insert(dmsCampus);

        DmsDormitoryPark park = new DmsDormitoryPark();
        park.setCampusId(dmsCampus.getId());
        park.setName("default");
        iDmsDormitoryParkService.save(park);
        return insert == 1 ? AjaxResult.success("添加成功") : AjaxResult.error("添加失败");
    }

    @Override
    @Transactional
    public AjaxResult updateCampus(CampusDto campusDto, String username) {
        DmsCampus dmsCampus = BeanCopyUtils.copyBean(campusDto, DmsCampus.class);
        dmsCampus.setUpdateBy(username);
        if (StringUtils.isBlank(dmsCampus.getName())) {
            return AjaxResult.error("名称不能为空");
        }
        int i = baseMapper.updateById(dmsCampus);
        return i == 1 ? AjaxResult.success("修改成功") : AjaxResult.error("修改失败");
    }

    @Override
    public List<CampusVo> campusList(String name) {
        return baseMapper.selectCapusList(name);
    }

    @Override
    @Transactional
    public AjaxResult deleteCampusById(Long id) {
        DmsDormitoryPark one = iDmsDormitoryParkService
                .lambdaQuery()
                .eq(DmsDormitoryPark::getCampusId, id).one();
        if (one != null) return AjaxResult.error();
        int i = baseMapper.deleteById(id);
        return i == 0 ? AjaxResult.error("删除失败") : AjaxResult.success("删除成功");
    }


    @Override
    @Transactional
    public AjaxResult deleteCampus(List<Long> ids) {
        List<DmsDormitoryPark> list = iDmsDormitoryParkService
                .lambdaQuery()
                .in(DmsDormitoryPark::getCampusId, ids)
                .list();
        if(list.size() != 0){
            return AjaxResult.error("请先删除对应的园区");
        }
        int i = baseMapper.deleteBatchIds(ids);
        return i == 0 ? AjaxResult.error("删除失败") : AjaxResult.success("删除成功");
    }


    @Override
    public AjaxResult getCampus(Long id) {
        DmsCampus campus = baseMapper.selectById(id);
        List<DmsDormitoryPark> parks = iDmsDormitoryParkService.lambdaQuery()
                .eq(DmsDormitoryPark::getCampusId, id)
                .list();
        Map<String, Object> map = BeanUtil.beanToMap(campus);
        map.put("children", parks);
        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult cascadingList() {
        List<DmsCampus> campusList = list();
        List<DmsDormitoryPark> dormitoryParkList = iDmsDormitoryParkService.list();
        List<DmsDormitoryBuilding> buildingList = iDmsDormitoryBuildingService.list();
        Map<Long, List<DmsDormitoryBuilding>> groupByParkId = buildingList.stream().collect(
                Collectors.groupingBy(DmsDormitoryBuilding::getParkId)
        );
        List<ParkCascadingList> parkCascadingLists = new ArrayList<>();
        dormitoryParkList.forEach(park -> {
            ParkCascadingList parkCascadingList = new ParkCascadingList();
            BeanUtil.copyProperties(park, parkCascadingList);
            parkCascadingList.setChildren(groupByParkId.get(park.getId()));
            parkCascadingLists.add(parkCascadingList);
        });
        Map<Long, List<ParkCascadingList>> groupByCampusId = parkCascadingLists.stream().collect(
                Collectors.groupingBy(ParkCascadingList::getCampusId)
        );
        List<CampusCascadingList> result = new ArrayList<>();
        campusList.forEach(campus -> {
            CampusCascadingList campusCascadingList = new CampusCascadingList();
            BeanUtil.copyProperties(campus, campusCascadingList);
            campusCascadingList.setChildren(groupByCampusId.get(campus.getId()));
            result.add(campusCascadingList);
        });
        return AjaxResult.success(result);
    }
}
