package com.haha.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haha.common.exception.BusinessException;
import com.haha.entity.StockRecord;
import com.haha.mapper.StockRecordMapper;
import com.haha.service.StockRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * 上货记录服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class StockRecordServiceImpl extends ServiceImpl<StockRecordMapper, StockRecord>
        implements StockRecordService {

    private final StockRecordMapper stockRecordMapper;

    @Override
    public IPage<StockRecord> getPage(int page, int pageSize, Map<String, Object> params) {
        LambdaQueryWrapper<StockRecord> wrapper = new LambdaQueryWrapper<>();

        // 设备ID筛选
        String deviceId = (String) params.get("deviceId");
        if (StringUtils.hasText(deviceId)) {
            wrapper.eq(StockRecord::getDeviceId, deviceId);
        }

        // 上货员筛选
        Object stockerId = params.get("stockerId");
        if (stockerId != null) {
            wrapper.eq(StockRecord::getStockerId, stockerId);
        }

        // 类型筛选
        Object stockType = params.get("stockType");
        if (stockType != null) {
            wrapper.eq(StockRecord::getStockType, stockType);
        }

        // 状态筛选
        Object status = params.get("status");
        if (status != null) {
            wrapper.eq(StockRecord::getStatus, status);
        }

        // 时间范围
        String startTime = (String) params.get("startTime");
        String endTime = (String) params.get("endTime");
        if (StringUtils.hasText(startTime)) {
            wrapper.ge(StockRecord::getCreateTime, LocalDateTime.parse(startTime + "T00:00:00"));
        }
        if (StringUtils.hasText(endTime)) {
            wrapper.le(StockRecord::getCreateTime, LocalDateTime.parse(endTime + "T23:59:59"));
        }

        // 按创建时间倒序
        wrapper.orderByDesc(StockRecord::getCreateTime);

        return page(new Page<>(page, pageSize), wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public StockRecord createRecord(String deviceId, Integer stockType, Long stockerId,
                                    String stockerName, String stockerPhone, String remark) {
        StockRecord record = new StockRecord();
        record.setDeviceId(deviceId);
        record.setStockType(stockType);
        record.setStockerId(stockerId);
        record.setStockerName(stockerName);
        record.setStockerPhone(stockerPhone);
        record.setStatus(1); // 进行中
        record.setTotalItems(0);
        record.setTotalQuantity(0);
        record.setRemark(remark);
        record.setCreateTime(LocalDateTime.now());
        record.setUpdateTime(LocalDateTime.now());

        save(record);

        log.info("创建上货记录: id={}, deviceId={}, stockerName={}", record.getId(), deviceId, stockerName);

        return record;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void startActivity(Long recordId) {
        StockRecord record = getById(recordId);
        if (record == null) {
            throw new BusinessException(404, "上货记录不存在");
        }

        record.setStatus(1); // 进行中
        record.setStartTime(LocalDateTime.now());
        record.setUpdateTime(LocalDateTime.now());
        updateById(record);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void completeActivity(Long recordId, Integer totalItems, Integer totalQuantity, String activityId) {
        StockRecord record = getById(recordId);
        if (record == null) {
            throw new BusinessException(404, "上货记录不存在");
        }

        record.setStatus(2); // 已完成
        record.setActivityId(activityId);
        record.setTotalItems(totalItems);
        record.setTotalQuantity(totalQuantity);
        record.setEndTime(LocalDateTime.now());
        record.setUpdateTime(LocalDateTime.now());
        updateById(record);

        log.info("完成上货记录: id={}, totalItems={}, totalQuantity={}", recordId, totalItems, totalQuantity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelActivity(Long recordId) {
        StockRecord record = getById(recordId);
        if (record == null) {
            throw new BusinessException(404, "上货记录不存在");
        }

        record.setStatus(3); // 已取消
        record.setEndTime(LocalDateTime.now());
        record.setUpdateTime(LocalDateTime.now());
        updateById(record);

        log.info("取消上货记录: id={}", recordId);
    }

    @Override
    public Map<String, Object> getStockerStatistics(Long stockerId, String startTime, String endTime) {
        return stockRecordMapper.selectStockerStatistics(stockerId, startTime, endTime);
    }

    @Override
    public Map<String, Object> getDetailWithDeviceName(Long id) {
        return stockRecordMapper.selectWithDeviceName(id);
    }
}
