package com.zehong.system.service.impl;

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

import com.zehong.common.core.domain.AjaxResult;
import com.zehong.common.utils.DateUtils;
import com.zehong.common.utils.StringUtils;
import com.zehong.system.domain.TTrayInfo;
import com.zehong.system.mapper.TTrayInfoMapper;
import org.springframework.stereotype.Service;
import com.zehong.system.mapper.PalletDeviceBindingMapper;
import com.zehong.system.domain.PalletDeviceBinding;
import com.zehong.system.service.IPalletDeviceBindingService;

import javax.annotation.Resource;

/**
 * 托盘绑定的设备列Service业务层处理
 *
 * @author zehong
 * @date 2025-06-29
 */
@Service
public class PalletDeviceBindingServiceImpl implements IPalletDeviceBindingService
{
    @Resource
    private PalletDeviceBindingMapper palletDeviceBindingMapper;

    @Resource
    private TTrayInfoMapper tTrayInfoMapper;

    /**
     * 查询托盘绑定的设备列
     *
     * @param palletDeviceBindingId 托盘绑定的设备列ID
     * @return 托盘绑定的设备列
     */
    @Override
    public PalletDeviceBinding selectPalletDeviceBindingById(Long palletDeviceBindingId)
    {
        return palletDeviceBindingMapper.selectPalletDeviceBindingById(palletDeviceBindingId);
    }

    /**
     * 查询托盘绑定的设备列列表
     *
     * @param palletDeviceBinding 托盘绑定的设备列
     * @return 托盘绑定的设备列
     */
    @Override
    public List<PalletDeviceBinding> selectPalletDeviceBindingList(PalletDeviceBinding palletDeviceBinding)
    {
        return palletDeviceBindingMapper.selectPalletDeviceBindingList(palletDeviceBinding);
    }

    /**
     * 获取所有未解除绑定的托盘绑定的设备列
     *
     * @param trayId 托盘ID
     * @return 列表
     */
    @Override
    public List<PalletDeviceBinding> getAllExcludeUnbindingTimeByTrayId(Long trayId) {

        return palletDeviceBindingMapper.getAllExcludeUnbindingTimeByTrayId(trayId);
    }

    /**
     * 根据托盘码查询托盘绑定的设备列
     *
     * @param trayCode 托盘码
     * @return 列表
     */
    @Override
    public List<PalletDeviceBinding> listByTrayCode(String trayCode) {
        return palletDeviceBindingMapper.listByTrayCode(trayCode);
    }

    @Override
    public void batchUpdateAdAndStatus(List<PalletDeviceBinding> palletDeviceBindingList) {
        palletDeviceBindingMapper.batchUpdateAdAndStatus(palletDeviceBindingList);
    }

    /**
     * 新增托盘绑定的设备列
     *
     * @param palletDeviceBinding 托盘绑定的设备列
     * @return 结果
     */
    @Override
    public int insertPalletDeviceBinding(PalletDeviceBinding palletDeviceBinding)
    {
        palletDeviceBinding.setCreateTime(DateUtils.getNowDate());
        return palletDeviceBindingMapper.insertPalletDeviceBinding(palletDeviceBinding);
    }

    /**
     * 重置所有托盘绑定的设备列
     *
     * @param trayId 托盘ID
     * @return 结果
     */
    @Override
    public AjaxResult resetAll(Long trayId) {

        int i = palletDeviceBindingMapper.countErrorByTrayId(trayId);
        if (i > 0) {
            return AjaxResult.error("有错误设备未解除绑定，不允许重置");
        }

        palletDeviceBindingMapper.resetAll(trayId);

        tTrayInfoMapper.initStatusByTrayId(trayId);

        return AjaxResult.success();
    }

    /**
     * 批量添加托盘绑定的设备列
     *
     * @param palletDeviceBindingList 托盘绑定的设备列
     * @return 结果
     */
    @Override
    public List<PalletDeviceBinding> batchInsertPalletDeviceBinding(List<PalletDeviceBinding> palletDeviceBindingList) {

        check(palletDeviceBindingList);

        // 获取所有不为空的 deviceCode
        List<String> validDeviceCodes = palletDeviceBindingList.stream()
                .filter(item -> StringUtils.isNotBlank(item.getDeviceCode()))
                .map(PalletDeviceBinding::getDeviceCode)
                .collect(Collectors.toList());

        int i1 = palletDeviceBindingMapper.checkRepeat(validDeviceCodes);
        if(i1 > 0) {
            throw new RuntimeException("有重复绑定设备码");
        }

        palletDeviceBindingList.forEach(palletDeviceBinding -> {
            palletDeviceBinding.setUpdateTime(DateUtils.getNowDate());
            palletDeviceBinding.setCreateTime(DateUtils.getNowDate());
            palletDeviceBinding.setBindingTime(DateUtils.getNowDate());
        });

        TTrayInfo tTrayInfo  = new TTrayInfo();
        tTrayInfo.setfTrayId(palletDeviceBindingList.get(0).getTrayId());
        tTrayInfo.setfStatus("4");
        tTrayInfoMapper.updateStatusByTrayId(tTrayInfo);
        int i = palletDeviceBindingMapper.batchInsertPalletDeviceBinding(palletDeviceBindingList);
        if(i <= 0) {
            throw new RuntimeException("添加失败");
        }
        return palletDeviceBindingList;
    }

    @Override
    public int batchUpdateDeviceCode(List<PalletDeviceBinding> palletDeviceBindingList) {
        check(palletDeviceBindingList);
        palletDeviceBindingList.forEach(palletDeviceBinding -> {
            palletDeviceBinding.setStatus("1");
            palletDeviceBinding.setUpdateTime(DateUtils.getNowDate());
        });

        tTrayInfoMapper.updateToBoundWhenStateIsIdle(palletDeviceBindingList.get(0).getTrayId());

        return palletDeviceBindingMapper.batchUpdateDeviceCode(palletDeviceBindingList);
    }


    private void check(List<PalletDeviceBinding> palletDeviceBindingList) {

        if(palletDeviceBindingList == null || palletDeviceBindingList.size() ==0) {
            throw new RuntimeException("数据不能为空");
        }

        boolean b = palletDeviceBindingList.stream().allMatch(item->StringUtils.isBlank(item.getDeviceCode()));
        if(b) {
            throw new RuntimeException("不能所有设备号都为空！！！");
        }
    }

    @Override
    public int batchUpdateDeviceCodeAndUnbindingTime(List<PalletDeviceBinding> palletDeviceBindingList) {
        palletDeviceBindingList.forEach(palletDeviceBinding -> {
            palletDeviceBinding.setStatus("1");
            palletDeviceBinding.setUpdateTime(DateUtils.getNowDate());
        });

        tTrayInfoMapper.updateToBoundWhenStateIsIdle(palletDeviceBindingList.get(0).getTrayId());

        return palletDeviceBindingMapper.batchUpdateDeviceCodeAndUnbindingTime(palletDeviceBindingList);
    }

    /**
     * 修改托盘绑定的设备列
     *
     * @param palletDeviceBinding 托盘绑定的设备列
     * @return 结果
     */
    @Override
    public int updatePalletDeviceBinding(PalletDeviceBinding palletDeviceBinding)
    {
        return palletDeviceBindingMapper.updatePalletDeviceBinding(palletDeviceBinding);
    }

    /**
     * 批量删除托盘绑定的设备列
     *
     * @param palletDeviceBindingIds 需要删除的托盘绑定的设备列ID
     * @return 结果
     */
    @Override
    public int deletePalletDeviceBindingByIds(Long[] palletDeviceBindingIds)
    {
        return palletDeviceBindingMapper.deletePalletDeviceBindingByIds(palletDeviceBindingIds);
    }

    /**
     * 删除托盘绑定的设备列信息
     *
     * @param palletDeviceBindingId 托盘绑定的设备列ID
     * @return 结果
     */
    @Override
    public int deletePalletDeviceBindingById(Long palletDeviceBindingId)
    {
        return palletDeviceBindingMapper.deletePalletDeviceBindingById(palletDeviceBindingId);
    }

    /**
     * 批量解绑所有设备
     *
     * @param trayId 托盘ID
     * @return 删除结果
     */
    @Override
    public AjaxResult unbindAllDevice(Long trayId) {

        if(trayId == null) {
            return AjaxResult.error("参数错误");
        }

        int i = palletDeviceBindingMapper.unbindAllDevice(trayId);
        if(i <=0) {
            return AjaxResult.error("无设备绑定");
        }

        int i1 = tTrayInfoMapper.initStatusByTrayId(trayId);
        if(i1 <=0) {
            return AjaxResult.error("更新托盘状态失败");
        }

        return AjaxResult.success();
    }

    /**
     * 解绑设备
     *
     * @param palletDeviceBinding 托盘绑定的设备列ID
     * @return 删除结果
     */
    @Override
    public AjaxResult unbindDevice(PalletDeviceBinding palletDeviceBinding) {

        if(palletDeviceBinding.getPalletDeviceBindingId() == null || StringUtils.isBlank(palletDeviceBinding.getDeviceCode())) {
            return AjaxResult.error("参数错误");
        }

        PalletDeviceBinding palletDeviceBindingDb = palletDeviceBindingMapper.selectPalletDeviceBindingById(palletDeviceBinding.getPalletDeviceBindingId());
        if(palletDeviceBindingDb == null) {
            return AjaxResult.error("数据不存在");
        }

        if(!palletDeviceBindingDb.getDeviceCode().equals(palletDeviceBinding.getDeviceCode())) {
            return AjaxResult.error("设备码错误");
        }

        int i = palletDeviceBindingMapper.unbindDevice(palletDeviceBindingDb.getPalletDeviceBindingId());
        if (i > 0) {

            // 成功之后 判断 是否还有设备，如果没有设备的话则 初始化托盘状态
            int count = palletDeviceBindingMapper.countDeviceByTrayId(palletDeviceBindingDb.getTrayId());
            if(count == 0) {
                tTrayInfoMapper.initStatusByTrayId(palletDeviceBindingDb.getTrayId());
            }

            return AjaxResult.success();
        }
        return AjaxResult.error();
    }
}
