package com.aiotagro.cattletrade.business.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.aiotagro.cattletrade.business.entity.Delivery;
import com.aiotagro.cattletrade.business.entity.DeliveryDevice;
import com.aiotagro.cattletrade.business.service.IDeliveryDeviceService;
import com.aiotagro.cattletrade.business.service.IDeliveryService;
import com.aiotagro.cattletrade.business.service.IJbqClientService;
import com.aiotagro.cattletrade.business.service.IJbqServerService;
import com.aiotagro.cattletrade.business.service.IXqClientService;
import com.aiotagro.common.core.web.domain.AjaxResult;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信端运送清单控制器
 *
 * @author System
 * @date 2025-01-16
 */
@RestController
@RequestMapping("/wechatDelivery")
public class WechatDeliveryController {

    @Autowired
    private IDeliveryDeviceService deliveryDeviceService;

    @Autowired
    private IDeliveryService deliveryService;
    
    @Autowired
    private IXqClientService xqClientService;

    @Autowired
    private IJbqClientService jbqClientService;

    @Autowired
    private IJbqServerService jbqServerService;

    /**
     * 获取装车信息
     */
    @SaCheckPermission("delivery:view")
    @PostMapping("/carLoadInfo")
    public AjaxResult carLoadInfo(@RequestBody Map<String, Object> params) {
        try {
            Integer deliveryId = (Integer) params.get("deliveryId");
            if (deliveryId == null) {
                return AjaxResult.error("运送清单ID不能为空");
            }

            Map<String, Object> result = new HashMap<>();
            
            // 查询耳标设备
            AjaxResult earResult = jbqClientService.getDevicesByDeliveryId(deliveryId, 2);
            if (earResult.get("code").equals(200)) {
                result.put("deliveryDevices", earResult.get("data"));
            } else {
                result.put("deliveryDevices", java.util.Collections.emptyList());
            }
            
            // 查询项圈设备
            AjaxResult collarResult = xqClientService.getDevicesByDeliveryId(deliveryId, 3);
            if (collarResult.get("code").equals(200)) {
                result.put("xqDevices", collarResult.get("data"));
            } else {
                result.put("xqDevices", java.util.Collections.emptyList());
            }
            
            return AjaxResult.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("查询装车信息失败：" + e.getMessage());
        }
    }

    /**
     * 测试数据库连接
     */
    @GetMapping("/testConnection")
    public AjaxResult testConnection() {
        try {
            // 测试基本查询
            List<Delivery> deliveries = deliveryService.list();
            Map<String, Object> result = new HashMap<>();
            result.put("deliveryCount", deliveries.size());
            result.put("status", "数据库连接正常");
            return AjaxResult.success("测试成功", result);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("测试失败: " + e.getMessage());
        }
    }

    /**
     * 更新装车信息
     */
    @SaCheckPermission("delivery:edit")
    @PostMapping("/updateLoadInfo")
    public AjaxResult updateLoadInfo(@RequestBody Map<String, Object> params) {
        try {
            Object deliveryIdObj = params.get("deliveryId");
            Integer deliveryId = null;
            if (deliveryIdObj != null) {
                if (deliveryIdObj instanceof Integer) {
                    deliveryId = (Integer) deliveryIdObj;
                } else if (deliveryIdObj instanceof String) {
                    try {
                        deliveryId = Integer.parseInt((String) deliveryIdObj);
                    } catch (NumberFormatException e) {
                        return AjaxResult.error("运送清单ID格式错误");
                    }
                } else {
                }
            }
            if (deliveryId == null) {
                return AjaxResult.error("运送清单ID不能为空");
            }

            // 更新运送清单基本信息
            LambdaUpdateWrapper<Delivery> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Delivery::getId, deliveryId);

            // 更新预计送达时间
            Object estimatedDeliveryTime = params.get("estimatedDeliveryTime");
            if (estimatedDeliveryTime != null && !estimatedDeliveryTime.toString().trim().isEmpty()) {
                updateWrapper.set(Delivery::getEstimatedDeliveryTime, estimatedDeliveryTime);
            }

            // 更新空车过磅重量
            Object emptyWeight = params.get("emptyWeight");
            if (emptyWeight != null && !emptyWeight.toString().trim().isEmpty()) {
                updateWrapper.set(Delivery::getEmptyWeight, emptyWeight);
            }

            // 更新装车过磅重量
            Object entruckWeight = params.get("entruckWeight");
            if (entruckWeight != null && !entruckWeight.toString().trim().isEmpty()) {
                updateWrapper.set(Delivery::getEntruckWeight, entruckWeight);
            }
            
            // 更新落地过磅重量
            Object landingEntruckWeight = params.get("landingEntruckWeight");
            if (landingEntruckWeight != null && !landingEntruckWeight.toString().trim().isEmpty()) {
                updateWrapper.set(Delivery::getLandingEntruckWeight, landingEntruckWeight);
            }
            // 更新检疫票
            if (params.get("quarantineTickeyUrl") != null) {
                updateWrapper.set(Delivery::getQuarantineTickeyUrl, params.get("quarantineTickeyUrl"));
            }

            // 更新传纸质磅单（双章）
            if (params.get("poundListImg") != null) {
                updateWrapper.set(Delivery::getPoundListImg, params.get("poundListImg"));
            }

            // 更新装车过磅视频
            if (params.get("entruckWeightVideo") != null) {
                updateWrapper.set(Delivery::getEntruckWeightVideo, params.get("entruckWeightVideo"));
            }

            // 更新空车过磅视频
            if (params.get("emptyWeightVideo") != null) {
                updateWrapper.set(Delivery::getEmptyWeightVideo, params.get("emptyWeightVideo"));
            }

            // 更新上传装牛视频
            if (params.get("entruckVideo") != null) {
                updateWrapper.set(Delivery::getEntruckVideo, params.get("entruckVideo"));
            }

            // 更新控槽视频
            if (params.get("controlSlotVideo") != null) {
                updateWrapper.set(Delivery::getControlSlotVideo, params.get("controlSlotVideo"));
            }

            // 更新车辆空磅上磅车头照片
            if (params.get("emptyVehicleFrontPhoto") != null) {
                updateWrapper.set(Delivery::getEmptyVehicleFrontPhoto, params.get("emptyVehicleFrontPhoto"));
            }

            // 更新装完牛绕车一圈视频
            if (params.get("cattleLoadingCircleVideo") != null) {
                updateWrapper.set(Delivery::getCattleLoadingCircleVideo, params.get("cattleLoadingCircleVideo"));
            }

            // 更新车辆过重磅车头照片
            if (params.get("loadedVehicleFrontPhoto") != null) {
                updateWrapper.set(Delivery::getLoadedVehicleFrontPhoto, params.get("loadedVehicleFrontPhoto"));
            }

            // 更新车辆重磅照片
            if (params.get("loadedVehicleWeightPhoto") != null) {
                updateWrapper.set(Delivery::getLoadedVehicleWeightPhoto, params.get("loadedVehicleWeightPhoto"));
            }

            // 更新驾驶员手持身份证站车头照片
            if (params.get("driverIdCardPhoto") != null) {
                updateWrapper.set(Delivery::getDriverIdCardPhoto, params.get("driverIdCardPhoto"));
            }

            // 执行更新
            boolean updateResult = deliveryService.update(updateWrapper);

            if (updateResult) {
                return AjaxResult.success("装车信息更新成功");
            } else {
                return AjaxResult.error("装车信息更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("更新装车信息失败：" + e.getMessage());
        }
    }
}

