package com.fizz.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fizz.business.domain.CrmPdoExcoil;
import com.fizz.business.form.CrmPdoExcoilForm;
import com.fizz.business.mapper.CrmPdoExcoilMapper;
import com.fizz.business.service.CrmPdoExcoilService;
import com.fizz.business.vo.ReportDetailVO;
import com.fizz.business.vo.ReportSummaryVO;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class CrmPdoExcoilServiceImpl extends ServiceImpl<CrmPdoExcoilMapper, CrmPdoExcoil> implements CrmPdoExcoilService {

    /**
     * 根据退出卷ID和操作员ID查询记录
     *
     * @param excoilid 退出卷ID
     * @return 查询到的CrmPdoExcoil对象
     */
    public CrmPdoExcoil getByExcoilId(String excoilid) {
        QueryWrapper<CrmPdoExcoil> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("exit_mat_id", excoilid);
        return this.getOne(queryWrapper);
    }

    /**
     * 添加新记录
     *
     * @param crmPdoExcoil 要添加的CrmPdoExcoil对象
     * @return 是否添加成功
     */
    public boolean addCrmPdoExcoil(CrmPdoExcoil crmPdoExcoil) {
        return this.save(crmPdoExcoil);
    }

    /**
     * 更新已有记录
     *
     * @param crmPdoExcoil 要更新的CrmPdoExcoil对象
     * @return 是否更新成功
     */
    public boolean updateCrmPdoExcoil(CrmPdoExcoil crmPdoExcoil) {
        return this.updateById(crmPdoExcoil);
    }

    /**
     * 根据退出卷ID和操作员ID删除记录
     *
     * @param excoilid 退出卷ID
     * @param planId   操作员ID
     * @return 是否删除成功
     */
    public boolean deleteCrmPdoExcoil(String excoilid, String planId) {
        QueryWrapper<CrmPdoExcoil> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("exit_mat_id", excoilid).eq("plan_id", planId);
        return this.remove(queryWrapper);
    }

    /**
     * 查询所有记录
     *
     * @return CrmPdoExcoil对象的列表
     */
    public List<CrmPdoExcoil> listAll(CrmPdoExcoilForm form) {

        QueryWrapper<CrmPdoExcoil> queryWrapper = new QueryWrapper<>();

        // 根据 exit_coilid 和 encoilid 进行查询
        if (!StringUtils.isEmpty(form.getCoilid())) {
            queryWrapper.like("exit_mat_id", form.getCoilid());

            return baseMapper.selectList(queryWrapper);
        }

        if (!StringUtils.isEmpty(form.getStartDate())&& !StringUtils.isEmpty(form.getEndDate())){
            queryWrapper.ge("start_time", form.getStartDate() + " 00:00:00");
            queryWrapper.le("end_time", form.getEndDate() + " 23:59:59");
        }

        queryWrapper.orderByDesc("end_time");
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public Long getNumber(String matId, String planId, Integer subNumber) {

        LambdaQueryWrapper<CrmPdoExcoil> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CrmPdoExcoil::getEntryMatId,matId);
        queryWrapper.eq(CrmPdoExcoil::getPlanId,planId);
        queryWrapper.eq(CrmPdoExcoil::getSubId,subNumber);

        return baseMapper.selectCount(queryWrapper);
    }

    @Override
    public ReportSummaryVO getReportSummary(String groupNo, String shiftNo, LocalDateTime startTime, LocalDateTime endTime) {
        return baseMapper.getReportSummary(groupNo, shiftNo, startTime, endTime);
    }

    @Override
    public List<ReportDetailVO> getReportDetails(String groupNo, String shiftNo, LocalDateTime startTime, LocalDateTime endTime) {
        return baseMapper.getReportDetails(groupNo, shiftNo, startTime, endTime);
    }

    /**
     * 【新增实现】
     * 负责更新产出卷的实际重量和状态。
     */
    @Override
    @Transactional
    public void updateExitCoilActualWeight(String exitMatId, BigDecimal actualWeight) {
        // 1. 根据成品卷号查询记录
        CrmPdoExcoil excoil = this.getByExcoilId(exitMatId);

        if (excoil == null) {
            log.error("未找到成品卷 {} 的数据库记录，无法更新重量。", exitMatId);
            return;
        }

        // 2. 检查当前状态是否为 "UNWEIGHT" (未称重)
        // 确保我们只更新未处理过的卷
        if (Objects.equals(excoil.getStatus(), "UNWEIGHT")) {
            // 3. 更新实际重量和状态
            excoil.setActualWeight(actualWeight.doubleValue());
            excoil.setStatus("COMPLETED"); // 或其他最终状态，如 "WEIGHED"

            // 4. 调用 CRM 服务进行数据库更新
            boolean success = this.updateCrmPdoExcoil(excoil);

            if (success) {
                log.info("成品卷 {} 的实际重量已成功更新为 {} kg，状态变为 {}.",
                        exitMatId, actualWeight, excoil.getStatus());
            } else {
                log.error("更新成品卷 {} 失败。", exitMatId);
            }
        } else {
            log.warn("成品卷 {} 的状态不是 'UNWEIGHT'，当前状态为 '{}'，跳过重量更新。",
                    exitMatId, excoil.getStatus());
        }
    }

}
