package com.fuyuanshen.equipment.service.impl;

import cn.hutool.core.bean.BeanUtil;
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.common.core.domain.model.LoginUser;
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
import com.fuyuanshen.common.satoken.utils.LoginHelper;
import com.fuyuanshen.customer.domain.Customer;
import com.fuyuanshen.customer.mapper.CustomerMapper;
import com.fuyuanshen.equipment.constants.DeviceConstants;
import com.fuyuanshen.equipment.domain.Device;
import com.fuyuanshen.equipment.domain.DeviceType;
import com.fuyuanshen.equipment.domain.form.DeviceForm;
import com.fuyuanshen.equipment.domain.query.DeviceQueryCriteria;
import com.fuyuanshen.equipment.domain.query.DeviceTypeQueryCriteria;
import com.fuyuanshen.equipment.domain.vo.CustomerVo;
import com.fuyuanshen.equipment.mapper.DeviceMapper;
import com.fuyuanshen.equipment.mapper.DeviceTypeMapper;
import com.fuyuanshen.equipment.service.DeviceService;
import com.fuyuanshen.system.domain.vo.SysOssVo;
import com.fuyuanshen.system.service.ISysOssService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Description:
 * @Author: WY
 * @Date: 2025/5/16
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements DeviceService {

    @Value("${file.device.pic}")
    private String filePath;
    @Value("${file.device.ip}")
    private String ip;

    private final DeviceMapper deviceMapper;
    private final DeviceTypeMapper deviceTypeMapper;

    private final CustomerMapper customerMapper;

    private final ISysOssService ossService;


    /**
     * 分页查询设备
     *
     * @param criteria 条件
     * @param page     分页参数
     * @return
     * @throws IOException
     */
    @Override
    public TableDataInfo<Device> queryAll(DeviceQueryCriteria criteria, Page<Device> page) throws IOException {

        // criteria.setCustomerId(LoginHelper.getUserId());
        criteria.setCurrentOwnerId(LoginHelper.getUserId());
        IPage<Device> devices = deviceMapper.findAll(criteria, page);

        List<Device> records = devices.getRecords();
        for (Device record : records) {
            if (record.getDevicePic() == null) {
                record.setDevicePic("");
            }
        }

        // return PageUtil.toPage(devices);
        return new TableDataInfo<Device>(records, devices.getTotal());
    }


    @Override
    public List<Device> queryAll(DeviceQueryCriteria criteria) {
        return deviceMapper.findAll(criteria);
    }


    /**
     * 查询所有设备
     *
     * @param criteria 筛选条件
     * @return
     */
    @Override
    public List<Device> queryAllDevices(DeviceQueryCriteria criteria) {
        return deviceMapper.findAllDevices(criteria);
    }


    /**
     * 新增设备
     *
     * @param deviceForm
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addDevice(DeviceForm deviceForm) throws Exception {
        DeviceTypeQueryCriteria queryCriteria = new DeviceTypeQueryCriteria();
        queryCriteria.setDeviceTypeId(deviceForm.getId());
        queryCriteria.setCustomerId(LoginHelper.getUserId());
        List<DeviceType> deviceTypes = deviceTypeMapper.findAll(queryCriteria);
        if (deviceTypes.isEmpty()) {
            throw new Exception("设备类型不存在!!!");
        }

        // 保存图片并获取URL
        // String imageUrl = saveDeviceImage(deviceForm.getFile(), deviceForm.getDeviceName());
        SysOssVo upload = ossService.upload(deviceForm.getFile());
        // 设置图片路径
        deviceForm.setDevicePic(upload.getUrl());

        // 转换对象并插入数据库
        Device device = new Device();
        LoginUser loginUser = LoginHelper.getLoginUser();
        device.setCurrentOwnerId(loginUser.getUserId());
        device.setCreateByName(loginUser.getNickname());
        BeanUtil.copyProperties(deviceForm, device, true);

        deviceMapper.insert(device);

    }


    /**
     * 更新设备信息
     *
     * @param deviceForm /
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DeviceForm deviceForm) throws Exception {

        DeviceTypeQueryCriteria deviceTypeQueryCriteria = new DeviceTypeQueryCriteria();
        deviceTypeQueryCriteria.setDeviceTypeId(deviceForm.getId());
        deviceTypeQueryCriteria.setCustomerId(LoginHelper.getUserId());
        List<DeviceType> deviceTypes = deviceTypeMapper.findAll(deviceTypeQueryCriteria);
        if (deviceTypes.isEmpty()) {
            throw new Exception("设备类型不存在!!!");
        }

        DeviceQueryCriteria queryCriteria = new DeviceQueryCriteria();
        queryCriteria.setDeviceId(deviceForm.getId());
        queryCriteria.setCustomerId(LoginHelper.getUserId());
        List<Device> devices = deviceMapper.findAll(queryCriteria);
        if (devices.isEmpty()) {
            throw new Exception("设备不存在!!!");
        }
        Device device = devices.get(0);

        // 处理上传的图片
        // String imageUrl = saveDeviceImage(deviceForm.getFile(), device.getDeviceName());
        SysOssVo upload = ossService.upload(deviceForm.getFile());
        // 设置图片路径
        deviceForm.setDevicePic(upload.getUrl());

        // 更新字段
        BeanUtil.copyProperties(deviceForm, device, true);
        device.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        deviceMapper.updateById(device);
    }


    /**
     * 保存设备图片并返回访问路径
     *
     * @param file      MultipartFile
     * @param deviceMac 设备MAC用于生成唯一文件名
     * @return 文件存储路径 URL 形式
     */
    private String saveDeviceImage(MultipartFile file, String deviceMac) throws IOException {
        if (file == null || file.isEmpty()) {
            return null;
        }

        String originalFileName = file.getOriginalFilename();
        String fileExtension = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
        String newFileName = "PS_" + deviceMac + "." + fileExtension;

        File newFile = new File(filePath + DeviceConstants.FILE_ACCESS_ISOLATION + File.separator + newFileName);

        if (!newFile.getParentFile().exists()) {
            newFile.getParentFile().mkdirs();
        }

        log.info("图片保存路径: {}", newFile.getAbsolutePath());
        file.transferTo(newFile);

        return ip + DeviceConstants.FILE_ACCESS_PREFIX + "/" + DeviceConstants.FILE_ACCESS_ISOLATION + "/" + newFileName;
    }


    /**
     * 删除设备
     *
     * @param ids /
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Long> ids) {
        List<Long> invalidIds = new ArrayList<>();

        for (Long id : ids) {
            Device deviceType = deviceMapper.selectById(id);
            if (deviceType == null || !Objects.equals(deviceType.getCurrentOwnerId(), LoginHelper.getUserId())) {
                invalidIds.add(id);
            }
        }
        if (!invalidIds.isEmpty()) {
            throw new RuntimeException("以下设备无法删除（ID 不存在或无权限）: " + invalidIds);
        }

        deviceMapper.deleteByIds(ids);
    }


    /**
     * 分配客户
     *
     * @param customerVo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignCustomer(CustomerVo customerVo) {
        List<Long> deviceIds = customerVo.getDeviceIds();
        Long customerId = customerVo.getCustomerId();

        Customer customer = customerMapper.queryCustomerById(customerId, LoginHelper.getLoginUser().getPid());
        if (customer == null) {
            throw new RuntimeException("待分配的客户不存在！！！");
        }

        List<Long> invalidIds = new ArrayList<>();
        List<Device> devices = new ArrayList<>();
        for (Long id : deviceIds) {
            Device device = deviceMapper.selectById(id);
            if (device == null || !Objects.equals(device.getCurrentOwnerId(), LoginHelper.getUserId())) {
                invalidIds.add(id);
                continue;
            }
            device.setCustomerId(customerId);
            device.setCustomerName(customer.getNickName());
            devices.add(device);

        }
        if (!invalidIds.isEmpty()) {
            throw new RuntimeException("以下设备无法分配（ID 不存在或无权限）: " + invalidIds);
        }

        devices.forEach((device) -> {
            deviceMapper.updateById(device);
            device.setId(null);
            device.setCurrentOwnerId(customerId);
            deviceMapper.insert(device);

            DeviceType deviceType = deviceTypeMapper.selectById(device.getDeviceType());
            deviceType.setId(null);
            device.setCurrentOwnerId(customerId);
            deviceTypeMapper.insert(deviceType);

        });
    }

    public void assign(List<Long> deviceIds) {

    }


    /**
     * 撤回设备
     *
     * @param deviceForm
     */
    @Override
    public void withdrawDevice(DeviceForm deviceForm) {


    }


    /**
     * 解绑设备
     *
     * @param deviceForm
     */
    @Override
    @Transactional
    public void unbindDevice(DeviceForm deviceForm) {

    }


}
