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

import com.aiotagro.cattletrade.business.dto.WarehouseInCreateDto;
import com.aiotagro.cattletrade.business.dto.WarehouseInDto;
import com.aiotagro.cattletrade.business.dto.WarehouseInEditDto;
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.mapper.DeliveryMapper;
import com.aiotagro.cattletrade.business.mapper.WarehouseInMapper;
import com.aiotagro.cattletrade.business.mapper.WarehouseMapper;
import com.aiotagro.cattletrade.business.service.IWarehouseInService;
import com.aiotagro.cattletrade.business.vo.WarehouseInVo;
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 WarehouseInServiceImpl extends ServiceImpl<WarehouseInMapper, WarehouseIn> implements IWarehouseInService {

    @Autowired
    private WarehouseInMapper warehouseInMapper;

    @Autowired
    private WarehouseMapper warehouseMapper;

    @Autowired
    private DeliveryMapper deliveryMapper;

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

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

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

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

        queryWrapper.orderByDesc(WarehouseIn::getCreateTime);

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

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

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

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

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

            voList.add(vo);
        }

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

    /**
     * 新增进仓记录
     */
    @Override
    @Transactional
    public AjaxResult addWarehouseIn(WarehouseInCreateDto 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("中转仓未启用，无法进仓");
        }

        // 生成进仓单号：IN + 年月日 + 4位流水号
        String inNumber = generateInNumber();

        // 创建进仓实体
        WarehouseIn warehouseIn = new WarehouseIn();
        BeanUtils.copyProperties(dto, warehouseIn);
        warehouseIn.setInNumber(inNumber);
        warehouseIn.setStatus(1); // 默认待进仓

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

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

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

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

        // 验证进仓记录是否存在
        WarehouseIn existingWarehouseIn = warehouseInMapper.selectById(dto.getId());
        if (existingWarehouseIn == 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("中转仓未启用");
        }

        // 更新进仓信息
        WarehouseIn warehouseIn = new WarehouseIn();
        BeanUtils.copyProperties(dto, warehouseIn);

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

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

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

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

        // 查询进仓记录是否存在
        WarehouseIn warehouseIn = warehouseInMapper.selectById(id);
        if (warehouseIn == null) {
            return AjaxResult.error("进仓记录不存在");
        }

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

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

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

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

        WarehouseIn warehouseIn = warehouseInMapper.selectById(id);
        if (warehouseIn == null || (warehouseIn.getIsDelete() != null && warehouseIn.getIsDelete() == 1)) {
            return AjaxResult.error("进仓记录不存在");
        }

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

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

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

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

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

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

        // 查询当天最大流水号
        Integer maxSequence = warehouseInMapper.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 "已进仓";
            case 3:
                return "已出仓";
            default:
                return "未知";
        }
    }
}

