package com.multictrl.modules.business.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.multictrl.common.constant.BusinessConstant;
import com.multictrl.common.page.PageData;
import com.multictrl.common.service.impl.CrudServiceImpl;
import com.multictrl.common.utils.ConvertUtils;
import com.multictrl.common.utils.DateUtils;
import com.multictrl.modules.business.dao.MaintenanceDao;
import com.multictrl.modules.business.dao.MaintenanceImgDao;
import com.multictrl.modules.business.dto.MaintenanceDTO;
import com.multictrl.modules.business.entity.MaintenanceEntity;
import com.multictrl.modules.business.entity.MaintenanceImgEntity;
import com.multictrl.modules.business.service.DockService;
import com.multictrl.modules.business.service.MaintenanceService;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 设备维护信息
 *
 * @author Sdy
 * @since 1.0.0 2026-06-12
 */
@Service
@RequiredArgsConstructor
public class MaintenanceServiceImpl extends CrudServiceImpl<MaintenanceDao, MaintenanceEntity, MaintenanceDTO> implements MaintenanceService {
    private final MaintenanceImgDao maintenanceImgDao;
    private final DockService dockService;

    @Override
    public QueryWrapper<MaintenanceEntity> getWrapper(Map<String, Object> params) {
        String id = (String) params.get("id");
        String dockSn = (String) params.get("dockSn");
        String date = (String) params.get("date");

        QueryWrapper<MaintenanceEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(id), "m.id", id);
        wrapper.eq(StrUtil.isNotBlank(dockSn), "m.dock_sn", dockSn);
        if (StrUtil.isNotBlank(date)) {
            wrapper.between("m.operation_date", DateUtils.parse(date + " 00:00:00", DateUtils.DATE_TIME_PATTERN)
                    , DateUtils.parse(date + " 23:59:59", DateUtils.DATE_TIME_PATTERN));
        }
        wrapper.orderByDesc("m.update_date");

        return wrapper;
    }

    @Override
    public PageData<MaintenanceDTO> pageList(Map<String, Object> params) {
        IPage<MaintenanceEntity> iPage = baseDao.pageList(getPage(params, null, false), getWrapper(params));
        List<MaintenanceDTO> list = ConvertUtils.sourceToTarget(iPage.getRecords(), MaintenanceDTO.class);
        if (CollUtil.isNotEmpty(list)) {
            for (MaintenanceDTO dto : list) {
                List<MaintenanceImgEntity> entityList = maintenanceImgDao.selectList(new QueryWrapper<MaintenanceImgEntity>()
                        .eq("maintenance_id", dto.getId()));
                if (CollUtil.isNotEmpty(entityList)) {
                    List<String> imageList = entityList.stream().map(v -> BusinessConstant.IMAGE_PATH + v.getImageUrl()).toList();
                    dto.setImageUrls(imageList);
                }
            }
        }
        return new PageData<>(list, iPage.getTotal());
    }

    @Override
    public MaintenanceDTO getInfo(Long id) {
        MaintenanceEntity maintenanceEntity = selectById(id);
        MaintenanceDTO dto = ConvertUtils.sourceToTarget(maintenanceEntity, MaintenanceDTO.class);
        List<MaintenanceImgEntity> imgEntities = maintenanceImgDao.selectList(new QueryWrapper<MaintenanceImgEntity>()
                .eq("maintenance_id", id));
        List<String> imgList = Optional.ofNullable(imgEntities).orElse(Collections.emptyList())
                .stream().map(MaintenanceImgEntity::getImageUrl).collect(Collectors.toList());
        dto.setImageUrls(imgList);
        return dto;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addMaintenance(MaintenanceDTO dto) {
        MaintenanceEntity maintenanceEntity = ConvertUtils.sourceToTarget(dto, MaintenanceEntity.class);
        insert(maintenanceEntity);

        //增加图片
        addImages(maintenanceEntity.getId(), dto.getImageUrls());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateMaintenance(MaintenanceDTO dto) {
        MaintenanceEntity maintenanceEntity = ConvertUtils.sourceToTarget(dto, MaintenanceEntity.class);
        updateById(maintenanceEntity);

        //删除图片
        maintenanceImgDao.delete(new QueryWrapper<MaintenanceImgEntity>().eq("maintenance_id", maintenanceEntity.getId()));
        //新增照片
        addImages(maintenanceEntity.getId(), dto.getImageUrls());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteMaintenance(Long[] ids) {
        delete(ids);

        //删除图片
        maintenanceImgDao.delete(new QueryWrapper<MaintenanceImgEntity>().in("maintenance_id", Arrays.asList(ids)));
    }

    //新增照片
    private void addImages(Long maintenanceId, List<String> imageUrls) {
        if (CollUtil.isNotEmpty(imageUrls)) {
            for (String imageUrl : imageUrls) {
                MaintenanceImgEntity imgEntity = new MaintenanceImgEntity();
                imgEntity.setMaintenanceId(maintenanceId);
                imgEntity.setImageUrl(imageUrl);
                maintenanceImgDao.insert(imgEntity);
            }
        }
    }
}