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

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.module.erp.controller.admin.mold.vo.MoldRespVO;
import cn.iocoder.yudao.module.erp.controller.admin.product.vo.product.ErpProductRespVO;
import cn.iocoder.yudao.module.common.dal.dataobject.mold.MoldBrandDO;
import cn.iocoder.yudao.module.common.dal.dataobject.mold.MoldDO;
import cn.iocoder.yudao.module.common.dal.mysql.mold.MoldMapper;
import cn.iocoder.yudao.module.iot.controller.admin.device.vo.DeviceRespVO;
import cn.iocoder.yudao.module.iot.controller.admin.device.vo.DeviceSaveReqVO;
import cn.iocoder.yudao.module.iot.service.device.DeviceService;
import cn.iocoder.yudao.module.mes.dal.dataobject.devicetype.DeviceTypeDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.product.ErpProductDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.product.ErpProductUnitDO;
import cn.iocoder.yudao.module.common.dal.mysql.mold.MoldMapper;
import cn.iocoder.yudao.module.mes.dal.mysql.devicetype.DeviceTypeMapper;
import cn.iocoder.yudao.module.common.dal.mysql.mold.MoldMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.product.ErpProductMapper;
import cn.iocoder.yudao.module.erp.service.product.ErpProductUnitService;
import cn.iocoder.yudao.module.mes.controller.admin.ticketmanagement.enums.PlanTypeEnum;
import cn.iocoder.yudao.module.mes.dal.dataobject.criticalcomponent.CriticalComponentDO;
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.mes.dal.dataobject.ticketresults.TicketResultsDO;
import cn.iocoder.yudao.module.mes.dal.mysql.criticalcomponent.CriticalComponentMapper;
import cn.iocoder.yudao.module.mes.dal.mysql.dvrepair.DvRepairLineMapper;
import cn.iocoder.yudao.module.mes.dal.mysql.dvrepair.DvRepairMapper;
import cn.iocoder.yudao.module.mes.dal.mysql.ticketresults.TicketResultsMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
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 java.util.*;
import java.util.stream.Collectors;

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

import cn.iocoder.yudao.module.mes.dal.mysql.deviceledger.DeviceLedgerMapper;

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

/**
 * 设备类型 Service 实现类
 *
 * @author 内蒙必硕
 */
@Service
@Validated
public class DeviceLedgerServiceImpl implements DeviceLedgerService {

    @Resource
    private DeviceLedgerMapper deviceLedgerMapper;

    @Resource
    @Lazy
    private TicketResultsMapper ticketResultsMapper;

    @Resource
    private DvRepairLineMapper dvRepairLineMapper;

    @Resource
    private DvRepairMapper dvRepairMapperRepair;

    @Resource
    private CriticalComponentMapper criticalComponentMapper;

    @Resource
    private ErpProductMapper productMapper;

    @Resource
    private MoldMapper moldMapper;

    @Resource
    private ErpProductUnitService productUnitService;

    @Resource
    private DeviceTypeMapper deviceTypeMapper;

    @Resource
    private DeviceService deviceService;

    @Override
    public Long createDeviceLedger(DeviceLedgerSaveReqVO createReqVO) {

        //验证是否唯一编码
        validateCodeOnly(createReqVO.getDeviceCode());
        // 插入
        DeviceLedgerDO deviceLedger = BeanUtils.toBean(createReqVO, DeviceLedgerDO.class);

        // 创建台账
        deviceLedgerMapper.insert(deviceLedger);

        // 数采设备设置
//        if (deviceLedger.getWorkshop() != null) {
//            DeviceRespVO deviceRespVO = deviceService.getDevice(Long.valueOf(createReqVO.getWorkshop()));
//            deviceRespVO.setOrg(Long.valueOf(deviceLedger.getWorkshop()));
//            deviceService.updateDevice(BeanUtils.toBean(deviceRespVO, DeviceSaveReqVO.class));
//        }
        // 返回
        return deviceLedger.getId();
    }

    private void validateCodeOnly( String code) {
        if (deviceLedgerMapper.exists(Wrappers.<DeviceLedgerDO>lambdaQuery()
                .eq(DeviceLedgerDO::getDeviceCode, code))) {
            throw exception(DEVICE_LEDGER_EXISTS);
        }
    }
    @Override
    public void updateDeviceLedger(DeviceLedgerSaveReqVO updateReqVO) {
        // 校验存在
        validateDeviceLedgerExists(updateReqVO.getId());

        //编码重复判断
        Long count = deviceLedgerMapper.selectCount(new LambdaQueryWrapper<DeviceLedgerDO>()
                .eq(DeviceLedgerDO::getDeviceCode, updateReqVO.getDeviceCode())
                .ne(DeviceLedgerDO::getId, updateReqVO.getId())

        );

        if (count > 0) {
            throw exception(DEVICE_LEDGER_EXISTS);
        }
        // 更新
        DeviceLedgerDO updateObj = BeanUtils.toBean(updateReqVO, DeviceLedgerDO.class);
        deviceLedgerMapper.updateById(updateObj);
    }

    @Override
    public void deleteDeviceLedger(List<Long> idList ) {

        for (Long id : idList) {
            // 校验存在
            validateDeviceLedgerExists(id);
        }

        // 删除
        deviceLedgerMapper.deleteByIds(idList);
    }

    private void validateDeviceLedgerExists(Long id) {
        if (deviceLedgerMapper.selectById(id) == null) {
            throw exception(DEVICE_LEDGER_NOT_EXISTS);
        }
    }

    @Override
    public DeviceLedgerDO getDeviceLedger(Long id) {

        DeviceLedgerDO deviceLedgerDO = deviceLedgerMapper.selectById(id);


        Map<String,List<DvRepairLineDO>> dvRepairDOMap=new HashMap<>();

        //TODO 待修改迁移
//        //点检列表
//        List<TicketResultsDO> inspectionList = ticketResultsMapper.findByDeviceIdAndPlanType(id, PlanTypeEnum.INSPECTION.getCode(),null,null,null);
//        if(CollectionUtils.isNotEmpty(inspectionList)){
//            deviceLedgerDO.setInspectionList(inspectionList);
//        }

//        //保养列表
//        List<TicketResultsDO> maintainList = ticketResultsMapper.findByDeviceIdAndPlanType(id, PlanTypeEnum.MAINTENANCE.getCode(),null,null,null);
//        if(CollectionUtils.isNotEmpty(maintainList)){
//            deviceLedgerDO.setMaintainList(maintainList);
//        }
//
//        //维修列表
//        List<DvRepairDO> dvRepairDOS = dvRepairMapperRepair.selectList(
//                Wrappers.<DvRepairDO>lambdaQuery()
//                        .eq(DvRepairDO::getDeviceId, id));
//
//        for (DvRepairDO dvRepairDO : dvRepairDOS) {
//            List<DvRepairLineDO> dvRepairLineDOS = dvRepairLineMapper.selectList(Wrappers.<DvRepairLineDO>lambdaQuery()
//                    .eq(DvRepairLineDO::getRepairId, dvRepairDO.getId())
//                    .orderByDesc(DvRepairLineDO::getCreateTime));
//            if (!dvRepairLineDOS.isEmpty()) {
//                dvRepairDOMap.put(dvRepairDO.getRepairName(), dvRepairLineDOS);
//            }
//        }
//
//        if(CollectionUtils.isNotEmpty(dvRepairDOMap)){
//            deviceLedgerDO.setRepairList(dvRepairDOMap);
//        }


        //关键件列表
        List<CriticalComponentDO> componentList = new ArrayList<>();
        if (deviceLedgerDO != null && StringUtils.isNotBlank(deviceLedgerDO.getComponentId())) {
            // 将逗号分隔的字符串转换为Long类型的List
            List<Long> idList = Arrays.stream(deviceLedgerDO.getComponentId().split(","))
                    .map(String::trim) // 去除可能存在的空格
                    .map(Long::valueOf)
                    .collect(Collectors.toList());
            for (Long componentId : idList) {
                CriticalComponentDO criticalComponentDO = criticalComponentMapper.selectById(componentId);
                if(criticalComponentDO!=null){
                    componentList.add(criticalComponentDO);
                }
            }
            deviceLedgerDO.setComponentList(componentList);
        }

        //模具列表
        List<MoldDO> moldList = new ArrayList<>();
        if (deviceLedgerDO != null && StringUtils.isNotBlank(deviceLedgerDO.getMoldId())) {
            // 将逗号分隔的字符串转换为Long类型的List
            List<Long> idList = Arrays.stream(deviceLedgerDO.getMoldId().split(","))
                    .map(String::trim) // 去除可能存在的空格
                    .map(Long::valueOf)
                    .collect(Collectors.toList());
            for (Long moldId : idList) {
                MoldDO moldDO = moldMapper.selectById(moldId);
                if(moldDO!=null){
                    moldList.add(moldDO);
                }
            }
            deviceLedgerDO.setMoldList(moldList);
        }

        //备件列表
        List<ErpProductDO> beijianList = new ArrayList<>();
        if (deviceLedgerDO != null && StringUtils.isNotBlank(deviceLedgerDO.getBeijianId())) {
            // 将逗号分隔的字符串转换为Long类型的List
            List<Long> idList = Arrays.stream(deviceLedgerDO.getBeijianId().split(","))
                    .map(String::trim) // 去除可能存在的空格
                    .map(Long::valueOf)
                    .collect(Collectors.toList());
            for (Long beijianId : idList) {
                ErpProductDO beijianDO = productMapper.selectById(beijianId);
                if(beijianDO!=null){
                    beijianList.add(beijianDO);
                }
            }
            deviceLedgerDO.setBeijianList(beijianList);
        }
        return deviceLedgerDO;
    }

    @Override
    public PageResult<DeviceLedgerDO> getDeviceLedgerPage(DeviceLedgerPageReqVO pageReqVO) {
        PageResult<DeviceLedgerDO> deviceLedgerDOPageResult = deviceLedgerMapper.selectPage(pageReqVO);
        for (DeviceLedgerDO deviceLedgerDO : deviceLedgerDOPageResult.getList()) {
            if (deviceLedgerDO.getDeviceType()!=null){
                DeviceTypeDO deviceTypeDO = deviceTypeMapper.selectById(deviceLedgerDO.getDeviceType());
                deviceLedgerDO.setTypeName(deviceTypeDO.getName());
            }
        }
        return deviceLedgerDOPageResult;
    }

    @Override
    public List<DeviceLedgerDO> getDeviceLedgerList() {
        return deviceLedgerMapper.selectList();
    }

    @Override
    public List<DeviceLedgerRespVO> getDeviceLedgerVOList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Collections.emptyList();
        }
        List<DeviceLedgerDO> list = deviceLedgerMapper.selectBatchIds(ids);
        return BeanUtils.toBean(list, DeviceLedgerRespVO.class);
    }

    @Override
    public List<ErpProductVO> exportSpareBased(Long id) {
        DeviceLedgerDO deviceLedgerDO = deviceLedgerMapper.selectById(id);
        if (deviceLedgerDO == null){
            throw exception(DEVICE_LEDGER_EXISTS);
        }

        List<ErpProductDO> beijianList = new ArrayList<>();
        if (StringUtils.isNotBlank(deviceLedgerDO.getBeijianId())) {
            // 将逗号分隔的字符串转换为Long类型的List
            List<Long> idList = Arrays.stream(deviceLedgerDO.getBeijianId().split(","))
                    .map(String::trim) // 去除可能存在的空格
                    .map(Long::valueOf)
                    .collect(Collectors.toList());
            for (Long beijianId : idList) {
                ErpProductDO beijianDO = productMapper.selectById(beijianId);
                if(beijianDO!=null){
                    beijianList.add(beijianDO);
                }
            }
        }

        Map<Long, ErpProductUnitDO> unitMap = productUnitService.getProductUnitMap(
                convertSet(beijianList, ErpProductDO::getUnitId));

        List<ErpProductVO> erpProductVOList = BeanUtils.toBean(beijianList, ErpProductVO.class, product -> {
            MapUtils.findAndThen(unitMap, product.getUnitId(),
                    unit -> product.setUnitName(unit.getName()));
        });


        return erpProductVOList;
    }


    @Override
    public List<MoldVO> exportMold(Long id) {
        DeviceLedgerDO deviceLedgerDO = deviceLedgerMapper.selectById(id);
        if (deviceLedgerDO == null){
            throw exception(DEVICE_LEDGER_EXISTS);
        }

        //模具列表
        List<MoldDO> moldList = new ArrayList<>();
        if (StringUtils.isNotBlank(deviceLedgerDO.getMoldId())) {
            // 将逗号分隔的字符串转换为Long类型的List
            List<Long> idList = Arrays.stream(deviceLedgerDO.getMoldId().split(","))
                    .map(String::trim) // 去除可能存在的空格
                    .map(Long::valueOf)
                    .collect(Collectors.toList());
            for (Long moldId : idList) {
                MoldDO moldDO = moldMapper.selectById(moldId);
                if(moldDO!=null){
                    moldList.add(moldDO);
                }
            }
        }

        return BeanUtils.toBean(moldList, MoldVO.class);
    }



}