package com.fuyuanshen.app.service.impl.equipment;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuyuanshen.app.domain.APPDevice;
import com.fuyuanshen.app.domain.APPDeviceType;
import com.fuyuanshen.app.domain.dto.APPReNameDTO;
import com.fuyuanshen.app.domain.dto.APPUnbindDTO;
import com.fuyuanshen.app.domain.query.APPDeviceQueryCriteria;
import com.fuyuanshen.app.domain.vo.APPDeviceTypeVo;
import com.fuyuanshen.app.enums.UserType;
import com.fuyuanshen.app.mapper.equipment.APPDeviceMapper;
import com.fuyuanshen.app.mapper.equipment.AppDeviceTypeMapper;
import com.fuyuanshen.app.service.equipment.APPDeviceService;
import com.fuyuanshen.common.core.exception.BadRequestException;
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
import com.fuyuanshen.common.satoken.utils.AppLoginHelper;
import com.fuyuanshen.common.satoken.utils.LoginHelper;
import com.fuyuanshen.equipment.domain.Device;
import com.fuyuanshen.equipment.domain.DeviceType;
import com.fuyuanshen.equipment.domain.dto.AppDeviceBo;
import com.fuyuanshen.equipment.domain.query.DeviceQueryCriteria;
import com.fuyuanshen.equipment.enums.BindingStatusEnum;
import com.fuyuanshen.equipment.enums.CommunicationModeEnum;
import com.fuyuanshen.equipment.mapper.DeviceMapper;
import com.fuyuanshen.equipment.mapper.DeviceTypeMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @Author: WY
 * @Date: 2025/5/16
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class APPDeviceServiceImpl extends ServiceImpl<APPDeviceMapper, APPDevice> implements APPDeviceService {

    private final APPDeviceMapper appDeviceMapper;
    private final DeviceMapper deviceMapper;
    private final AppDeviceTypeMapper appDeviceTypeMapper;
    private final DeviceTypeMapper deviceTypeMapper;


    /**
     * APP用户设备列表
     *
     * @param criteria
     */
    @Override
    public TableDataInfo<APPDevice> appDeviceList(Page<APPDevice> page, APPDeviceQueryCriteria criteria) {
        // criteria.setCustomerId(SecurityUtils.getCurrentUserId());
        // IPage<APPDevice> devices = appDeviceMapper.appDeviceList(page, criteria);
        // return new PageResult<>(devices.getRecords(), devices.getTotal());
        return null;
    }


    /**
     * APP用户设备类型列表
     *
     * @param criteria
     * @return
     */
    @Override
    public List<APPDeviceType> appTypeList(APPDeviceQueryCriteria criteria) {
        // criteria.setCustomerId(SecurityUtils.getCurrentUserId());
        // return appDeviceTypeMapper.appTypeList(criteria);
        return null;
    }


    /**
     * APP/小程序用户设备绑定
     *
     * @param criteria
     */
    @Override
    @Transactional
    public void appBindDevice(APPDeviceQueryCriteria criteria) {
        List<Device> devices = new ArrayList<>();
        if (criteria.getCommunicationMode().equals(CommunicationModeEnum.BLUETOOTH.getValue())) {
            devices = deviceMapper.selectList(new QueryWrapper<Device>()
                    .eq("original_device_id", null)
                    .eq("device_mac", criteria.getDeviceMac()));
            if (CollectionUtil.isEmpty(devices)) {
                throw new BadRequestException("请先将设备入库！！！");
            }
            List<APPDevice> appDevices = appDeviceMapper.selectList(new QueryWrapper<APPDevice>()
                    .eq("device_mac", criteria.getDeviceMac()).eq("binding_type", UserType.APP.getValue()));
            if (CollectionUtil.isNotEmpty(appDevices)) {
                throw new BadRequestException("该设备已绑定！！！");
            }
        }

        if (criteria.getCommunicationMode().equals(CommunicationModeEnum.FOUR_G.getValue())) {
            devices = deviceMapper.selectList(new QueryWrapper<Device>()
                    .eq("original_device_id", null)
                    .eq("device_imei", criteria.getDeviceImei()));
            if (CollectionUtil.isEmpty(devices)) {
                throw new BadRequestException("请先将设备入库！！！");
            }
            List<APPDevice> appDevices = appDeviceMapper.selectList(new QueryWrapper<APPDevice>()
                    .eq("device_imei", criteria.getDeviceImei()).eq("binding_type", UserType.APP.getValue()));
            if (CollectionUtil.isNotEmpty(appDevices)) {
                throw new BadRequestException("该设备已绑定！！！");
            }
        }

        Device device = devices.get(0);
        device.setBindingStatus(BindingStatusEnum.BOUND.getCode());
        deviceMapper.updateById(device);

        APPDevice appDevice = new APPDevice();
        BeanUtil.copyProperties(device, appDevice);
        appDevice.setBindingType(UserType.APP.getValue());
        appDevice.setBindingStatus(BindingStatusEnum.BOUND.getCode());
        Long userId = LoginHelper.getUserId();
        appDevice.setCustomerId(userId);
        appDevice.setCreateTime(new Timestamp(System.currentTimeMillis()));
        // 设备类型名称
        appDevice.setDeviceTypeName(device.getTypeName());
        appDeviceMapper.insert(appDevice);

        APPDeviceType appDeviceType = appDeviceTypeMapper.selectById(device.getDeviceType());
        if (appDeviceType == null) {
            DeviceType deviceType = deviceTypeMapper.selectById(device.getDeviceType());
            APPDeviceType type = new APPDeviceType();
            BeanUtil.copyProperties(deviceType, type);
            type.setCustomerId(userId);
            appDeviceTypeMapper.insert(type);
        }

    }


    /**
     * 分页查询APP/小程序设备
     *
     * @param criteria
     * @param page
     * @return
     */
    @Override
    public TableDataInfo<APPDevice> queryAll(Page<APPDevice> page, APPDeviceQueryCriteria criteria) {
        IPage<APPDevice> devices = appDeviceMapper.queryAll(page, criteria);
        return new TableDataInfo<>(devices.getRecords(), devices.getTotal());
    }


    /**
     * APP/小程序用户设备解绑
     *
     * @param deviceForm
     */
    @Override
    @Transactional
    public void unbindAPPDevice(APPUnbindDTO deviceForm) {
        // QueryWrapper<APPDevice> queryWrapper = new QueryWrapper<>();
        // QueryWrapper<Device> qw = new QueryWrapper<>();
        // if (StringUtils.isNotEmpty(deviceForm.getDeviceMac())) {
        //     queryWrapper.eq("device_mac", deviceForm.getDeviceMac());
        //     qw.eq("device_mac", deviceForm.getDeviceMac());
        // }
        // if (StringUtils.isNotEmpty(deviceForm.getDeviceImei())) {
        //     queryWrapper.eq("device_imei", deviceForm.getDeviceImei());
        //     qw.eq("device_imei", deviceForm.getDeviceImei());
        // }
        // queryWrapper.eq("binding_type", UserType.APP.getValue());
        // APPDevice appDevice = appDeviceMapper.selectOne(queryWrapper);
        // appDeviceMapper.delete(queryWrapper);
        //
        // List<Device> devices = deviceMapper.selectList(qw);
        // List<Long> ids = devices.stream()
        //         .map(Device::getId)
        //         .collect(Collectors.toList());
        // if (CollectionUtil.isNotEmpty(ids)) {
        //     appDeviceTypeMapper.deleteBatchIds(ids);
        // }
        // Device device = new Device();
        // device.setId(appDevice.getId());
        // device.setBindingStatus(BindingStatusEnum.UNBOUND.getCode());
        // deviceMapper.updateById(device);

    }

    @Override
    public List<APPDeviceTypeVo> getTypeList() {
        Long userId = AppLoginHelper.getUserId();
        return appDeviceMapper.getTypeList(userId);
    }

    @Override
    public void reName(APPReNameDTO reNameDTO) {
        UpdateWrapper<Device> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", reNameDTO.getId())
                .eq("binding_user_id", AppLoginHelper.getUserId())
                .set("device_name", reNameDTO.getDeviceName());
        deviceMapper.update(updateWrapper);
    }


    /**
     * WEB端查看APP客户设备绑定
     *
     * @param criteria
     * @return
     */
    @Override
    public TableDataInfo<APPDevice> queryAppDeviceList(DeviceQueryCriteria criteria) {

        // Page<AppDeviceVo> result = baseMapper.queryAppDeviceList(pageQuery.build(), bo);
        // return TableDataInfo.build(result);

        return null;
    }

    @Override
    public int sendMessage(AppDeviceBo bo) {
        UpdateWrapper<Device> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", bo.getDeviceId())
                .eq("binding_user_id", AppLoginHelper.getUserId())
                .set("send_msg", bo.getSendMsg());
        return deviceMapper.update(updateWrapper);
    }


}
