package com.ruoyi.oa.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.oa.domain.SysOaWarehouse;
import com.ruoyi.oa.domain.SysOaWarehouseDetail;
import com.ruoyi.oa.domain.SysOaWarehouseMaster;
import com.ruoyi.oa.domain.bo.SysOaWarehouseDetailBo;
import com.ruoyi.oa.domain.bo.SysOaWarehouseMasterBo;
import com.ruoyi.oa.domain.vo.SysOaWarehouseDetailVo;
import com.ruoyi.oa.domain.vo.SysOaWarehouseMasterVo;
import com.ruoyi.oa.domain.vo.SysOaWarehouseVo;
import com.ruoyi.oa.mapper.SysOaWarehouseMapper;
import com.ruoyi.oa.mapper.SysOaWarehouseMasterMapper;
import com.ruoyi.oa.service.ISysOaWarehouseDetailService;
import com.ruoyi.oa.service.ISysOaWarehouseMasterService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.oa.domain.bo.SysOaWarehouseTaskBo;
import com.ruoyi.oa.domain.vo.SysOaWarehouseTaskVo;
import com.ruoyi.oa.domain.SysOaWarehouseTask;
import com.ruoyi.oa.mapper.SysOaWarehouseTaskMapper;
import com.ruoyi.oa.service.ISysOaWarehouseTaskService;

import java.util.*;

/**
 * 采购计划Service业务层处理
 *
 * @author hdka
 * @date 2025-03-30
 */
@RequiredArgsConstructor
@Service
public class SysOaWarehouseTaskServiceImpl implements ISysOaWarehouseTaskService {

    private final SysOaWarehouseTaskMapper baseMapper;

    private final SysOaWarehouseMasterMapper masterMapper;

    @Autowired
    private ISysOaWarehouseDetailService detailService;

    @Autowired
    private SysOaWarehouseMapper wareMapper;

    /**
     * 查询采购计划
     */
    @Override
    public SysOaWarehouseTaskVo queryById(Long taskId) {
        return baseMapper.selectVoById(taskId);
    }

    /**
     * 查询采购计划列表
     */
    @Override
    public TableDataInfo<SysOaWarehouseTaskVo> queryPageList(SysOaWarehouseTaskBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysOaWarehouseTask> lqw = buildQueryWrapper(bo);
        Page<SysOaWarehouseTaskVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询采购计划列表
     */
    @Override
    public List<SysOaWarehouseTaskVo> queryList(SysOaWarehouseTaskBo bo) {
        LambdaQueryWrapper<SysOaWarehouseTask> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysOaWarehouseTask> buildQueryWrapper(SysOaWarehouseTaskBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysOaWarehouseTask> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getMasterId() != null, SysOaWarehouseTask::getMasterId, bo.getMasterId());
        lqw.like(StringUtils.isNotBlank(bo.getName()), SysOaWarehouseTask::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getModel()), SysOaWarehouseTask::getModel, bo.getModel());
        lqw.eq(bo.getTaskInventory() != null, SysOaWarehouseTask::getTaskInventory, bo.getTaskInventory());
        lqw.eq(StringUtils.isNotBlank(bo.getBrand()), SysOaWarehouseTask::getBrand, bo.getBrand());
        lqw.eq(StringUtils.isNotBlank(bo.getSpecifications()), SysOaWarehouseTask::getSpecifications, bo.getSpecifications());
        return lqw;
    }

    /**
     * 新增采购计划
     */
    @Override
    public Boolean insertByBo(SysOaWarehouseTaskBo bo) {
        SysOaWarehouseTask add = BeanUtil.toBean(bo, SysOaWarehouseTask.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setTaskId(add.getTaskId());
        }
        return flag;
    }

    /**
     * 修改采购计划
     */
    @Override
    public Boolean updateByBo(SysOaWarehouseTaskBo bo) {
        SysOaWarehouseTask update = BeanUtil.toBean(bo, SysOaWarehouseTask.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysOaWarehouseTask entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除采购计划
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public List<SysOaWarehouseTaskVo> queryByMasterId(Long masterId) {
        SysOaWarehouseTaskBo sysOaWarehouseTaskBo = new SysOaWarehouseTaskBo();
        sysOaWarehouseTaskBo.setMasterId(masterId);
        return this.queryList(sysOaWarehouseTaskBo);
    }

    @Override
    public Boolean addBatch(List<SysOaWarehouseTaskBo> boList) {
        // 首先新增一条采购单
        SysOaWarehouseMaster sysOaWarehouseMaster = new SysOaWarehouseMaster();
        sysOaWarehouseMaster.setType(2L);
        sysOaWarehouseMaster.setStatus(0L);
        sysOaWarehouseMaster.setMasterNum(UUID.randomUUID().toString());
        sysOaWarehouseMaster.setSignUser(LoginHelper.getNickName());
        Boolean flag = masterMapper.insert(sysOaWarehouseMaster) > 0;
        Long masterId = sysOaWarehouseMaster.getMasterId();
        for (SysOaWarehouseTaskBo sysOaWarehouseTaskBo : boList) {
            sysOaWarehouseTaskBo.setMasterId(masterId);
            sysOaWarehouseTaskBo.setWarehouseId(sysOaWarehouseTaskBo.getId());
            this.insertByBo(sysOaWarehouseTaskBo);
        }

        return flag;
    }

    @Override
    public int updateByBoBatch(List<SysOaWarehouseTaskBo> boList) {
        List<SysOaWarehouseTask> sysOaWarehouseTasks = BeanUtil.copyToList(boList, SysOaWarehouseTask.class);
        return baseMapper.updateBatchById(sysOaWarehouseTasks) ? 1 : 0;
    }

    @Override
    public int updateToWare(SysOaWarehouseTaskBo bo) {

        // 判断是否为此物料完成状态
        if (bo.getTaskStatus() == 2) {
            Long masterId;
            // 首先判断是否有此采购单对应的入库单
            SysOaWarehouseDetailBo sysOaWarehouseDetailBo = new SysOaWarehouseDetailBo();
            sysOaWarehouseDetailBo.setFatherId(bo.getMasterId());
            List<SysOaWarehouseDetailVo> sysOaWarehouseDetailVos = detailService.queryList(sysOaWarehouseDetailBo);
            if (sysOaWarehouseDetailVos.isEmpty()) {
                // 如果为空代表此task 为首次入库则创建入库单
                SysOaWarehouseMaster sysOaWarehouseMaster = new SysOaWarehouseMaster();
                sysOaWarehouseMaster.setType(1L);
                sysOaWarehouseMaster.setMasterNum(UUID.randomUUID().toString());
                sysOaWarehouseMaster.setSignUser(LoginHelper.getNickName());
                masterMapper.insert(sysOaWarehouseMaster);
                // 此masterId就是新的入库单id
                masterId = sysOaWarehouseMaster.getMasterId();
            } else {
                // 另外一种情况是已经存在了此采购单的入库单 这个时候就要在此入库单中进行新增
                SysOaWarehouseDetailVo sysOaWarehouseDetailVo = sysOaWarehouseDetailVos.get(0);
                masterId = sysOaWarehouseDetailVo.getMasterId();
            }
            toWareOne(masterId, bo, sysOaWarehouseDetailBo);
            // 最终将判断此master是否还存在0||1的
            // 如果不存在则将此采购单的完成情况置1
            LambdaQueryWrapper<SysOaWarehouseTask> taskLambdaQueryWrapper = new LambdaQueryWrapper<>();
            taskLambdaQueryWrapper.eq(SysOaWarehouseTask::getDelFlag, 0)
                    .eq(SysOaWarehouseTask::getMasterId, bo.getMasterId())
                    .in(SysOaWarehouseTask::getTaskStatus, Arrays.asList(0, 1));
            List<SysOaWarehouseTask> sysOaWarehouseTasks = baseMapper.selectList(taskLambdaQueryWrapper);
            if (sysOaWarehouseTasks.isEmpty()) {
                SysOaWarehouseMasterVo sysOaWarehouseMasterVo = masterMapper.selectVoById(bo.getMasterId());
                // 如果为空代表了所有都结束了 将采购单状态置1
                sysOaWarehouseMasterVo.setStatus(1L);
                masterMapper.updateById(BeanUtil.toBean(sysOaWarehouseMasterVo, SysOaWarehouseMaster.class));
            }
            return 1;
        }

        SysOaWarehouseTask task = BeanUtil.copyProperties(bo, SysOaWarehouseTask.class);

        return baseMapper.updateById(task);
    }

    private int toWareOne(Long masterId, SysOaWarehouseTaskBo bo , SysOaWarehouseDetailBo sysOaWarehouseDetailBo) {
        // 进行入库操作 (因为存在一种情况是此为全新物料是没有物料id的)
        SysOaWarehouse sysOaWarehouse = new SysOaWarehouse();
        Long warehouseId = 0L;
        SysOaWarehouseVo sysOaWarehouseVo = wareMapper.selectVoById(bo.getWarehouseId());
        if (Objects.isNull(sysOaWarehouseVo)) {
            sysOaWarehouse.setPrice(bo.getPrice());
            sysOaWarehouse.setInventory(bo.getTaskInventory());
            sysOaWarehouse.setBrand(bo.getBrand());
            sysOaWarehouse.setModel(bo.getModel());
            sysOaWarehouse.setSpecifications(bo.getSpecifications());
            sysOaWarehouse.setName(bo.getName());
            sysOaWarehouse.setRemark(bo.getRemark());
            sysOaWarehouse.setUnit(bo.getUnit());
            wareMapper.insert(sysOaWarehouse);
            warehouseId = sysOaWarehouse.getId();
        } else {
            warehouseId = bo.getWarehouseId();
            sysOaWarehouse = wareMapper.selectById(warehouseId);
            sysOaWarehouse.setPrice((sysOaWarehouse.getPrice() * sysOaWarehouse.getInventory() + bo.getPrice() * bo.getTaskInventory()) / (sysOaWarehouse.getInventory() + bo.getTaskInventory()));
            sysOaWarehouse.setInventory(sysOaWarehouse.getInventory() + bo.getTaskInventory());
            wareMapper.updateById(sysOaWarehouse);
        }

        // 接下来拿到masterId后开始将采购单数据写入入库单
        sysOaWarehouseDetailBo.setMasterId(masterId);
        sysOaWarehouseDetailBo.setWarehouseId(bo.getWarehouseId());
        sysOaWarehouseDetailBo.setAmount(bo.getTaskInventory());
        sysOaWarehouseDetailBo.setSignPrice(bo.getPrice());
        sysOaWarehouseDetailBo.setWarehouseId(warehouseId);
        sysOaWarehouseDetailBo.setType(1L);
        detailService.insertByBo(sysOaWarehouseDetailBo);
        SysOaWarehouseTask bean = BeanUtil.toBean(bo, SysOaWarehouseTask.class);
        // 最后将此物料更新为完成入库
        return baseMapper.updateById(bean);
    }
}
