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

import com.aiotagro.cattletrade.business.dto.SlaughterEntryCreateDto;
import com.aiotagro.cattletrade.business.dto.SlaughterEntryDto;
import com.aiotagro.cattletrade.business.dto.SlaughterEntryEditDto;
import com.aiotagro.cattletrade.business.entity.Delivery;
import com.aiotagro.cattletrade.business.entity.Order;
import com.aiotagro.cattletrade.business.entity.SlaughterEntry;
import com.aiotagro.cattletrade.business.entity.SlaughterHouse;
import com.aiotagro.cattletrade.business.mapper.DeliveryMapper;
import com.aiotagro.cattletrade.business.mapper.OrderMapper;
import com.aiotagro.cattletrade.business.mapper.SlaughterEntryMapper;
import com.aiotagro.cattletrade.business.mapper.SlaughterHouseMapper;
import com.aiotagro.cattletrade.business.service.ISlaughterEntryService;
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 进场管理服务实现
 *
 * @author System
 * @date 2025-12-09
 */
@Service
public class SlaughterEntryServiceImpl extends ServiceImpl<SlaughterEntryMapper, SlaughterEntry> implements ISlaughterEntryService {

    @Autowired
    private SlaughterEntryMapper slaughterEntryMapper;
    @Autowired
    private SlaughterHouseMapper slaughterHouseMapper;
    @Autowired
    private DeliveryMapper deliveryMapper;
    @Autowired
    private OrderMapper orderMapper;

    @Override
    public PageResultResponse<SlaughterEntry> pageQuery(SlaughterEntryDto dto) {
        Integer pageNum = dto.getPageNum() != null ? dto.getPageNum() : 1;
        Integer pageSize = dto.getPageSize() != null ? dto.getPageSize() : 10;

        Page<SlaughterEntry> page = PageHelper.startPage(pageNum, pageSize);

        LambdaQueryWrapper<SlaughterEntry> wrapper = new LambdaQueryWrapper<>();
        wrapper.and(q -> q.eq(SlaughterEntry::getIsDelete, 0).or().isNull(SlaughterEntry::getIsDelete));

        if (dto.getSlaughterHouseId() != null) {
            wrapper.eq(SlaughterEntry::getSlaughterHouseId, dto.getSlaughterHouseId());
        }
        if (dto.getDeliveryId() != null) {
            wrapper.eq(SlaughterEntry::getDeliveryId, dto.getDeliveryId());
        }
        if (dto.getOrderId() != null) {
            wrapper.eq(SlaughterEntry::getOrderId, dto.getOrderId());
        }

        wrapper.orderByDesc(SlaughterEntry::getCreateTime);

        List<SlaughterEntry> list = slaughterEntryMapper.selectList(wrapper);
        return new PageResultResponse<>(page.getTotal(), list);
    }

    @Override
    @Transactional
    public AjaxResult addEntry(SlaughterEntryCreateDto dto) {
        AjaxResult validateResult = validateRelation(dto.getSlaughterHouseId(), dto.getDeliveryId(), dto.getOrderId());
        if (validateResult != null) {
            return validateResult;
        }

        SlaughterEntry entry = new SlaughterEntry();
        BeanUtils.copyProperties(dto, entry);

        Integer userId = SecurityUtil.getCurrentUserId();
        entry.setCreatedBy(userId);
        entry.setCreateTime(new Date());

        int inserted = slaughterEntryMapper.insert(entry);
        return inserted > 0 ? AjaxResult.success("新增进场记录成功") : AjaxResult.error("新增进场记录失败");
    }

    @Override
    @Transactional
    public AjaxResult updateEntry(SlaughterEntryEditDto dto) {
        if (dto.getId() == null) {
            return AjaxResult.error("进场记录ID不能为空");
        }
        SlaughterEntry existing = slaughterEntryMapper.selectById(dto.getId());
        if (existing == null || (existing.getIsDelete() != null && existing.getIsDelete() == 1)) {
            return AjaxResult.error("进场记录不存在");
        }

        AjaxResult validateResult = validateRelation(dto.getSlaughterHouseId(), dto.getDeliveryId(), dto.getOrderId());
        if (validateResult != null) {
            return validateResult;
        }

        SlaughterEntry entry = new SlaughterEntry();
        BeanUtils.copyProperties(dto, entry);

        Integer userId = SecurityUtil.getCurrentUserId();
        entry.setUpdatedBy(userId);
        entry.setUpdateTime(new Date());

        int updated = slaughterEntryMapper.updateById(entry);
        return updated > 0 ? AjaxResult.success("更新进场记录成功") : AjaxResult.error("更新进场记录失败");
    }

    @Override
    @Transactional
    public AjaxResult deleteEntry(Integer id) {
        if (id == null) {
            return AjaxResult.error("进场记录ID不能为空");
        }
        SlaughterEntry entry = slaughterEntryMapper.selectById(id);
        if (entry == null || (entry.getIsDelete() != null && entry.getIsDelete() == 1)) {
            return AjaxResult.error("进场记录不存在");
        }

        Integer userId = SecurityUtil.getCurrentUserId();
        UpdateWrapper<SlaughterEntry> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", id).eq("is_delete", 0)
                .set("is_delete", 1)
                .set("updated_by", userId)
                .set("update_time", new Date());

        int result = slaughterEntryMapper.update(null, wrapper);
        return result > 0 ? AjaxResult.success("删除进场记录成功") : AjaxResult.error("删除进场记录失败");
    }

    @Override
    public AjaxResult detail(Integer id) {
        if (id == null) {
            return AjaxResult.error("进场记录ID不能为空");
        }
        SlaughterEntry entry = slaughterEntryMapper.selectById(id);
        if (entry == null || (entry.getIsDelete() != null && entry.getIsDelete() == 1)) {
            return AjaxResult.error("进场记录不存在");
        }
        return AjaxResult.success("查询成功", entry);
    }

    /**
     * 校验关联的屠宰场、运送清单、订单是否存在
     */
    private AjaxResult validateRelation(Integer houseId, Integer deliveryId, Integer orderId) {
        SlaughterHouse house = slaughterHouseMapper.selectById(houseId);
        if (house == null || (house.getIsDelete() != null && house.getIsDelete() == 1)) {
            return AjaxResult.error("屠宰场不存在");
        }

        Delivery delivery = deliveryMapper.selectById(deliveryId);
        if (delivery == null) {
            return AjaxResult.error("运送清单不存在");
        }

        if (orderId != null) {
            Order order = orderMapper.selectById(orderId);
            if (order == null || (order.getIsDelete() != null && order.getIsDelete() == 1)) {
                return AjaxResult.error("订单不存在");
            }
        }
        return null;
    }
}

