package cn.iocoder.yudao.module.mes.service.ticketmanagement;

import cn.iocoder.yudao.module.mes.controller.admin.dashboard.vo.dashboard.EventStatisticsVO;
import cn.iocoder.yudao.module.mes.controller.admin.ticketmanagement.enums.JobStatusEnum;
import cn.iocoder.yudao.module.mes.controller.admin.ticketmanagement.enums.PlanTypeEnum;
import cn.iocoder.yudao.module.mes.dal.dataobject.deviceledger.DeviceLedgerDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.dvrepair.DvRepairDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.dvrepair.DvRepairLineDO;
import cn.iocoder.yudao.module.common.dal.dataobject.moldrepair.MoldRepairDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.ticketresults.TicketResultsDO;
import cn.iocoder.yudao.module.mes.dal.mysql.deviceledger.DeviceLedgerMapper;
import cn.iocoder.yudao.module.mes.dal.mysql.ticketresults.TicketResultsMapper;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

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

import cn.iocoder.yudao.module.mes.controller.admin.ticketmanagement.vo.*;
import cn.iocoder.yudao.module.mes.dal.dataobject.ticketmanagement.TicketManagementDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.mes.dal.mysql.ticketmanagement.TicketManagementMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.mes.enums.ErrorCodeConstants.*;

/**
 * 项目方案关联 Service 实现类
 *
 * @author 内蒙必硕
 */
@Service
@Validated
public class TicketManagementServiceImpl implements TicketManagementService {

    @Resource
    private TicketManagementMapper ticketManagementMapper;
    @Resource
    @Lazy
    private DeviceLedgerMapper deviceLedgerMapper;
    @Resource
    @Lazy
    private TicketResultsMapper ticketResultsMapper;

    @Override
    public Long createTicketManagement(TicketManagementSaveReqVO createReqVO) {
        // 插入
        TicketManagementDO ticketManagement = BeanUtils.toBean(createReqVO, TicketManagementDO.class);
        ticketManagementMapper.insert(ticketManagement);
        // 返回
        return ticketManagement.getId();
    }

    @Override
    public void updateTicketManagement(TicketManagementSaveReqVO updateReqVO) {
        // 校验存在
        validateTicketManagementExists(updateReqVO.getId());
        // 更新
        TicketManagementDO updateObj = BeanUtils.toBean(updateReqVO, TicketManagementDO.class);
        ticketManagementMapper.updateById(updateObj);
    }

    @Override
    public void deleteTicketManagement(Long id) {
        // 校验存在
        validateTicketManagementExists(id);
        // 删除
        ticketManagementMapper.deleteById(id);
    }

    private void validateTicketManagementExists(Long id) {
        if (ticketManagementMapper.selectById(id) == null) {
            throw exception(TICKET_MANAGEMENT_NOT_EXISTS);
        }
    }

    @Override
    public TicketManagementDO getTicketManagement(Long id) {
        return ticketManagementMapper.selectById(id);
    }

    @Override
    public PageResult<TicketManagementDO> getTicketManagementPage(TicketManagementPageReqVO pageReqVO) {
        return ticketManagementMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchUpdateJobStatus(TicketManagementBatchUpdateReqVO reqVO) {
        // 1. 解析ID列表
        List<Long> idList = parseIds(reqVO.getIds());
        if (idList.isEmpty()) {
            throw exception(TICKET_MANAGEMENT_NOT_EXISTS);
        }

        // 2. 批量更新
        ticketManagementMapper.batchUpdateJobStatus(idList, reqVO.getJobStatus(),reqVO.getCancelReason());
    }

    @Override
    public  List<TicketResultsDO> getInspectionByDeviceId(Long id,String startTime,String endTime,String ids) {
        DeviceLedgerDO deviceLedgerDO = deviceLedgerMapper.selectById(id);
        //点检列表
        List<TicketResultsDO> inspectionList = ticketResultsMapper.findByDeviceIdAndPlanType(id, PlanTypeEnum.INSPECTION.getCode(),startTime,endTime,ids);
        if(CollectionUtils.isNotEmpty(inspectionList)){
            deviceLedgerDO.setInspectionList(inspectionList);
        }

        return  inspectionList;
    }

    @Override
    public List<TicketResultsDO> getMaintenanceByDeviceId(Long id,String startTime,String endTime,String ids) {
        DeviceLedgerDO deviceLedgerDO = deviceLedgerMapper.selectById(id);

        //保养列表
        List<TicketResultsDO> inspectionList = ticketResultsMapper.findByDeviceIdAndPlanType(id, PlanTypeEnum.MAINTENANCE.getCode(),startTime,endTime,ids);
        if(CollectionUtils.isNotEmpty(inspectionList)){
            deviceLedgerDO.setInspectionList(inspectionList);
        }

        return  inspectionList;
    }

    @Override
    public Long getBaoyangListCountByJobStatus() {
        return ticketManagementMapper.selectCount(Wrappers.<TicketManagementDO>lambdaQuery()
                .eq(TicketManagementDO::getJobStatus, 0)
                .eq(TicketManagementDO::getPlanType,2));
    }

    @Override
    public Long getDianjianListCountByJobStatus() {
        return ticketManagementMapper.selectCount(Wrappers.<TicketManagementDO>lambdaQuery()
                .eq(TicketManagementDO::getJobStatus, 0)
                .eq(TicketManagementDO::getPlanType,1));
    }

    @Override
    public List<TicketManagementDO> getListByJobStatus() {
        return ticketManagementMapper.selectList(Wrappers.<TicketManagementDO>lambdaQuery()
                .eq(TicketManagementDO::getJobStatus, 0));
    }

    @Override
    public void selectCountDeviceInspection(EventStatisticsVO eventStatisticsVO) {
        //点检
        int count = ticketManagementMapper.selectCount(Wrappers.<TicketManagementDO>lambdaQuery()
                .eq(TicketManagementDO::getPlanType, PlanTypeEnum.INSPECTION.getCode())
                .eq(TicketManagementDO::getJobStatus, JobStatusEnum.PENDING.getCode())).intValue();;

        eventStatisticsVO.setDeviceInspection(count);
    }

    @Override
    public void selectCountDeviceMaintenance(EventStatisticsVO eventStatisticsVO) {

        //保养
        int count = ticketManagementMapper.selectCount(Wrappers.<TicketManagementDO>lambdaQuery()
                .eq(TicketManagementDO::getPlanType, PlanTypeEnum.MAINTENANCE.getCode())
                .eq(TicketManagementDO::getJobStatus, JobStatusEnum.PENDING.getCode())).intValue();;

        eventStatisticsVO.setDeviceMaintenance(count);
    }

    @Override
    public List<TicketManagementDO> getList() {
        return ticketManagementMapper.selectList();
    }


    /**
     * 解析逗号分隔的ID字符串
     */
    private List<Long> parseIds(String ids) {
        if (StringUtils.isBlank(ids)) {
            return Collections.emptyList();
        }

        return Arrays.stream(ids.split(","))
                .map(String::trim)
                .filter(StringUtils::isNotBlank)
                .map(Long::valueOf)
                .distinct()
                .collect(Collectors.toList());
    }

}