package com.aucma.production.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import com.aucma.common.exception.ServiceException;
import com.aucma.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.aucma.production.mapper.MrpProdWeeklyPlanMapper;
import com.aucma.production.domain.MrpProdWeeklyPlan;
import com.aucma.production.service.IMrpProdWeeklyPlanService;

/**
 * 周排产计划Service业务层处理
 * 
 * @author Yinq
 * @date 2026-01-05
 */
@Service
public class MrpProdWeeklyPlanServiceImpl implements IMrpProdWeeklyPlanService 
{
    @Autowired
    private MrpProdWeeklyPlanMapper mrpProdWeeklyPlanMapper;

    /**
     * 查询周排产计划
     * 
     * @param id 周排产计划主键
     * @return 周排产计划
     */
    @Override
    public MrpProdWeeklyPlan selectMrpProdWeeklyPlanById(Long id)
    {
        return mrpProdWeeklyPlanMapper.selectMrpProdWeeklyPlanById(id);
    }

    /**
     * 查询周排产计划列表
     * 
     * @param mrpProdWeeklyPlan 周排产计划
     * @return 周排产计划
     */
    @Override
    public List<MrpProdWeeklyPlan> selectMrpProdWeeklyPlanList(MrpProdWeeklyPlan mrpProdWeeklyPlan)
    {
        return mrpProdWeeklyPlanMapper.selectMrpProdWeeklyPlanList(mrpProdWeeklyPlan);
    }

    /**
     * 新增周排产计划
     * 
     * @param mrpProdWeeklyPlan 周排产计划
     * @return 结果
     */
    @Override
    public int insertMrpProdWeeklyPlan(MrpProdWeeklyPlan mrpProdWeeklyPlan)
    {
        return mrpProdWeeklyPlanMapper.insertMrpProdWeeklyPlan(mrpProdWeeklyPlan);
    }

    /**
     * 修改周排产计划
     * 
     * @param mrpProdWeeklyPlan 周排产计划
     * @return 结果
     */
    @Override
    public int updateMrpProdWeeklyPlan(MrpProdWeeklyPlan mrpProdWeeklyPlan)
    {
        return mrpProdWeeklyPlanMapper.updateMrpProdWeeklyPlan(mrpProdWeeklyPlan);
    }

    /**
     * 批量删除周排产计划
     * 
     * @param ids 需要删除的周排产计划主键
     * @return 结果
     */
    @Override
    public int deleteMrpProdWeeklyPlanByIds(Long[] ids)
    {
        return mrpProdWeeklyPlanMapper.deleteMrpProdWeeklyPlanByIds(ids);
    }

    /**
     * 删除周排产计划信息
     * 
     * @param id 周排产计划主键
     * @return 结果
     */
    @Override
    public int deleteMrpProdWeeklyPlanById(Long id)
    {
        return mrpProdWeeklyPlanMapper.deleteMrpProdWeeklyPlanById(id);
    }

    /**
     * 导入周排产计划数据（批量插入，事务性）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importData(List<MrpProdWeeklyPlan> list, boolean updateSupport, String operName, String weekStartDate)
    {
        if (StringUtils.isNull(list) || list.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        if (StringUtils.isEmpty(weekStartDate))
        {
            throw new ServiceException("请选择周一日期！");
        }
        // 解析周一日期并计算年第周
        Date mondayDate;
        String yearWeek;
        try
        {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            mondayDate = sdf.parse(weekStartDate);
            Calendar cal = Calendar.getInstance();
            cal.setFirstDayOfWeek(Calendar.MONDAY);
            cal.setMinimalDaysInFirstWeek(4);
            cal.setTime(mondayDate);
            int year = cal.get(Calendar.YEAR);
            int week = cal.get(Calendar.WEEK_OF_YEAR);
            yearWeek = String.format("%d%02d", year, week);
        }
        catch (Exception e)
        {
            throw new ServiceException("周一日期格式错误，请使用yyyy-MM-dd格式！");
        }
        
        // 预处理数据，校验并填充字段（跳过空行）
        List<MrpProdWeeklyPlan> validList = new ArrayList<>();
        int skipNum = 0;
        Date now = new Date();
        
        for (MrpProdWeeklyPlan item : list)
        {
            // 跳过编码为空的行（视为空行）
            if (StringUtils.isEmpty(item.getItemCode()))
            {
                skipNum++;
                continue;
            }
            // 自动填充年第周和周一日期
            item.setYearWeek(yearWeek);
            item.setWeekStartDate(mondayDate);
            item.setCreatedAt(now);
            validList.add(item);
        }
        
        if (validList.isEmpty())
        {
            throw new ServiceException("没有有效的数据可导入！所有行的编码都为空。");
        }
        
        // 逐条插入（Oracle INSERT ALL不支持SEQUENCE.NEXTVAL）
        int total = validList.size();
        int count = 0;
        long startTime = System.currentTimeMillis();
        System.out.println("开始导入周排产计划，共 " + total + " 条数据");
        
        for (MrpProdWeeklyPlan item : validList)
        {
            mrpProdWeeklyPlanMapper.insertMrpProdWeeklyPlan(item);
            count++;
            // 每500条打印进度
            if (count % 500 == 0)
            {
                long elapsed = (System.currentTimeMillis() - startTime) / 1000;
                System.out.println("已导入 " + count + "/" + total + " 条，耗时 " + elapsed + " 秒");
            }
        }
        
        long totalTime = (System.currentTimeMillis() - startTime) / 1000;
        System.out.println("导入完成，共 " + total + " 条，总耗时 " + totalTime + " 秒");
        
        String msg = "数据导入成功！共导入 " + total + " 条";
        if (skipNum > 0)
        {
            msg += "，跳过空行 " + skipNum + " 条";
        }
        return msg;
    }
}
