package com.bonus.material.lease.service.impl;

import java.util.List;
import java.util.Optional;
import cn.hutool.core.collection.CollectionUtil;
import com.bonus.common.biz.constant.MaterialConstants;
import com.bonus.common.biz.enums.LeaseTaskStatusEnum;
import com.bonus.common.biz.enums.TmTaskTypeEnum;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.lease.domain.LeaseApplyDetails;
import com.bonus.material.lease.domain.LeaseOutDetails;
import com.bonus.material.lease.domain.vo.LeaseApplyRequestVo;
import com.bonus.material.lease.domain.vo.LeaseOutRequestVo;
import com.bonus.material.lease.mapper.LeaseApplyDetailsMapper;
import com.bonus.material.lease.service.ILeaseOutDetailsService;
import com.bonus.material.task.domain.TmTask;
import com.bonus.material.task.domain.TmTaskAgreement;
import com.bonus.material.task.mapper.TmTaskAgreementMapper;
import com.bonus.material.task.mapper.TmTaskMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import com.bonus.material.lease.mapper.LeaseApplyInfoMapper;
import com.bonus.material.lease.domain.LeaseApplyInfo;
import com.bonus.material.lease.service.ILeaseApplyInfoService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;

/**
 * 领料任务Service业务层处理
 * 
 * @author xsheng
 * @date 2024-10-16
 */
@Service
public class LeaseApplyInfoServiceImpl implements ILeaseApplyInfoService {

    @Autowired
    private ILeaseOutDetailsService leaseOutDetailsService;

    @Resource
    private LeaseApplyInfoMapper leaseApplyInfoMapper;

    @Resource
    private LeaseApplyDetailsMapper leaseApplyDetailsMapper;

    @Resource
    private TmTaskMapper tmTaskMapper;

    @Resource
    TmTaskAgreementMapper tmTaskAgreementMapper;

    /**
     * 查询领料任务
     *
     * @param id 领料任务主键
     * @return 领料任务
     */
    @Override
    public LeaseApplyRequestVo selectLeaseApplyInfoById(Long id) {
        try {
            Optional<LeaseApplyInfo> optionalInfo = Optional.ofNullable(leaseApplyInfoMapper.selectLeaseApplyInfoById(id));
            LeaseApplyRequestVo leaseApplyRequestVo = new LeaseApplyRequestVo();

            optionalInfo.ifPresent(info -> {
                leaseApplyRequestVo.setLeaseApplyInfo(info);
                // 获取领料单详情
                List<LeaseApplyDetails> details = leaseApplyDetailsMapper.selectLeaseApplyDetailsList(new LeaseApplyDetails(info.getId()));
                if (!CollectionUtils.isEmpty(details)) {
                    leaseApplyRequestVo.setLeaseApplyDetailsList(details);
                }
            });

            return leaseApplyRequestVo;
        } catch (Exception e) {
            // 记录异常日志
            System.err.println("Error occurred while selecting lease apply info by ID: " + id + e.getMessage());
            throw new RuntimeException("Failed to select lease apply info", e);
        }
    }


    /**
     * 查询领料任务列表
     * 
     * @param leaseApplyInfo 领料任务
     * @return 领料任务
     */
    @Override
    public List<LeaseApplyInfo> selectLeaseApplyInfoList(LeaseApplyInfo leaseApplyInfo) {
        List<LeaseApplyInfo> list = leaseApplyInfoMapper.selectLeaseApplyInfoList(leaseApplyInfo);
        for (LeaseApplyInfo applyInfo : list) {
            applyInfo.setMaTypeNames(leaseApplyDetailsMapper.selectMaTypeNameByParentId(applyInfo.getId()));
        }
        return list;
    }

    /**
     * 新增领料任务
     * 
     * @param leaseApplyRequestVo 领料任务
     * @return 结果
     */
    @Override
    public AjaxResult insertLeaseApplyInfo(LeaseApplyRequestVo leaseApplyRequestVo) {
        if (leaseApplyRequestVo.getLeaseApplyInfo() == null) {
            return AjaxResult.error("请先填写领料任务信息");
        }
        if (CollectionUtil.isEmpty(leaseApplyRequestVo.getLeaseApplyDetailsList())) {
            return AjaxResult.error("请先添加领料任务物资明细");
        }
        leaseApplyRequestVo.getLeaseApplyInfo().setCreateTime(DateUtils.getNowDate());
        leaseApplyRequestVo.getLeaseApplyInfo().setCreateBy(SecurityUtils.getUsername());
        try {
            int thisMonthMaxOrder = tmTaskMapper.getMonthMaxOrderByDate(DateUtils.getCurrentYear(), DateUtils.getCurrentMonth(), TmTaskTypeEnum.TM_TASK_LEASE.getTaskTypeId());
            String taskCode = genderTaskCode(thisMonthMaxOrder);
            TmTask tmTask = new TmTask(null, TmTaskTypeEnum.TM_TASK_LEASE.getTaskTypeId(),
                    LeaseTaskStatusEnum.LEASE_TASK_TO_PUBLISHED.getStatus(),
                    leaseApplyRequestVo.getLeaseApplyInfo().getCompanyId(),thisMonthMaxOrder + 1, taskCode);
            tmTask.setCreateTime(DateUtils.getNowDate());
            tmTask.setCreateBy(SecurityUtils.getUsername());
            tmTaskMapper.insertTmTask(tmTask);
            TmTaskAgreement tmTaskAgreement = new TmTaskAgreement(tmTask.getTaskId(), leaseApplyRequestVo.getLeaseApplyInfo().getAgreementId());
            tmTaskAgreement.setCreateTime(DateUtils.getNowDate());
            tmTaskAgreement.setCreateBy(SecurityUtils.getUsername());
            tmTaskAgreementMapper.insertTmTaskAgreement(tmTaskAgreement);
            leaseApplyRequestVo.getLeaseApplyInfo().setTaskId(tmTask.getTaskId());
            leaseApplyRequestVo.getLeaseApplyInfo().setCode(taskCode);
            int count = leaseApplyInfoMapper.insertLeaseApplyInfo(leaseApplyRequestVo.getLeaseApplyInfo());
            if (count > 0) {
                return insertPurchaseCheckDetails(leaseApplyRequestVo.getLeaseApplyDetailsList(), leaseApplyRequestVo.getLeaseApplyInfo().getId());
            } else {
                return AjaxResult.error("新增任务失败,lease_apply_info表插入0条");
            }
        } catch (DataAccessException e) {
            return AjaxResult.error("数据库操作失败:" + e.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("新增任务失败:" + e.getMessage());
        }
    }

    /**
     * 发布任务
     *
     * @param leaseApplyInfo 领料任务info
     */
    @Override
    @Transactional
    public AjaxResult publish(LeaseApplyInfo leaseApplyInfo) {
        if (leaseApplyInfo.getId() == null) {
            return AjaxResult.error("ID为空,请完善后重新发布!");
        }
        if (leaseApplyInfo.getTaskId() == null) {
            return AjaxResult.error("任务ID为空,请完善后重新发布!");
        }
        leaseApplyInfo.setUpdateTime(DateUtils.getNowDate());
        try {
            int result = leaseApplyInfoMapper.updateLeaseApplyInfo(leaseApplyInfo);
            if (result > 0) {
                // 同步修改tm_task任务状态, 如果不需要审核，改成 LEASE_TASK_IN_PROGRESS， 如果需要审核，改成 LEASE_TASK_TO_AUDIT
                TmTask tmTask = new TmTask();
                tmTask.setTaskType(TmTaskTypeEnum.TM_TASK_LEASE.getTaskTypeId());
                tmTask.setTaskId(leaseApplyInfo.getTaskId());
                tmTask.setTaskStatus(LeaseTaskStatusEnum.LEASE_TASK_IN_PROGRESS.getStatus());
                tmTaskMapper.updateTmTask(tmTask);
                return AjaxResult.success("发布成功");
            }
            return AjaxResult.error("发布失败");
        } catch (DataAccessException e) {
            // 抛出异常、回滚数据
            throw new RuntimeException();
        } catch (Exception e) {
            return AjaxResult.error("发布失败:" + e.getMessage());
        }
    }

    private AjaxResult insertPurchaseCheckDetails(List<LeaseApplyDetails> leaseApplyDetailsList, Long parentId) {
        if (!CollectionUtils.isEmpty(leaseApplyDetailsList)) {
            for (LeaseApplyDetails details : leaseApplyDetailsList) {
                details.setParentId(parentId); // 设置info.parentId
                details.setCreateTime(DateUtils.getNowDate());
                details.setCreateBy(SecurityUtils.getUsername());
            }
            // 批量插入详情数据
            int count = leaseApplyDetailsMapper.insertLeaseApplyDetailsList(leaseApplyDetailsList);
            if (count > 0) {
                return AjaxResult.success("新增任务成功");
            } else {
                return AjaxResult.error("新增任务失败,lease_apply_detail详情表插入0条");
            }
        } else {
            return AjaxResult.success("新增任务成功");
        }
    }

    /**
     * 生成任务编号并构造Tm_Task任务对象
     * @param thisMonthMaxOrder 当月最大单号
     * @return 任务对象
     */
    private static String genderTaskCode(Integer thisMonthMaxOrder) {
        return MaterialConstants.LEASE_TASK_TYPE_LABEL + DateUtils.getCurrentYear() + DateUtils.getCurrentMonth() + String.format("%06d", thisMonthMaxOrder + 1);
    }

    /**
     * 修改领料任务
     * 
     * @param leaseApplyRequestVo 领料任务
     * @return 结果
     */
    @Override
    public boolean updateLeaseApplyInfo(LeaseApplyRequestVo leaseApplyRequestVo) {
        try {
            // 提取到局部变量中，减少重复代码
            LeaseApplyInfo leaseApplyInfo = leaseApplyRequestVo.getLeaseApplyInfo();
            if (leaseApplyInfo != null && leaseApplyInfo.getId() != null) {
                leaseApplyInfo.setUpdateTime(DateUtils.getNowDate());
                leaseApplyInfo.setUpdateBy(SecurityUtils.getUsername());

                // 去除创建一个新的数组对象，直接复用
                Long[] ids = {leaseApplyInfo.getId()};

                if (CollectionUtil.isNotEmpty(leaseApplyRequestVo.getLeaseApplyDetailsList())) {
                    // 业务逻辑代码
                    leaseApplyDetailsMapper.deleteLeaseApplyDetailsByParentIds(ids);
                    insertPurchaseCheckDetails(leaseApplyRequestVo.getLeaseApplyDetailsList(), leaseApplyInfo.getId());
                }
                // 修改外层info
                leaseApplyInfoMapper.updateLeaseApplyInfo(leaseApplyInfo);
                return true;
            }
            return false;
        } catch (DataAccessException dae) {
            throw new ServiceException("数据访问异常: " + dae.getMessage());
        } catch (IllegalArgumentException iae) {
            throw new ServiceException("非法参数异常: " + iae.getMessage());
        } catch (Exception e) {
            throw new ServiceException("未知异常: " + e.getMessage());
        }
    }


    /**
     * 领料：出库
     *
     * @param leaseOutRequestVo 领料：出库
     * @return 结果
     */
    @Override
    public AjaxResult leaseOut(LeaseOutRequestVo leaseOutRequestVo) {
        for (LeaseOutDetails bean : leaseOutRequestVo.getLeaseOutDetailsList()) {
            AjaxResult ajaxResult = leaseOutDetailsService.leaseOut(bean);
            if (ajaxResult.isError()) {
                return ajaxResult;
            }
        }
        return AjaxResult.success();
    }



    /**
     * 批量删除领料任务
     * 
     * @param ids 需要删除的领料任务主键
     * @return 结果
     */
    @Override
    public int deleteLeaseApplyInfoByIds(Long[] ids) {
        return leaseApplyInfoMapper.deleteLeaseApplyInfoByIds(ids);
    }

    /**
     * 删除领料任务信息
     * 
     * @param id 领料任务主键
     * @return 结果
     */
    @Override
    public int deleteLeaseApplyInfoById(Long id) {
        return leaseApplyInfoMapper.deleteLeaseApplyInfoById(id);
    }
}
