package cn.iocoder.yudao.module.system.service.deviceinfo;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.system.controller.admin.deviceinfo.vo.DeviceInfoPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.deviceinfo.vo.DeviceInfoSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.cashregisterinfo.CashRegisterInfoDO;
import cn.iocoder.yudao.module.system.dal.dataobject.deviceInfo.DeviceInfoDO;
import cn.iocoder.yudao.module.system.dal.dataobject.devuce.DevuceDO;
import cn.iocoder.yudao.module.system.dal.dataobject.facedeviceinfo.FaceDeviceInfoDO;
import cn.iocoder.yudao.module.system.dal.mysql.cashregisterinfo.CashRegisterInfoMapper;
import cn.iocoder.yudao.module.system.dal.mysql.deviceInfo.DeviceInfoMapper;
import cn.iocoder.yudao.module.system.dal.mysql.devuce.DevuceMapper;
import cn.iocoder.yudao.module.system.dal.mysql.facedeviceinfo.FaceDeviceInfoMapper;
import cn.iocoder.yudao.module.system.enums.ErrorCodeConstants;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 设备信息关联门店 Service 实现类
 *
 * @author 开发账号
 */
@Service
@Validated
public class DeviceInfoServiceImpl implements DeviceInfoService {

    @Resource
    private DeviceInfoMapper deviceInfoMapper;

    @Resource
    private StringRedisTemplate RedisTemplate;

    @Resource
    private HttpServletRequest httpServletRequest;

    @Resource
    private FaceDeviceInfoMapper faceDeviceInfoMapper;

    @Resource
    private CashRegisterInfoMapper cashRegisterInfoMapper;

    @Resource
    private DevuceMapper devuceMapper;

    @Override
    public Long createDeviceInfo(DeviceInfoSaveReqVO createReqVO) {
        // 插入
        DeviceInfoDO deviceInfo = BeanUtils.toBean(createReqVO, DeviceInfoDO.class);
        List<DeviceInfoDO> deviceInfoDOS = deviceInfoMapper.selectList(new LambdaQueryWrapper<DeviceInfoDO>().eq(DeviceInfoDO::getDeviceIp, createReqVO.getDeviceIp()));
        if (CollectionUtil.isNotEmpty(deviceInfoDOS)){
            throw exception(ErrorCodeConstants.DEVUCE_EXISTS);
        }
        deviceInfoMapper.insert(deviceInfo);
        // 返回
        return deviceInfo.getId();
    }

    @Override
    public void updateDeviceInfo(DeviceInfoSaveReqVO updateReqVO) {
        // 校验存在
        validateDeviceInfoExists(updateReqVO.getId());
        List<DeviceInfoDO> deviceInfoDOS = deviceInfoMapper.selectList(new LambdaQueryWrapper<DeviceInfoDO>()
                .eq(DeviceInfoDO::getDeviceIp, updateReqVO.getDeviceIp())
                .ne(DeviceInfoDO::getId, updateReqVO.getId()));
        if (CollectionUtil.isNotEmpty(deviceInfoDOS)){
            throw exception(ErrorCodeConstants.DEVUCE_EXISTS);
        }
        // 更新
        DeviceInfoDO updateObj = BeanUtils.toBean(updateReqVO, DeviceInfoDO.class);
        deviceInfoMapper.updateById(updateObj);
        //清空设备绑定菜品
        devuceMapper.update(Wrappers.<DevuceDO>lambdaUpdate().eq(DevuceDO::getDeviceSn,updateObj.getDeviceIp())
                .eq(DevuceDO::getBind,true).set(DevuceDO::getDishesId,null));
    }

    @Override
    public void deleteDeviceInfo(Long id) {
        // 校验存在
        validateDeviceInfoExists(id);
        // 删除
        deviceInfoMapper.deleteById(id);
    }

    private void validateDeviceInfoExists(Long id) {
        if (deviceInfoMapper.selectById(id) == null) {
            throw exception(ErrorCodeConstants.DEVUCE_NOT_EXISTS);
        }
    }

    @Override
    public DeviceInfoDO getDeviceInfo(Long id) {
        return deviceInfoMapper.selectById(id);
    }

    @Override
    public PageResult<DeviceInfoDO> getDeviceInfoPage(DeviceInfoPageReqVO pageReqVO) {
        return deviceInfoMapper.selectPage(pageReqVO);
    }

    @Override
    public void alive() {
        String deviceSn = getHearder();
        RedisTemplate.opsForValue().set(deviceSn, String.valueOf(System.currentTimeMillis()));
        deviceInfoMapper.update(new DeviceInfoDO(),new LambdaUpdateWrapper<DeviceInfoDO>()
                .eq(DeviceInfoDO::getDeviceIp,deviceSn)
                .set(DeviceInfoDO::getAlive,"1"));
        faceDeviceInfoMapper.update(new FaceDeviceInfoDO(),new LambdaUpdateWrapper<FaceDeviceInfoDO>()
                .eq(FaceDeviceInfoDO::getMac,deviceSn)
                .set(FaceDeviceInfoDO::getAlive,"1"));
        cashRegisterInfoMapper.update(new CashRegisterInfoDO(),new LambdaUpdateWrapper<CashRegisterInfoDO>()
                .eq(CashRegisterInfoDO::getEquipmentCode,deviceSn)
                .set(CashRegisterInfoDO::getAlive,"1"));
    }

    @Override
    public int updateAlive() {
        //称重机
        List<String> updateList = new ArrayList<>();
        List<DeviceInfoDO> deviceInfoDOS = deviceInfoMapper.selectList();
        List<String> devuceList = deviceInfoDOS.stream().map(DeviceInfoDO::getDeviceIp).collect(Collectors.toList());
        for (String deviceSn : devuceList){
            if(StringUtils.isBlank(deviceSn)){
                continue;
            }
            String time = RedisTemplate.opsForValue().get(deviceSn);
            if(StringUtils.isBlank(time)){
                updateList.add(deviceSn);
                continue;
            }
            if(System.currentTimeMillis()-Long.valueOf(time)>120000){
                updateList.add(deviceSn);
            }
        }

        if(CollectionUtil.isNotEmpty(updateList)){
            deviceInfoMapper.update(new DeviceInfoDO(),new LambdaUpdateWrapper<DeviceInfoDO>()
                    .set(DeviceInfoDO::getAlive,"0")
                    .in(DeviceInfoDO::getDeviceIp,updateList));
        }
        //人脸
        List<String> upList = new ArrayList<>();
        List<FaceDeviceInfoDO> faceDeviceInfoDOS = faceDeviceInfoMapper.selectList();
        List<String> macList = faceDeviceInfoDOS.stream().map(FaceDeviceInfoDO::getMac).collect(Collectors.toList());
        for (String deviceSn : macList){
            if(StringUtils.isBlank(deviceSn)){
                continue;
            }
            String time = RedisTemplate.opsForValue().get(deviceSn);
            if(StringUtils.isBlank(time)){
                upList.add(deviceSn);
                continue;
            }
            if(System.currentTimeMillis()-Long.valueOf(time)>120000){
                upList.add(deviceSn);
            }
        }

        if(CollectionUtil.isNotEmpty(upList)){
            faceDeviceInfoMapper.update(new FaceDeviceInfoDO(),new LambdaUpdateWrapper<FaceDeviceInfoDO>()
                    .set(FaceDeviceInfoDO::getAlive,"0")
                    .in(FaceDeviceInfoDO::getMac,upList));
        }

        //收银机
        List<String> cashUpList = new ArrayList<>();
        List<CashRegisterInfoDO> cashRegisterInfoDOS = cashRegisterInfoMapper.selectList();
        List<String> codes = cashRegisterInfoDOS.stream().map(CashRegisterInfoDO::getEquipmentCode).collect(Collectors.toList());
        for (String code : codes){
            if(StringUtils.isBlank(code)){
                continue;
            }
            String time = RedisTemplate.opsForValue().get(code);
            if(StringUtils.isBlank(code)){
                upList.add(code);
                continue;
            }
            if(System.currentTimeMillis()-Long.valueOf(time)>120000){
                upList.add(code);
            }
        }

        if(CollectionUtil.isNotEmpty(cashUpList)){
            cashRegisterInfoMapper.update(new CashRegisterInfoDO(),new LambdaUpdateWrapper<CashRegisterInfoDO>()
                    .set(CashRegisterInfoDO::getAlive,"0")
                    .in(CashRegisterInfoDO::getEquipmentCode,upList));
        }


        return updateList.size()+upList.size()+cashUpList.size();
    }

    public String getHearder(){
        try {
            return httpServletRequest.getHeader("Authorization");
        } catch (Exception e) {
            throw exception(2000_10_001,"无法获取设备编码");
        }
    }

    @Override
    public Long getCarteen(String mac) {
        DeviceInfoDO deviceInfoDO = deviceInfoMapper.selectOne(new LambdaQueryWrapper<DeviceInfoDO>()
                .eq(DeviceInfoDO::getDeviceIp, mac)
                .last("limit 1"));
        if(ObjectUtil.isNotEmpty(deviceInfoDO)){
            return deviceInfoDO.getCarteenId();
        }
        FaceDeviceInfoDO faceDeviceInfoDO = faceDeviceInfoMapper.selectOne(new LambdaQueryWrapper<FaceDeviceInfoDO>()
                .eq(FaceDeviceInfoDO::getMac, mac)
                .last("limit 1"));
        if(ObjectUtil.isNotEmpty(faceDeviceInfoDO)){
            return faceDeviceInfoDO.getCarteenId();
        }
        return null;
    }
}