package com.aiotagro.cattletrade.business.service.impl;

import com.aiotagro.cattletrade.business.dto.WarehouseCreateDto;
import com.aiotagro.cattletrade.business.dto.WarehouseDto;
import com.aiotagro.cattletrade.business.dto.WarehouseEditDto;
import com.aiotagro.cattletrade.business.entity.Warehouse;
import com.aiotagro.cattletrade.business.mapper.WarehouseMapper;
import com.aiotagro.cattletrade.business.service.IWarehouseService;
import com.aiotagro.common.core.utils.SecurityUtil;
import com.aiotagro.common.core.utils.bean.BeanUtils;
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.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * 中转仓管理服务实现类
 *
 * @author System
 * @date 2025-01-20
 */
@Service
public class WarehouseServiceImpl extends ServiceImpl<WarehouseMapper, Warehouse> implements IWarehouseService {

    @Autowired
    private WarehouseMapper warehouseMapper;

    /**
     * 分页查询中转仓列表
     */
    @Override
    public PageResultResponse<Warehouse> pageQuery(WarehouseDto dto) {
        Integer pageNum = dto.getPageNum() != null ? dto.getPageNum() : 1;
        Integer pageSize = dto.getPageSize() != null ? dto.getPageSize() : 10;

        // 使用PageHelper进行分页
        Page<Warehouse> page = PageHelper.startPage(pageNum, pageSize);

        // 构建查询条件
        LambdaQueryWrapper<Warehouse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.and(wrapper -> wrapper.eq(Warehouse::getIsDelete, 0).or().isNull(Warehouse::getIsDelete));
        
        if (StringUtils.hasText(dto.getWarehouseName())) {
            queryWrapper.like(Warehouse::getWarehouseName, dto.getWarehouseName());
        }
        if (StringUtils.hasText(dto.getWarehouseCode())) {
            queryWrapper.like(Warehouse::getWarehouseCode, dto.getWarehouseCode());
        }
        if (dto.getStatus() != null) {
            queryWrapper.eq(Warehouse::getStatus, dto.getStatus());
        }
        
        queryWrapper.orderByDesc(Warehouse::getCreateTime);

        // 执行查询
        List<Warehouse> list = warehouseMapper.selectList(queryWrapper);

        // 构建分页结果
        return new PageResultResponse<>(page.getTotal(), list);
    }

    /**
     * 新增中转仓
     */
    @Override
    @Transactional
    public AjaxResult addWarehouse(WarehouseCreateDto dto) {
        // 如果中转仓编码为空，自动生成
        String warehouseCode = dto.getWarehouseCode();
        if (!StringUtils.hasText(warehouseCode)) {
            warehouseCode = generateWarehouseCode();
        } else {
            // 如果用户提供了编码，验证是否已存在
            Warehouse existingWarehouse = warehouseMapper.selectByWarehouseCode(warehouseCode);
            if (existingWarehouse != null) {
                return AjaxResult.error("中转仓编码已存在");
            }
        }

        // 创建中转仓实体
        Warehouse warehouse = new Warehouse();
        BeanUtils.copyProperties(dto, warehouse);
        warehouse.setWarehouseCode(warehouseCode);
        
        // 设置默认状态
        if (warehouse.getStatus() == null) {
            warehouse.setStatus(1); // 默认启用
        }

        // 设置创建人和创建时间
        Integer userId = SecurityUtil.getCurrentUserId();
        warehouse.setCreatedBy(userId);
        warehouse.setCreateTime(new Date());

        try {
            // 插入数据库
            int result = warehouseMapper.insert(warehouse);

            if (result > 0) {
                return AjaxResult.success("新增中转仓成功");
            } else {
                return AjaxResult.error("新增中转仓失败");
            }
        } catch (DuplicateKeyException e) {
            String errorMessage = e.getMessage();
            if (errorMessage != null && errorMessage.contains("warehouse_code")) {
                return AjaxResult.error("中转仓编码已存在，请使用其他编码");
            }
            return AjaxResult.error("数据重复：" + errorMessage);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("新增中转仓失败：" + e.getMessage());
        }
    }

    /**
     * 更新中转仓信息
     */
    @Override
    @Transactional
    public AjaxResult updateWarehouse(WarehouseEditDto dto) {
        if (dto.getId() == null) {
            return AjaxResult.error("中转仓ID不能为空");
        }

        // 验证中转仓是否存在
        Warehouse existingWarehouse = warehouseMapper.selectById(dto.getId());
        if (existingWarehouse == null) {
            return AjaxResult.error("中转仓不存在");
        }

        // 验证中转仓编码唯一性（排除当前记录）
        Warehouse codeWarehouse = warehouseMapper.selectByWarehouseCode(dto.getWarehouseCode());
        if (codeWarehouse != null && !codeWarehouse.getId().equals(dto.getId())) {
            return AjaxResult.error("中转仓编码已存在");
        }

        // 更新中转仓信息
        Warehouse warehouse = new Warehouse();
        BeanUtils.copyProperties(dto, warehouse);

        // 设置更新人和更新时间
        Integer userId = SecurityUtil.getCurrentUserId();
        warehouse.setUpdatedBy(userId);
        warehouse.setUpdateTime(new Date());

        try {
            // 更新数据库
            int result = warehouseMapper.updateById(warehouse);

            if (result > 0) {
                return AjaxResult.success("更新中转仓成功");
            } else {
                return AjaxResult.error("更新中转仓失败");
            }
        } catch (DuplicateKeyException e) {
            String errorMessage = e.getMessage();
            if (errorMessage != null && errorMessage.contains("warehouse_code")) {
                return AjaxResult.error("中转仓编码已存在，请使用其他编码");
            }
            return AjaxResult.error("数据重复：" + errorMessage);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("更新中转仓失败：" + e.getMessage());
        }
    }

    /**
     * 删除中转仓（逻辑删除）
     */
    @Override
    @Transactional
    public AjaxResult deleteWarehouse(Integer id) {
        if (id == null) {
            return AjaxResult.error("中转仓ID不能为空");
        }

        // 查询中转仓是否存在
        Warehouse warehouse = warehouseMapper.selectById(id);
        if (warehouse == null) {
            return AjaxResult.error("中转仓不存在");
        }

        // 获取当前用户ID
        Integer userId = SecurityUtil.getCurrentUserId();

        // 直接使用 SQL 更新，不依赖 @TableLogic
        UpdateWrapper<Warehouse> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id)
                    .eq("is_delete", 0); // 只更新未删除的记录

        updateWrapper.set("is_delete", 1)
                    .set("updated_by", userId)
                    .set("update_time", new Date());

        int result = warehouseMapper.update(null, updateWrapper);

        if (result > 0) {
            return AjaxResult.success("删除中转仓成功");
        } else {
            return AjaxResult.error("删除中转仓失败");
        }
    }

    /**
     * 获取中转仓详情
     */
    @Override
    public AjaxResult getWarehouseDetail(Integer id) {
        if (id == null) {
            return AjaxResult.error("中转仓ID不能为空");
        }

        Warehouse warehouse = warehouseMapper.selectById(id);
        if (warehouse == null || (warehouse.getIsDelete() != null && warehouse.getIsDelete() == 1)) {
            return AjaxResult.error("中转仓不存在");
        }

        return AjaxResult.success("查询成功", warehouse);
    }

    /**
     * 获取所有启用的中转仓（下拉选择用）
     */
    @Override
    public List<Warehouse> getAllEnabled() {
        return warehouseMapper.selectAllEnabled();
    }

    /**
     * 生成中转仓编码：WH + 4位流水号
     */
    private String generateWarehouseCode() {
        // 查询当前最大编码
        LambdaQueryWrapper<Warehouse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.likeRight(Warehouse::getWarehouseCode, "WH");
        queryWrapper.orderByDesc(Warehouse::getWarehouseCode);
        queryWrapper.last("LIMIT 1");
        
        Warehouse lastWarehouse = warehouseMapper.selectOne(queryWrapper);
        
        if (lastWarehouse != null && lastWarehouse.getWarehouseCode() != null) {
            String lastCode = lastWarehouse.getWarehouseCode();
            if (lastCode.startsWith("WH")) {
                try {
                    String numStr = lastCode.substring(2);
                    int num = Integer.parseInt(numStr);
                    return String.format("WH%04d", num + 1);
                } catch (NumberFormatException e) {
                    // 如果解析失败，从1开始
                }
            }
        }
        
        // 如果没有找到，从0001开始
        return "WH0001";
    }
}

