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

import com.aiotagro.cattletrade.business.dto.WarehouseOutCreateDto;
import com.aiotagro.cattletrade.business.dto.WarehouseOutDto;
import com.aiotagro.cattletrade.business.dto.WarehouseOutEditDto;
import com.aiotagro.cattletrade.business.entity.Delivery;
import com.aiotagro.cattletrade.business.entity.Warehouse;
import com.aiotagro.cattletrade.business.entity.WarehouseIn;
import com.aiotagro.cattletrade.business.entity.WarehouseOut;
import com.aiotagro.cattletrade.business.mapper.DeliveryMapper;
import com.aiotagro.cattletrade.business.mapper.WarehouseInMapper;
import com.aiotagro.cattletrade.business.mapper.WarehouseMapper;
import com.aiotagro.cattletrade.business.mapper.WarehouseOutMapper;
import com.aiotagro.cattletrade.business.service.IWarehouseOutService;
import com.aiotagro.cattletrade.business.vo.WarehouseOutVo;
import com.aiotagro.common.core.utils.SecurityUtil;
import com.aiotagro.common.core.utils.StringUtils;
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 java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 出仓管理服务实现类
 *
 * @author System
 * @date 2025-01-20
 */
@Service
public class WarehouseOutServiceImpl extends ServiceImpl<WarehouseOutMapper, WarehouseOut> implements IWarehouseOutService {

    @Autowired
    private WarehouseOutMapper warehouseOutMapper;

    @Autowired
    private WarehouseMapper warehouseMapper;

    @Autowired
    private WarehouseInMapper warehouseInMapper;

    @Autowired
    private DeliveryMapper deliveryMapper;

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

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

        // 构建查询条件
        LambdaQueryWrapper<WarehouseOut> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.and(wrapper -> wrapper.eq(WarehouseOut::getIsDelete, 0).or().isNull(WarehouseOut::getIsDelete));

        if (StringUtils.isNotEmpty(dto.getOutNumber())) {
            queryWrapper.like(WarehouseOut::getOutNumber, dto.getOutNumber());
        }
        if (dto.getWarehouseId() != null) {
            queryWrapper.eq(WarehouseOut::getWarehouseId, dto.getWarehouseId());
        }
        if (dto.getWarehouseInId() != null) {
            queryWrapper.eq(WarehouseOut::getWarehouseInId, dto.getWarehouseInId());
        }
        if (dto.getDeliveryId() != null) {
            queryWrapper.eq(WarehouseOut::getDeliveryId, dto.getDeliveryId());
        }
        if (dto.getStatus() != null) {
            queryWrapper.eq(WarehouseOut::getStatus, dto.getStatus());
        }
        if (StringUtils.isNotEmpty(dto.getStartTime())) {
            queryWrapper.ge(WarehouseOut::getOutTime, dto.getStartTime() + " 00:00:00");
        }
        if (StringUtils.isNotEmpty(dto.getEndTime())) {
            queryWrapper.le(WarehouseOut::getOutTime, dto.getEndTime() + " 23:59:59");
        }

        queryWrapper.orderByDesc(WarehouseOut::getCreateTime);

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

        // 转换为VO并填充关联信息
        List<WarehouseOutVo> voList = new ArrayList<>();
        for (WarehouseOut warehouseOut : list) {
            WarehouseOutVo vo = new WarehouseOutVo();
            BeanUtils.copyProperties(warehouseOut, vo);

            // 关联查询中转仓名称
            if (warehouseOut.getWarehouseId() != null) {
                Warehouse warehouse = warehouseMapper.selectById(warehouseOut.getWarehouseId());
                if (warehouse != null) {
                    vo.setWarehouseName(warehouse.getWarehouseName());
                }
            }

            // 关联查询进仓记录
            if (warehouseOut.getWarehouseInId() != null) {
                WarehouseIn warehouseIn = warehouseInMapper.selectById(warehouseOut.getWarehouseInId());
                if (warehouseIn != null) {
                    vo.setWarehouseInNumber(warehouseIn.getInNumber());
                }
            }

            // 关联查询运送清单信息（车牌号、司机信息等）
            if (warehouseOut.getDeliveryId() != null) {
                Delivery delivery = deliveryMapper.selectById(warehouseOut.getDeliveryId());
                if (delivery != null) {
                    vo.setDeliveryNumber(delivery.getDeliveryNumber());
                    vo.setLicensePlate(delivery.getLicensePlate());
                    vo.setDriverName(delivery.getDriverName());
                    vo.setDriverMobile(delivery.getDriverMobile());
                }
            }

            // 设置状态描述
            vo.setStatusDesc(getStatusDesc(warehouseOut.getStatus()));

            voList.add(vo);
        }

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

    /**
     * 新增出仓记录
     */
    @Override
    @Transactional
    public AjaxResult addWarehouseOut(WarehouseOutCreateDto dto) {
        // 校验中转仓是否存在且启用
        Warehouse warehouse = warehouseMapper.selectById(dto.getWarehouseId());
        if (warehouse == null || (warehouse.getIsDelete() != null && warehouse.getIsDelete() == 1)) {
            return AjaxResult.error("中转仓不存在");
        }
        if (warehouse.getStatus() == null || warehouse.getStatus() == 0) {
            return AjaxResult.error("中转仓未启用，无法出仓");
        }

        // 如果关联了进仓记录，校验进仓记录是否存在
        if (dto.getWarehouseInId() != null) {
            WarehouseIn warehouseIn = warehouseInMapper.selectById(dto.getWarehouseInId());
            if (warehouseIn == null || (warehouseIn.getIsDelete() != null && warehouseIn.getIsDelete() == 1)) {
                return AjaxResult.error("进仓记录不存在");
            }
            // 校验出仓数量不能超过进仓数量
            if (dto.getCattleCount() > warehouseIn.getCattleCount()) {
                return AjaxResult.error("出仓数量不能超过进仓数量");
            }
        }

        // 生成出仓单号：OUT + 年月日 + 4位流水号
        String outNumber = generateOutNumber();

        // 创建出仓实体
        WarehouseOut warehouseOut = new WarehouseOut();
        BeanUtils.copyProperties(dto, warehouseOut);
        warehouseOut.setOutNumber(outNumber);
        warehouseOut.setStatus(1); // 默认待出仓

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

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

            if (result > 0) {
                return AjaxResult.success("新增出仓记录成功", warehouseOut);
            } else {
                return AjaxResult.error("新增出仓记录失败");
            }
        } catch (DuplicateKeyException e) {
            String errorMessage = e.getMessage();
            if (errorMessage != null && errorMessage.contains("out_number")) {
                return AjaxResult.error("出仓单号已存在，请重试");
            }
            return AjaxResult.error("数据重复：" + errorMessage);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("新增出仓记录失败：" + e.getMessage());
        }
    }

    /**
     * 更新出仓记录
     */
    @Override
    @Transactional
    public AjaxResult updateWarehouseOut(WarehouseOutEditDto dto) {
        if (dto.getId() == null) {
            return AjaxResult.error("出仓记录ID不能为空");
        }

        // 验证出仓记录是否存在
        WarehouseOut existingWarehouseOut = warehouseOutMapper.selectById(dto.getId());
        if (existingWarehouseOut == null) {
            return AjaxResult.error("出仓记录不存在");
        }

        // 校验中转仓是否存在且启用
        Warehouse warehouse = warehouseMapper.selectById(dto.getWarehouseId());
        if (warehouse == null || (warehouse.getIsDelete() != null && warehouse.getIsDelete() == 1)) {
            return AjaxResult.error("中转仓不存在");
        }
        if (warehouse.getStatus() == null || warehouse.getStatus() == 0) {
            return AjaxResult.error("中转仓未启用");
        }

        // 如果关联了进仓记录，校验进仓记录是否存在
        if (dto.getWarehouseInId() != null) {
            WarehouseIn warehouseIn = warehouseInMapper.selectById(dto.getWarehouseInId());
            if (warehouseIn == null || (warehouseIn.getIsDelete() != null && warehouseIn.getIsDelete() == 1)) {
                return AjaxResult.error("进仓记录不存在");
            }
            // 校验出仓数量不能超过进仓数量
            if (dto.getCattleCount() > warehouseIn.getCattleCount()) {
                return AjaxResult.error("出仓数量不能超过进仓数量");
            }
        }

        // 更新出仓信息
        WarehouseOut warehouseOut = new WarehouseOut();
        BeanUtils.copyProperties(dto, warehouseOut);

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

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

            if (result > 0) {
                return AjaxResult.success("更新出仓记录成功");
            } else {
                return AjaxResult.error("更新出仓记录失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("更新出仓记录失败：" + e.getMessage());
        }
    }

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

        // 查询出仓记录是否存在
        WarehouseOut warehouseOut = warehouseOutMapper.selectById(id);
        if (warehouseOut == null) {
            return AjaxResult.error("出仓记录不存在");
        }

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

        // 直接使用 SQL 更新，不依赖 @TableLogic
        UpdateWrapper<WarehouseOut> 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 = warehouseOutMapper.update(null, updateWrapper);

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

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

        WarehouseOut warehouseOut = warehouseOutMapper.selectById(id);
        if (warehouseOut == null || (warehouseOut.getIsDelete() != null && warehouseOut.getIsDelete() == 1)) {
            return AjaxResult.error("出仓记录不存在");
        }

        // 转换为VO并填充关联信息
        WarehouseOutVo vo = new WarehouseOutVo();
        BeanUtils.copyProperties(warehouseOut, vo);

        // 关联查询中转仓名称
        if (warehouseOut.getWarehouseId() != null) {
            Warehouse warehouse = warehouseMapper.selectById(warehouseOut.getWarehouseId());
            if (warehouse != null) {
                vo.setWarehouseName(warehouse.getWarehouseName());
            }
        }

        // 关联查询进仓记录
        if (warehouseOut.getWarehouseInId() != null) {
            WarehouseIn warehouseIn = warehouseInMapper.selectById(warehouseOut.getWarehouseInId());
            if (warehouseIn != null) {
                vo.setWarehouseInNumber(warehouseIn.getInNumber());
            }
        }

        // 关联查询运送清单信息
        if (warehouseOut.getDeliveryId() != null) {
            Delivery delivery = deliveryMapper.selectById(warehouseOut.getDeliveryId());
            if (delivery != null) {
                vo.setDeliveryNumber(delivery.getDeliveryNumber());
                vo.setLicensePlate(delivery.getLicensePlate());
                vo.setDriverName(delivery.getDriverName());
                vo.setDriverMobile(delivery.getDriverMobile());
            }
        }

        // 设置状态描述
        vo.setStatusDesc(getStatusDesc(warehouseOut.getStatus()));

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

    /**
     * 生成出仓单号：OUT + 年月日 + 4位流水号（如：OUT202501200001）
     */
    private String generateOutNumber() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(new Date());
        String datePrefix = "OUT" + dateStr;

        // 查询当天最大流水号
        Integer maxSequence = warehouseOutMapper.getMaxSequenceByDate(datePrefix);
        if (maxSequence == null) {
            maxSequence = 0;
        }

        // 生成新的流水号
        int nextSequence = maxSequence + 1;
        return String.format("%s%04d", datePrefix, nextSequence);
    }

    /**
     * 获取状态描述
     */
    private String getStatusDesc(Integer status) {
        if (status == null) {
            return "未知";
        }
        switch (status) {
            case 1:
                return "待出仓";
            case 2:
                return "已出仓";
            default:
                return "未知";
        }
    }
}

