package com.aiotagro.cattletrade.business.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.crypto.digest.DigestUtil;
import com.aiotagro.cattletrade.business.entity.SysRole;
import com.aiotagro.cattletrade.business.entity.SysUser;
import com.aiotagro.cattletrade.business.mapper.MemberDriverMapper;
import com.aiotagro.cattletrade.business.mapper.MemberMapper;
import com.aiotagro.cattletrade.business.mapper.SysRoleMapper;
import com.aiotagro.cattletrade.business.mapper.SysUserMapper;
import com.aiotagro.common.core.constant.Constants;
import com.aiotagro.common.core.utils.SecurityUtil;
import com.aiotagro.common.core.web.domain.AjaxResult;
import com.aiotagro.common.core.web.domain.PageResultResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.transaction.annotation.Transactional;

/**
 * 会员用户控制器
 *
 * @author System
 * @date 2025-01-16
 */
@RestController
@RequestMapping("/member")
public class MemberController {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private MemberDriverMapper memberDriverMapper;

    @Resource
    private MemberMapper memberMapper;

    @Resource
    private SysRoleMapper sysRoleMapper;

    /**
     * 获取用户列表（用于权限分配）
     */
    @SaCheckPermission("permission:menu:list")
    @GetMapping("/userList")
    public AjaxResult getUserList() {
        // 查询所有用户（从sys_user表）
        List<SysUser> userList = sysUserMapper.selectUserListForPermission();
        return AjaxResult.success(userList);
    }

    /**
     * 获取用户列表（分页，用于用户管理页面）
     * 查询member表和member_user表关联数据
     */
    @PostMapping("/userList")
    public PageResultResponse<Map<String, Object>> getUserListWithPagination(@RequestBody Map<String, Object> params) {
        try {
            Integer pageNum = params.get("pageNum") != null ? (Integer) params.get("pageNum") : 1;
            Integer pageSize = params.get("pageSize") != null ? (Integer) params.get("pageSize") : 10;
            String username = (String) params.get("username");
            String mobile = (String) params.get("mobile");
            Integer type = params.get("type") != null ? (Integer) params.get("type") : null;
            Boolean usernameExact = params.get("usernameExact") != null ? (Boolean) params.get("usernameExact") : false;
            Boolean mobileExact = params.get("mobileExact") != null ? (Boolean) params.get("mobileExact") : false;

            // 计算偏移量
            Integer offset = (pageNum - 1) * pageSize;
            
            // 查询用户列表（从member表和member_user表）
            List<Map<String, Object>> userList = memberMapper.selectUserListForManagement(username, mobile, type, usernameExact, mobileExact, offset, pageSize);
            
            // 查询总数
            Long total = memberMapper.countUserListForManagement(username, mobile, type, usernameExact, mobileExact);
            
            return new PageResultResponse<>(total, userList);
        } catch (Exception e) {
            e.printStackTrace();
            return new PageResultResponse<>(0L, java.util.Collections.emptyList());
        }
    }

    /**
     * 新增司机
     */
    @PostMapping("/addDriver")
    public AjaxResult addDriver(@RequestBody Map<String, Object> params) {
        try {
            // 获取参数值
            String username = (String) params.get("username");
            String mobile = (String) params.get("mobile");
            String driverLicense = (String) params.get("driverLicense");
            String drivingLicense = (String) params.get("drivingLicense");
            String carImg = (String) params.get("carImg");
            String recordCode = (String) params.get("recordCode");
            String idCard = (String) params.get("idCard");
            String remark = (String) params.get("remark");
            Integer status = params.get("status") != null ? (Integer) params.get("status") : 0; // 默认启用

            // 参数验证
            if (mobile == null || mobile.trim().isEmpty()) {
                return AjaxResult.error("手机号不能为空");
            }
            if (username == null || username.trim().isEmpty()) {
                return AjaxResult.error("司机姓名不能为空");
            }

            // 检查手机号是否已存在
            Integer existingMemberId = memberMapper.selectMemberIdByMobile(mobile);
            if (existingMemberId != null) {
                return AjaxResult.error("该手机号已存在");
            }

            // 先插入member表
            int memberResult = memberMapper.insertMember(mobile, 1, status); // type=1表示司机
            if (memberResult <= 0) {
                return AjaxResult.error("司机基础信息插入失败");
            }

            // 获取刚插入的member记录的ID
            Integer memberId = memberMapper.selectMemberIdByMobile(mobile);
            if (memberId == null) {
                return AjaxResult.error("获取新司机ID失败");
            }
            
            // 插入member_driver表（不再包含carNumber参数）
            int driverResult = memberDriverMapper.insertDriver(memberId, username, 
                    driverLicense, drivingLicense, carImg, recordCode, idCard, remark);
            if (driverResult <= 0) {
                return AjaxResult.error("司机详细信息插入失败");
            }
            
            return AjaxResult.success("司机新增成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("新增司机失败：" + e.getMessage());
        }
    }

    /**
     * 获取司机列表（分页）
     */
    @PostMapping("/driverList")
    public PageResultResponse<Map<String, Object>> driverList(@RequestBody Map<String, Object> params) {
        Integer pageNum = params.get("pageNum") != null ? (Integer) params.get("pageNum") : 1;
        Integer pageSize = params.get("pageSize") != null ? (Integer) params.get("pageSize") : 10;
        String username = (String) params.get("username");
        String mobile = (String) params.get("mobile");
        
        // 添加调试日志
        
        Page<Map<String, Object>> result = PageHelper.startPage(pageNum, pageSize);
        List<Map<String, Object>> list;
        
        // 如果只查询手机号，使用简化的精确查询
        if (mobile != null && !mobile.trim().isEmpty() && (username == null || username.trim().isEmpty())) {
            list = memberDriverMapper.selectDriverListByMobile(mobile);
        } else if ((username != null && !username.trim().isEmpty()) || (mobile != null && !mobile.trim().isEmpty())) {
            list = memberDriverMapper.selectDriverListBySearch(username, mobile, true);
        } else {
            list = memberDriverMapper.selectDriverList();
        }
        
        return new PageResultResponse<>(result.getTotal(), list);
    }
    @PostMapping("/memberListByType")
    public PageResultResponse<Map<String, Object>> getMemberListByType(@RequestBody Map<String, Object> params) {
        Integer pageNum = params.get("pageNum") != null ? (Integer) params.get("pageNum") : 1;
        Integer pageSize = params.get("pageSize") != null ? (Integer) params.get("pageSize") : 10;
        String username = (String) params.get("username");
        Integer type = params.get("type") != null ? (Integer) params.get("type") : null;

        // 计算偏移量
        Integer offset = (pageNum - 1) * pageSize;
        
        // 查询数据
        List<Map<String, Object>> list = memberMapper.selectMemberListByType(type, username, offset, pageSize);
        
        // 查询总数
        Long total = memberMapper.countMemberListByType(type, username);
        
        return new PageResultResponse<>(total, list);
    }

    /**
     * 插入测试数据（仅用于开发测试）
     */
    @PostMapping("/insertTestData")
    public AjaxResult insertTestData() {
        try {
            // 这里可以添加插入测试数据的逻辑
            // 由于没有直接的SQL执行方法，我们返回成功信息
            return AjaxResult.success("测试数据插入功能已准备就绪，请手动执行SQL脚本");
        } catch (Exception e) {
            return AjaxResult.error("插入测试数据失败: " + e.getMessage());
        }
    }

    /**
     * 调试接口：直接查询member表数据
     */
    @GetMapping("/debugMemberData")
    public AjaxResult debugMemberData() {
        try {
            // 直接查询member表的所有数据
            List<Map<String, Object>> allMembers = memberMapper.selectMemberUserList();
            return AjaxResult.success("member表数据", allMembers);
        } catch (Exception e) {
            return AjaxResult.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 更新司机信息
     */
    @SaCheckPermission("member:edit")
    @PostMapping("/updateDriver")
    @Transactional
    public AjaxResult updateDriver(@RequestBody Map<String, Object> params) {
        try {
            Integer id = (Integer) params.get("id");
            if (id == null) {
                return AjaxResult.error("司机ID不能为空");
            }

            // 获取参数值
            String username = (String) params.get("username");
            String mobile = (String) params.get("mobile");
            String driverLicense = (String) params.get("driverLicense");
            String drivingLicense = (String) params.get("drivingLicense");
            String carImg = (String) params.get("carImg");
            String recordCode = (String) params.get("recordCode");
            String idCard = (String) params.get("idCard");
            String remark = (String) params.get("remark");

            // 获取司机的member_id
            Map<String, Object> driverInfo = memberDriverMapper.selectDriverById(id);
            if (driverInfo == null) {
                return AjaxResult.error("司机信息不存在");
            }
            
            // member_id 从数据库返回时可能是Long类型，需要转换为Integer
            Object memberIdObj = driverInfo.get("member_id");
            Integer memberId = null;
            if (memberIdObj != null) {
                if (memberIdObj instanceof Long) {
                    memberId = ((Long) memberIdObj).intValue();
                } else if (memberIdObj instanceof Integer) {
                    memberId = (Integer) memberIdObj;
                } else if (memberIdObj instanceof Number) {
                    memberId = ((Number) memberIdObj).intValue();
                }
            }
            
            if (memberId == null) {
                return AjaxResult.error("司机关联的会员ID不存在");
            }

            // 如果提供了新手机号，检查是否与其他用户重复
            if (mobile != null && !mobile.trim().isEmpty()) {
                String currentMobile = (String) driverInfo.get("mobile");
                // 如果手机号有变化，检查新手机号是否已存在
                if (currentMobile == null || !currentMobile.equals(mobile.trim())) {
                    Integer existingMemberId = memberMapper.selectMemberIdByMobile(mobile.trim());
                    if (existingMemberId != null && !existingMemberId.equals(memberId)) {
                        return AjaxResult.error("该手机号已被其他用户使用");
                    }
                }
                
                // 更新member表的手机号
                int mobileUpdateResult = memberMapper.updateMemberMobile(memberId, mobile.trim());
                if (mobileUpdateResult <= 0) {
                    return AjaxResult.error("更新手机号失败");
                }
            }

            // 执行更新member_driver表
            int result = memberDriverMapper.updateDriver(id, username, driverLicense, 
                    drivingLicense, carImg, recordCode, idCard, remark);
            
            if (result > 0) {
                return AjaxResult.success("司机信息更新成功");
            } else {
                return AjaxResult.error("司机信息更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("更新司机信息失败：" + e.getMessage());
        }
    }

    /**
     * 更新用户信息
     */
    @SaCheckPermission("member:edit")
    @PostMapping("/updateUser")
    public AjaxResult updateUser(@RequestBody Map<String, Object> params) {
        try {
            Integer id = (Integer) params.get("id");
            if (id == null) {
                return AjaxResult.error("用户ID不能为空");
            }

            // 获取参数值
            String mobile = (String) params.get("mobile");
            Integer type = params.get("type") != null ? (Integer) params.get("type") : null;
            Integer status = params.get("status") != null ? (Integer) params.get("status") : null;
            String username = (String) params.get("username");
            String cbkAccount = (String) params.get("cbkAccount");
            String remark = (String) params.get("remark");

            // 处理mobile和cbkAccount：如果为空字符串，设置为null
            if (mobile != null && mobile.trim().isEmpty()) {
                mobile = null;
            }
            if (cbkAccount != null && cbkAccount.trim().isEmpty()) {
                cbkAccount = null;
            }

            // 执行更新
            int result = memberMapper.updateUserInfo(id, mobile, type, status, username, cbkAccount, remark);
            
            if (result > 0) {
                return AjaxResult.success("用户信息更新成功");
            } else {
                return AjaxResult.error("用户信息更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("更新用户信息失败：" + e.getMessage());
        }
    }

    /**
     * 新增用户
     */
    @PostMapping("/addUser")
    @Transactional
    public AjaxResult addUser(@RequestBody Map<String, Object> params) {
        try {
            // 获取参数值
            String mobile = (String) params.get("mobile");
            Integer type = params.get("type") != null ? (Integer) params.get("type") : null;
            Integer status = params.get("status") != null ? (Integer) params.get("status") : 0; // 默认启用
            String username = (String) params.get("username");
            String cbkAccount = (String) params.get("cbkAccount");
            String remark = (String) params.get("remark");

            // 参数验证
            if (username == null || username.trim().isEmpty()) {
                return AjaxResult.error("用户姓名不能为空");
            }
            if (type == null) {
                return AjaxResult.error("用户类型不能为空");
            }

            // 处理mobile：如果为空或空字符串，设置为null
            if (mobile != null && mobile.trim().isEmpty()) {
                mobile = null;
            }

            // 检查手机号是否已存在（仅在mobile不为空时检查）
            if (mobile != null && !mobile.trim().isEmpty()) {
                Integer existingMemberId = memberMapper.selectMemberIdByMobile(mobile);
                if (existingMemberId != null) {
                    return AjaxResult.error("该手机号已存在");
                }
            }

            // 先插入member表
            int memberResult = memberMapper.insertMember(mobile, type, status);
            if (memberResult <= 0) {
                return AjaxResult.error("用户基础信息插入失败");
            }

            // 获取刚插入的member记录的ID
            Integer memberId = null;
            if (mobile != null && !mobile.trim().isEmpty()) {
                // 如果mobile不为空，通过mobile查询
                memberId = memberMapper.selectMemberIdByMobile(mobile);
            } else {
                // 如果mobile为空，查询最新插入的记录（通过create_time和id）
                memberId = memberMapper.selectLatestMemberId();
            }
            if (memberId == null) {
                return AjaxResult.error("获取新用户ID失败");
            }
            
            // 再插入member_user表
            int userResult = memberMapper.insertMemberUser(memberId, username, cbkAccount, remark);
            if (userResult <= 0) {
                return AjaxResult.error("用户详细信息插入失败");
            }
            
            // 自动创建员工记录
            try {
                createEmployeeRecord(username, mobile, type, status);
            } catch (Exception e) {
                // 员工记录创建失败不影响用户创建，只记录日志
                System.err.println("创建员工记录失败: " + e.getMessage());
            }
            
            return AjaxResult.success("用户新增成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("新增用户失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID获取司机详情
     */
    @SaCheckPermission("member:view")
    @GetMapping("/driverDetail/{id}")
    public AjaxResult getDriverDetail(@PathVariable("id") Integer id) {
        try {
            if (id == null) {
                return AjaxResult.error("司机ID不能为空");
            }

            Map<String, Object> driverInfo = memberDriverMapper.selectDriverById(id);
            if (driverInfo != null) {
                return AjaxResult.success(driverInfo);
            } else {
                return AjaxResult.error("司机信息不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取司机详情失败：" + e.getMessage());
        }
    }

    /**
     * 删除司机
     */
    @SaCheckPermission("member:delete")
    @PostMapping("/deleteDriver")
    @Transactional
    public AjaxResult deleteDriver(@RequestBody Map<String, Object> params) {
        try {
            Integer id = (Integer) params.get("id");
            if (id == null) {
                return AjaxResult.error("司机ID不能为空");
            }

            // 查询司机信息，获取member_id
            Map<String, Object> driverInfo = memberDriverMapper.selectDriverById(id);
            if (driverInfo == null) {
                return AjaxResult.error("司机信息不存在");
            }

            // member_id 从数据库返回时可能是Long类型，需要转换为Integer
            Object memberIdObj = driverInfo.get("member_id");
            Integer memberId = null;
            if (memberIdObj != null) {
                if (memberIdObj instanceof Long) {
                    memberId = ((Long) memberIdObj).intValue();
                } else if (memberIdObj instanceof Integer) {
                    memberId = (Integer) memberIdObj;
                }
            }

            // 删除司机详情（member_driver表）
            int driverResult = memberDriverMapper.deleteDriver(id);
            
            // 如果member_id存在，也删除member表记录
            if (memberId != null) {
                int memberResult = memberMapper.deleteById(memberId);
                if (memberResult > 0 && driverResult > 0) {
                    return AjaxResult.success("删除成功");
                } else if (driverResult > 0) {
                    return AjaxResult.success("删除司机信息成功");
                } else {
                    return AjaxResult.error("删除失败");
                }
            } else {
                if (driverResult > 0) {
                    return AjaxResult.success("删除成功");
                } else {
                    return AjaxResult.error("删除失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("删除司机失败：" + e.getMessage());
        }
    }

    /**
     * 根据用户类型自动创建员工记录
     * 
     * @param username 用户姓名
     * @param mobile 手机号
     * @param userType 用户类型 (1:司机, 2:供应商, 3:资金方, 4:采购商)
     * @param status 状态
     */
    private void createEmployeeRecord(String username, String mobile, Integer userType, Integer status) {
        // 检查手机号是否已存在于员工表中
        List<SysUser> existingUsers = sysUserMapper.selectList(
            new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getMobile, mobile)
                .eq(SysUser::getIsDelete, 0)
        );
        
        if (!existingUsers.isEmpty()) {
            return;
        }
        
        // 根据用户类型获取或创建对应的岗位
        Integer roleId = getOrCreateRoleByUserType(userType);
        if (roleId == null) {
            throw new RuntimeException("无法获取或创建岗位");
        }
        
        // 创建员工记录
        SysUser sysUser = new SysUser();
        sysUser.setName(username);
        sysUser.setMobile(mobile);
        sysUser.setRoleId(roleId);
        sysUser.setPassword(DigestUtil.md5Hex(Constants.USER_PASSWORD_PREFIX + "123456")); // 默认密码123456
        sysUser.setStatus(status != null ? status : 1); // 默认启用
        sysUser.setCreateTime(new Date());
        sysUser.setCreateBy(SecurityUtil.getCurrentUserId());
        sysUser.setIsDelete(0);
        
        int result = sysUserMapper.insert(sysUser);
        if (result <= 0) {
            throw new RuntimeException("员工记录插入失败");
        }
        
    }
    
    /**
     * 根据用户类型获取或创建对应的岗位
     * 
     * @param userType 用户类型
     * @return 岗位ID
     */
    private Integer getOrCreateRoleByUserType(Integer userType) {
        String roleName;
        String roleDescription;
        
        // 根据用户类型确定岗位名称和描述
        switch (userType) {
            case 1:
                roleName = "司机";
                roleDescription = "司机用户岗位";
                break;
            case 2:
                roleName = "供应商";
                roleDescription = "供应商用户岗位";
                break;
            case 3:
                roleName = "资金方";
                roleDescription = "资金方用户岗位";
                break;
            case 4:
                roleName = "采购商";
                roleDescription = "采购商用户岗位";
                break;
            default:
                roleName = "普通用户";
                roleDescription = "普通用户岗位";
                break;
        }
        
        // 查询是否已存在该岗位
        List<SysRole> existingRoles = sysRoleMapper.selectList(
            new LambdaQueryWrapper<SysRole>()
                .eq(SysRole::getName, roleName)
                .eq(SysRole::getIsDelete, 0)
        );
        
        if (!existingRoles.isEmpty()) {
            return existingRoles.get(0).getId();
        }
        
        // 创建新岗位
        SysRole newRole = new SysRole();
        newRole.setName(roleName);
        newRole.setDescription(roleDescription);
        newRole.setCreateTime(new Date());
        newRole.setIsDelete(0);
        
        int result = sysRoleMapper.insert(newRole);
        if (result <= 0) {
            throw new RuntimeException("创建岗位失败");
        }
        
        return newRole.getId();
    }

    /**
     * 图片代理接口 - 解决CORS跨域问题
     * 通过后端代理访问外部图片资源
     */
    @GetMapping("/proxy/image")
    public ResponseEntity<byte[]> proxyImage(@RequestParam("url") String imageUrl) {
        try {
            // 验证URL格式
            if (imageUrl == null || imageUrl.trim().isEmpty()) {
                return ResponseEntity.badRequest().build();
            }
            
            // 安全检查：只允许HTTPS协议
            if (!imageUrl.startsWith("https://")) {
                return ResponseEntity.badRequest().build();
            }
            
            
            // 创建URL连接
            URL url = new URL(imageUrl);
            URLConnection connection = url.openConnection();
            
            // 设置请求头，模拟浏览器请求
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
            connection.setRequestProperty("Accept", "image/*");
            connection.setConnectTimeout(10000); // 10秒连接超时
            connection.setReadTimeout(30000); // 30秒读取超时
            
            // 获取输入流
            InputStream inputStream = connection.getInputStream();
            
            // 读取图片数据
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            
            byte[] imageData = outputStream.toByteArray();
            
            // 关闭流
            inputStream.close();
            outputStream.close();
            
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_JPEG); // 默认设置为JPEG
            headers.setContentLength(imageData.length);
            
            // 设置缓存头，减少重复请求
            headers.setCacheControl("public, max-age=3600"); // 缓存1小时
            
            // 根据文件扩展名设置正确的Content-Type
            String contentType = connection.getContentType();
            if (contentType != null && contentType.startsWith("image/")) {
                headers.setContentType(MediaType.parseMediaType(contentType));
            }
            
        
        return new ResponseEntity<>(imageData, headers, HttpStatus.OK);
        
    } catch (Exception e) {
        System.err.println("图片代理失败: " + e.getMessage());
        e.printStackTrace();
        return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
    }
}

/**
 * 调试接口：查看司机图片数据详情
 */
@GetMapping("/debug/driverImages")
public AjaxResult debugDriverImages() {
    try {
        // 查询所有司机的图片数据
        List<Map<String, Object>> drivers = memberDriverMapper.selectDriverList();
        
        for (Map<String, Object> driver : drivers) {
            String username = (String) driver.get("username");
            String carImg = (String) driver.get("car_img");
            String mobile = (String) driver.get("mobile");
            
            
            if (carImg != null && !carImg.trim().isEmpty()) {
                String[] urls = carImg.split(",");
                for (int i = 0; i < urls.length; i++) {
                    String url = urls[i].trim();
                }
            } else {
            }
        }
        
        return AjaxResult.success("司机图片数据调试完成，请查看控制台输出", drivers);
    } catch (Exception e) {
        e.printStackTrace();
        return AjaxResult.error("调试失败: " + e.getMessage());
    }
}

@GetMapping("/debug/carImgSplit")
public AjaxResult debugCarImgSplit() {
    try {
        // 测试分割逻辑
        String testCarImg = "https://smart-1251449951.cos.ap-guangzhou.myqcloud.com/iotPlateform/2025/10/16/4c4e20251016142427.jpg,https://smart-1251449951.cos.ap-guangzhou.myqcloud.com/iotPlateform/2025/10/16/4c4e20251016142429.jpg";
        
        
        String[] carImgUrls = testCarImg.split(",");
        
        if (carImgUrls.length >= 2) {
            String carBehindPhoto = carImgUrls[0].trim();
            String carFrontPhoto = carImgUrls[1].trim();
            
            
            Map<String, Object> result = new HashMap<>();
            result.put("originalCarImg", testCarImg);
            result.put("carBehindPhoto", carBehindPhoto);
            result.put("carFrontPhoto", carFrontPhoto);
            result.put("splitCount", carImgUrls.length);
            
            return AjaxResult.success("分割测试完成", result);
        } else {
            return AjaxResult.error("分割失败：URL数量不足");
        }
    } catch (Exception e) {
        e.printStackTrace();
        return AjaxResult.error("分割测试失败: " + e.getMessage());
    }
}
}


