package org.dromara.zhishu.service.impl;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.dromara.zhishu.domain.WaveDetail;
import org.dromara.zhishu.domain.dto.WaveDetailRequestDto;
import org.dromara.zhishu.domain.vo.EmployeeInfoVo;
import org.dromara.zhishu.mapper.WaveDetailMapper;
import org.dromara.zhishu.service.IWaveDetailService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 波次信息Service业务层处理
 *
 * @author Lion Li
 * @date 2026-01-22
 */
@RequiredArgsConstructor
@Service
public class WaveDetailServiceImpl implements IWaveDetailService {

    private final WaveDetailMapper waveDetailMapper;

    /**
     * 新增波次信息
     *
     * @param requestDto 波次信息请求DTO
     * @return 是否新增成功
     */
    @Override
        public Boolean insertWaveDetail(String userId, WaveDetailRequestDto requestDto) {
            // 获取当前时间戳
        long currentTime = System.currentTimeMillis() / 1000;
        
        // 遍历ISBN列表，创建WaveDetail实体并保存
        List<WaveDetail> waveDetailList = new ArrayList<>();
        for (WaveDetailRequestDto.IsbnDto isbnDto : requestDto.getIsbnList()) {
            
            // 获取仓库id
            String shipmentId = requestDto.getShipmentId();
            Long stockId = parseShipmentId(userId, shipmentId);

            WaveDetail waveDetail = new WaveDetail();
            waveDetail.setUserId(Long.valueOf(userId));
            waveDetail.setWaveId(requestDto.getWaveId());
            waveDetail.setIsbn(isbnDto.getIsbn());
            waveDetail.setQuality(isbnDto.getQuality());
            waveDetail.setStockId(stockId);
            // shipmentId作为stockNum存储
            waveDetail.setStockNum(requestDto.getShipmentId());
            waveDetail.setCreatedTime(currentTime);
            waveDetail.setUpdatedTime(currentTime);
            waveDetail.setIsDel(0L); // 默认未删除
            waveDetailList.add(waveDetail);
        }
        
        // 批量插入数据库
        if (!waveDetailList.isEmpty()) {
            return waveDetailMapper.insertBatch(waveDetailList) > 0;
        }
        
        return false;
    }

    @Override
    public Long getWaveID() {
        return waveDetailMapper.getWaveId();
    }

    @Override
    public String getEmployeeId(String name, String userId) {
        return waveDetailMapper.getEmployeeId(name, userId);
    }

    @Override
    public Boolean countVerWave(String waveId, String employeeId, Integer submitCount) {

        Long timestamp = System.currentTimeMillis() / 1000;

        // 从wave_employee表查询员工姓名
        Map<String, String> staffInfo = waveDetailMapper.getWaveEmployeeName(employeeId);


        // 插入employeeInfo记录
        EmployeeInfoVo employeeInfo = new EmployeeInfoVo();

        String name = staffInfo.get("name");
        String userId = staffInfo.get("user_id");


        employeeInfo.setEmployeeId(employeeId); // 设置员工ID
        employeeInfo.setName(name); // 使用从wave_employee表获取的员工姓名
        employeeInfo.setUserId(Long.valueOf(staffInfo.get("user_id").toString()));
        employeeInfo.setWave(waveId);
        employeeInfo.setCount(submitCount);
        employeeInfo.setCreatedTime(timestamp);
        employeeInfo.setUpdatedTime(timestamp);
        employeeInfo.setDelFlag(0);

        long insertResult = waveDetailMapper.insertEmployeeInfo(employeeInfo);
        if (insertResult <= 0) {
            return false;
        }

        // 从employeeInfo表统计count的和
        Long countSum = waveDetailMapper.getEmployeeInfoCountSum(userId, waveId);
        if (countSum == null) {
            countSum = 0L;
        }

        // 检查wave表中是否存在记录
        int exists = waveDetailMapper.checkWaveExists(employeeId, userId);
        if (exists > 0) {
            // 如果存在，更新count
            int updateResult = waveDetailMapper.updateWaveCount(employeeId, userId, countSum, timestamp);
            return updateResult > 0;
        } else {
            // 如果不存在，新增一条数据
            int insertWaveResult = waveDetailMapper.insertWave(employeeId, name, employeeId, countSum, timestamp, timestamp);
            return insertWaveResult > 0;
        }
    }

    /**
     * 解析shipmentId，获取一、二、三级货区号
     * @param shipmentId 货号
     */
    private Long parseShipmentId(String userId, String shipmentId) {
        if (shipmentId != null && shipmentId.length() == 5) {
            // 一级货区：前2位
            String firstLevel = shipmentId.substring(0, 2);

            char thirdChar = shipmentId.charAt(2);
            String secondLevel;
            String thirdLevel;

            if (Character.isDigit(thirdChar)) {
                // 第三位是数字：第三位是二级货区，第四五位是三级货区
                secondLevel = shipmentId.substring(2, 3);
                thirdLevel = shipmentId.substring(3, 5);
            } else {
                // 第三位是字母：第三四位是二级货区，第五位是三级货区
                secondLevel = shipmentId.substring(2, 4);
                thirdLevel = shipmentId.substring(4, 5);
            }

            return waveDetailMapper.getFreightId(userId, firstLevel, secondLevel, thirdLevel);
        }
        return null;
    }

}
