package com.fuyuanshen.equipment.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.DateUtils;
import com.fuyuanshen.equipment.domain.Device;
import com.fuyuanshen.equipment.domain.dto.DeviceExcelExportDTO;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: 默苍璃
 * @date: 2025-06-0618:22
 */
@Service
public class DeviceExportService {

    public void export(List<Device> devices, HttpServletResponse response) {
        try {
            String fileName = "设备列表_" + System.currentTimeMillis() + ".xlsx";
            // 使用URLEncoder进行RFC 5987编码
            String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20");

            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 使用RFC 5987标准编码文件名
            response.setHeader("Content-disposition", "attachment;filename*=UTF-8''" + encodedFileName);

            // 转换为DTO列表
            List<DeviceExcelExportDTO> dtoList = devices.stream().map(device -> {
                DeviceExcelExportDTO dto = new DeviceExcelExportDTO();
                dto.setId(device.getId());
                dto.setDeviceType(device.getDeviceType());
                dto.setCustomerName(device.getCustomerName());
                dto.setDeviceName(device.getDeviceName());
                dto.setDeviceMac(device.getDeviceMac());
                // 设备IMEI
                dto.setDeviceImei(device.getDeviceImei());
                // 蓝牙名称
                dto.setBluetoothName(device.getBluetoothName());
                dto.setLongitude(device.getLongitude());
                dto.setLatitude(device.getLatitude());
                dto.setRemark(device.getRemark());
                dto.setTypeName(device.getTypeName());
                dto.setCreateBy(device.getCreateByName());
                Integer deviceStatus = device.getDeviceStatus();
                dto.setDeviceStatus(deviceStatus == 1 ? "正常" : "失效");
                // 时间戳转换
                dto.setCreateTime(DateUtils.format(device.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));

                // 处理图片URL转换
                handleDevicePic(device, dto);

                return dto;
            }).collect(Collectors.toList());

            // 写入Excel
            EasyExcel.write(response.getOutputStream(), DeviceExcelExportDTO.class).sheet("设备数据").doWrite(dtoList);

        } catch (IOException e) {
            throw new RuntimeException("导出Excel失败", e);
        }
    }


    private void handleDevicePic(Device device, DeviceExcelExportDTO dto) {
        String picUrl = device.getDevicePic();
        if (picUrl != null && !picUrl.trim().isEmpty()) {
            try {
                // 尝试创建URL对象（会自动验证格式）
                dto.setDevicePic(new URL(picUrl));
            } catch (MalformedURLException e) {
                // 不是有效URL时设置为null
                dto.setDevicePic(null);
            }
        } else {
            dto.setDevicePic(null);
        }
    }

}