package com.zt.plat.module.qms.resource.device.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zt.plat.framework.common.pojo.CommonResult;
import com.zt.plat.module.qms.resource.device.controller.vo.DeviceMaintainItemPageReqVO;
import com.zt.plat.module.qms.resource.device.controller.vo.DeviceMaintainItemRespVO;
import com.zt.plat.module.qms.resource.device.controller.vo.DeviceMaintainItemSaveReqVO;
import com.zt.plat.module.qms.resource.device.dal.dataobject.DeviceConfigBusinessItemDO;
import com.zt.plat.module.qms.resource.device.dal.dataobject.DeviceMaintainDO;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

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

import com.zt.plat.module.qms.resource.device.dal.dataobject.DeviceMaintainItemDO;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.util.object.BeanUtils;

import com.zt.plat.module.qms.resource.device.dal.mapper.DeviceMaintainItemMapper;

import static com.zt.plat.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.zt.plat.framework.common.util.collection.CollectionUtils.convertList;
import static com.zt.plat.module.qms.enums.ErrorCodeConstants.DEVICE_CONFIG_BUSINESS_ITEM_NOT_EXISTS;
import static com.zt.plat.module.qms.enums.ErrorCodeConstants.DEVICE_MAINTAIN_ITEM_NOT_EXISTS;

/**
 * 设备-保养分项 Service 实现类
 *
 * @author 后台管理-1
 */
@Service
@Validated
public class DeviceMaintainItemServiceImpl implements DeviceMaintainItemService {

    @Resource private DeviceMaintainItemMapper deviceMaintainItemMapper;
    @Resource private DeviceConfigBusinessItemService deviceConfigBusinessItemService;;

    @Override
    public void updateBatch(List<DeviceMaintainItemDO> list) {
        deviceMaintainItemMapper.updateBatch(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<String> createItems(DeviceMaintainDO maintain, Long ruleId) {
        List<DeviceConfigBusinessItemDO> itemList = deviceConfigBusinessItemService.listByRuleId(ruleId);  //配置的所有明细项
        List<Long> itemIdList = itemList.stream().map(DeviceConfigBusinessItemDO::getId).toList();
        if(itemIdList.isEmpty())
            return CommonResult.error(DEVICE_CONFIG_BUSINESS_ITEM_NOT_EXISTS.getCode(), "没有配置检查项，请联系管理员处理！");
        //查询各明细项的最新数据
//        List<DeviceBusMaintainItem> lastDataList = queryLastestData(itemIdList, maintain.getDeviceId());

        //循环检查当前维护
        List<DeviceMaintainItemDO> insertList = new ArrayList<>();
        for(DeviceConfigBusinessItemDO library : itemList){
//            if(!checkItemNeeded(maintain, library, lastDataList))
//                continue;
            DeviceMaintainItemDO item = new DeviceMaintainItemDO();
            item.setParentId(maintain.getId());
            item.setFrequencyTimeStart(maintain.getFrequencyTimeStart());
            item.setFrequencyTimeEnd(maintain.getFrequencyTimeEnd());
            item.setCheckItemId(library.getId());
            item.setItemKey(library.getItemKey());
            item.setItemName(library.getItemName());
            item.setFrequencyType(library.getFrequencyType());
            item.setFrequency(library.getFrequency());
            item.setStandard(library.getStandard());
            item.setItemMethod(library.getItemMethod());
            item.setFrequencyRemark(library.getFrequencyRemark());
            item.setSortNo(library.getOrderNo());
            insertList.add(item);
        }
        if(!insertList.isEmpty())
            deviceMaintainItemMapper.insertBatch(insertList);
        return CommonResult.success("");
    }

    @Override
    public List<DeviceMaintainItemDO> getListByParId(Long maintainId) {
        LambdaQueryWrapper<DeviceMaintainItemDO> query = new LambdaQueryWrapper<>();
        query.eq(DeviceMaintainItemDO::getParentId, maintainId);
        query.orderByAsc(DeviceMaintainItemDO::getSortNo);
        return deviceMaintainItemMapper.selectList(query);
    }

    @Override
    public DeviceMaintainItemRespVO createDeviceMaintainItem(DeviceMaintainItemSaveReqVO createReqVO) {
        // 插入
        DeviceMaintainItemDO deviceMaintainItem = BeanUtils.toBean(createReqVO, DeviceMaintainItemDO.class);
        deviceMaintainItemMapper.insert(deviceMaintainItem);
        // 返回
        return BeanUtils.toBean(deviceMaintainItem, DeviceMaintainItemRespVO.class);
    }

    @Override
    public void updateDeviceMaintainItem(DeviceMaintainItemSaveReqVO updateReqVO) {
        // 校验存在
        validateDeviceMaintainItemExists(updateReqVO.getId());
        // 更新
        DeviceMaintainItemDO updateObj = BeanUtils.toBean(updateReqVO, DeviceMaintainItemDO.class);
        deviceMaintainItemMapper.updateById(updateObj);
    }

    @Override
    public void deleteDeviceMaintainItem(Long id) {
        // 校验存在
        validateDeviceMaintainItemExists(id);
        // 删除
        deviceMaintainItemMapper.deleteById(id);
    }

    @Override
        public void deleteDeviceMaintainItemListByIds(List<Long> ids) {
        // 校验存在
        validateDeviceMaintainItemExists(ids);
        // 删除
        deviceMaintainItemMapper.deleteByIds(ids);
        }

    private void validateDeviceMaintainItemExists(List<Long> ids) {
        List<DeviceMaintainItemDO> list = deviceMaintainItemMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(DEVICE_MAINTAIN_ITEM_NOT_EXISTS);
        }
    }

    private void validateDeviceMaintainItemExists(Long id) {
        if (deviceMaintainItemMapper.selectById(id) == null) {
            throw exception(DEVICE_MAINTAIN_ITEM_NOT_EXISTS);
        }
    }

    @Override
    public DeviceMaintainItemDO getDeviceMaintainItem(Long id) {
        return deviceMaintainItemMapper.selectById(id);
    }

    @Override
    public PageResult<DeviceMaintainItemDO> getDeviceMaintainItemPage(DeviceMaintainItemPageReqVO pageReqVO) {
        return deviceMaintainItemMapper.selectPage(pageReqVO);
    }

}