package com.erp.warehouse.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.warehouse.client.CloudWmsClient;
import com.erp.warehouse.client.CloudWmsClientFactory;
import com.erp.warehouse.dto.PurchaseOrderDTO;
import com.erp.warehouse.dto.SaleOrderDTO;
import com.erp.warehouse.dto.StockQueryDTO;
import com.erp.warehouse.dto.WarehouseDTO;
import com.erp.warehouse.entity.Warehouse;
import com.erp.warehouse.entity.WarehouseTemplateBinding;
import com.erp.warehouse.mapper.WarehouseMapper;
import com.erp.warehouse.mapper.WarehouseTemplateBindingMapper;
import com.erp.warehouse.service.CloudWarehouseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 云仓服务实现
 */
@Slf4j
@Service
public class CloudWarehouseServiceImpl implements CloudWarehouseService {

    @Autowired
    private WarehouseMapper warehouseMapper;

    @Autowired
    private WarehouseTemplateBindingMapper bindingMapper;

    @Autowired
    private CloudWmsClientFactory clientFactory;

    // ==================== 仓库管理 ====================

    @Override
    public PageResult<Warehouse> listWarehouses(String name, String type, int page, int limit) {
        LambdaQueryWrapper<Warehouse> queryWrapper = new LambdaQueryWrapper<>();
        
        if (name != null && !name.isEmpty()) {
            queryWrapper.like(Warehouse::getName, name);
        }
        if (type != null && !type.isEmpty()) {
            queryWrapper.eq(Warehouse::getType, type);
        }
        
        queryWrapper.orderByDesc(Warehouse::getId);

        IPage<Warehouse> pageResult = warehouseMapper.selectPage(
                new Page<>(page, limit), 
                queryWrapper
        );

        return new PageResult<>(
                pageResult.getRecords(),
                pageResult.getTotal(),
                (int) pageResult.getCurrent(),
                (int) pageResult.getPages()
        );
    }

    @Override
    public Warehouse getWarehouse(Long id) {
        Warehouse warehouse = warehouseMapper.selectById(id);
        if (warehouse == null) {
            throw new IllegalArgumentException("仓库不存在: " + id);
        }
        return warehouse;
    }

    @Override
    @Transactional
    public Warehouse createWarehouse(WarehouseDTO dto) {
        validateWarehouseDto(dto);
        
        Warehouse warehouse = Warehouse.builder()
                .name(dto.getName())
                .type(dto.getType())
                .cloudSystem(dto.getCloudSystem())
                .ownerCode(dto.getOwnerCode())
                .cloudCode(dto.getCloudCode())
                .appKey(dto.getAppKey())
                .appSecret(dto.getAppSecret())
                .apiUrl(dto.getApiUrl())
                .remark(dto.getRemark())
                .enabled(true)
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .build();

        warehouseMapper.insert(warehouse);
        return warehouse;
    }

    @Override
    @Transactional
    public Warehouse updateWarehouse(Long id, WarehouseDTO dto) {
        Warehouse warehouse = warehouseMapper.selectById(id);
        if (warehouse == null) {
            throw new IllegalArgumentException("仓库不存在: " + id);
        }

        if (dto.getName() != null) {
            warehouse.setName(dto.getName());
        }
        if (dto.getType() != null) {
            warehouse.setType(dto.getType());
        }
        if (dto.getCloudSystem() != null) {
            warehouse.setCloudSystem(dto.getCloudSystem());
        }
        if (dto.getOwnerCode() != null) {
            warehouse.setOwnerCode(dto.getOwnerCode());
        }
        if (dto.getCloudCode() != null) {
            warehouse.setCloudCode(dto.getCloudCode());
        }
        if (dto.getAppKey() != null) {
            warehouse.setAppKey(dto.getAppKey());
        }
        if (dto.getAppSecret() != null) {
            warehouse.setAppSecret(dto.getAppSecret());
        }
        if (dto.getApiUrl() != null) {
            warehouse.setApiUrl(dto.getApiUrl());
        }
        if (dto.getRemark() != null) {
            warehouse.setRemark(dto.getRemark());
        }
        
        warehouse.setUpdateTime(LocalDateTime.now());
        warehouseMapper.updateById(warehouse);
        
        return warehouse;
    }

    @Override
    @Transactional
    public void deleteWarehouse(Long id) {
        Warehouse warehouse = warehouseMapper.selectById(id);
        if (warehouse == null) {
            throw new IllegalArgumentException("仓库不存在: " + id);
        }
        // TODO: 检查是否有库存关联
        warehouseMapper.deleteById(id);
    }

    private void validateWarehouseDto(WarehouseDTO dto) {
        if ("cloud".equals(dto.getType())) {
            if (dto.getCloudSystem() == null || dto.getCloudSystem().isEmpty()) {
                throw new IllegalArgumentException("云仓必须指定云仓系统");
            }
        }
    }

    // ==================== 云仓订单管理 ====================

    @Override
    public CloudWmsClient.CloudWmsResponse pushPurchaseOrder(Long warehouseId, PurchaseOrderDTO purchaseOrder) {
        Warehouse warehouse = getWarehouse(warehouseId);
        CloudWmsClient client = clientFactory.createClient(warehouse);
        
        log.info("推送采购单到云仓: warehouseId={}, poOrderNo={}", warehouseId, purchaseOrder.getPoOrderNo());
        
        CloudWmsClient.CloudWmsResponse response = client.pushPurchaseOrder(purchaseOrder);
        
        if (response.isSuccess()) {
            log.info("采购单推送成功: poOrderNo={}", purchaseOrder.getPoOrderNo());
        } else {
            log.error("采购单推送失败: poOrderNo={}, code={}, message={}", 
                    purchaseOrder.getPoOrderNo(), response.getCode(), response.getMessage());
        }
        
        return response;
    }

    @Override
    public CloudWmsClient.CloudWmsResponse confirmPurchaseOrder(Long warehouseId, String poOrderNo) {
        Warehouse warehouse = getWarehouse(warehouseId);
        CloudWmsClient client = clientFactory.createClient(warehouse);
        
        log.info("确认采购入库: warehouseId={}, poOrderNo={}", warehouseId, poOrderNo);
        
        CloudWmsClient.CloudWmsResponse response = client.confirmPurchaseOrder(poOrderNo);
        
        if (response.isSuccess()) {
            log.info("采购入库确认成功: poOrderNo={}", poOrderNo);
        } else {
            log.error("采购入库确认失败: poOrderNo={}, code={}, message={}", 
                    poOrderNo, response.getCode(), response.getMessage());
        }
        
        return response;
    }

    @Override
    public CloudWmsClient.CloudWmsResponse pushSaleOrder(Long warehouseId, SaleOrderDTO saleOrder) {
        Warehouse warehouse = getWarehouse(warehouseId);
        CloudWmsClient client = clientFactory.createClient(warehouse);
        
        log.info("推送销售订单到云仓: warehouseId={}, orderNo={}", warehouseId, saleOrder.getOrderNo());
        
        CloudWmsClient.CloudWmsResponse response = client.pushSaleOrder(saleOrder);
        
        if (response.isSuccess()) {
            log.info("销售订单推送成功: orderNo={}", saleOrder.getOrderNo());
        } else {
            log.error("销售订单推送失败: orderNo={}, code={}, message={}", 
                    saleOrder.getOrderNo(), response.getCode(), response.getMessage());
        }
        
        return response;
    }

    // ==================== 云仓库存同步 ====================

    @Override
    public Object queryStock(Long warehouseId, String skuCode) {
        Warehouse warehouse = getWarehouse(warehouseId);
        CloudWmsClient client = clientFactory.createClient(warehouse);
        
        log.debug("查询库存: warehouseId={}, skuCode={}", warehouseId, skuCode);
        
        return client.queryStock(skuCode, warehouse.getCloudCode());
    }

    @Override
    public Object getStockList(Long warehouseId, int page, int pageSize) {
        Warehouse warehouse = getWarehouse(warehouseId);
        CloudWmsClient client = clientFactory.createClient(warehouse);
        
        log.debug("获取库存列表: warehouseId={}, page={}, pageSize={}", warehouseId, page, pageSize);
        
        return client.getStockList(warehouse.getCloudCode(), page, pageSize);
    }

    @Override
    public CloudWmsClient.CloudWmsResponse adjustStock(Long warehouseId, String skuCode, int type, int quantity, String reason) {
        Warehouse warehouse = getWarehouse(warehouseId);
        CloudWmsClient client = clientFactory.createClient(warehouse);
        
        log.info("库存调整: warehouseId={}, skuCode={}, type={}, quantity={}, reason={}", 
                warehouseId, skuCode, type, quantity, reason);
        
        return client.adjustStock(warehouse.getCloudCode(), skuCode, type, quantity, reason);
    }

    @Override
    public Object getGoodsList(Long warehouseId, int page, int pageSize) {
        Warehouse warehouse = getWarehouse(warehouseId);
        CloudWmsClient client = clientFactory.createClient(warehouse);
        
        log.debug("获取商品列表: warehouseId={}, page={}, pageSize={}", warehouseId, page, pageSize);
        
        return client.getGoodsList(page, pageSize);
    }

    @Override
    public Object getGoodsDetail(Long warehouseId, String itemId) {
        Warehouse warehouse = getWarehouse(warehouseId);
        CloudWmsClient client = clientFactory.createClient(warehouse);
        
        log.debug("获取商品详情: warehouseId={}, itemId={}", warehouseId, itemId);
        
        return client.getGoodsDetail(itemId);
    }

    @Override
    public Object getLogisticsTrace(Long warehouseId, String logisticsNo) {
        Warehouse warehouse = getWarehouse(warehouseId);
        CloudWmsClient client = clientFactory.createClient(warehouse);
        
        log.debug("查询物流轨迹: warehouseId={}, logisticsNo={}", warehouseId, logisticsNo);
        
        return client.getLogisticsTrace(logisticsNo);
    }

    @Override
    public Object getCloudWarehouseList(Long warehouseId) {
        Warehouse warehouse = getWarehouse(warehouseId);
        CloudWmsClient client = clientFactory.createClient(warehouse);
        
        log.debug("获取云仓仓库列表: warehouseId={}", warehouseId);
        
        return client.getWarehouseList();
    }

    // ==================== 仓库模板绑定 ====================

    @Override
    public List<WarehouseTemplateBinding> getBindings(Long warehouseId) {
        LambdaQueryWrapper<WarehouseTemplateBinding> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WarehouseTemplateBinding::getWarehouseId, warehouseId);
        return bindingMapper.selectList(queryWrapper);
    }

    @Override
    @Transactional
    public WarehouseTemplateBinding createBinding(Long warehouseId, String platform, Long templateId) {
        // 检查是否已存在相同平台绑定
        LambdaQueryWrapper<WarehouseTemplateBinding> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WarehouseTemplateBinding::getWarehouseId, warehouseId)
                    .eq(WarehouseTemplateBinding::getPlatform, platform);
        WarehouseTemplateBinding existing = bindingMapper.selectOne(queryWrapper);
        
        if (existing != null) {
            throw new IllegalArgumentException("该仓库已绑定此平台的模板");
        }

        WarehouseTemplateBinding binding = WarehouseTemplateBinding.builder()
                .warehouseId(warehouseId)
                .platform(platform)
                .templateId(templateId)
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .build();

        bindingMapper.insert(binding);
        return binding;
    }

    @Override
    @Transactional
    public WarehouseTemplateBinding updateBinding(Long bindingId, Long templateId) {
        WarehouseTemplateBinding binding = bindingMapper.selectById(bindingId);
        if (binding == null) {
            throw new IllegalArgumentException("绑定记录不存在: " + bindingId);
        }

        binding.setTemplateId(templateId);
        binding.setUpdateTime(LocalDateTime.now());
        bindingMapper.updateById(binding);
        
        return binding;
    }

    @Override
    @Transactional
    public void deleteBinding(Long bindingId) {
        WarehouseTemplateBinding binding = bindingMapper.selectById(bindingId);
        if (binding == null) {
            throw new IllegalArgumentException("绑定记录不存在: " + bindingId);
        }
        bindingMapper.deleteById(bindingId);
    }

    // ==================== 云仓连接测试 ====================

    @Override
    public CloudWmsResponse testConnection(Long warehouseId) {
        Warehouse warehouse = getWarehouse(warehouseId);
        
        if (!"cloud".equals(warehouse.getType())) {
            return CloudWmsResponse.error(400, "ERP仓库不支持连接测试");
        }
        
        try {
            CloudWmsClient client = clientFactory.createClient(warehouse);
            Object result = client.testConnection();
            
            if (result instanceof CloudWmsResponse) {
                return (CloudWmsResponse) result;
            }
            return CloudWmsResponse.success(result);
            
        } catch (Exception e) {
            log.error("云仓连接测试失败: warehouseId={}", warehouseId, e);
            return CloudWmsResponse.error(500, "连接失败: " + e.getMessage());
        }
    }

    // 内部类简化
    private static class CloudWmsResponse extends com.erp.warehouse.client.CloudWmsClient.CloudWmsResponse {
        public CloudWmsResponse(boolean success, Integer code, String message, Object data) {
            super(success, code, message, data);
        }
        
        public static CloudWmsResponse success(Object data) {
            return new CloudWmsResponse(true, 0, "success", data);
        }
        
        public static CloudWmsResponse error(Integer code, String message) {
            return new CloudWmsResponse(false, code, message, null);
        }
    }
}
