package com.fjhx.stock.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.base.Condition;
import com.fjhx.constants.StatusConstant;
import com.fjhx.entity.stock.StockTransfer;
import com.fjhx.entity.stock.StockTransferDetails;
import com.fjhx.params.stock.StockTransferVo;
import com.fjhx.stock.mapper.StockTransferMapper;
import com.fjhx.stock.service.StockTransferDetailsService;
import com.fjhx.stock.service.StockTransferService;
import com.fjhx.utils.Assert;
import com.fjhx.utils.WrapperUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 转仓 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2022-09-13
 */
@Service
public class StockTransferServiceImpl extends ServiceImpl<StockTransferMapper, StockTransfer> implements StockTransferService {

    @Autowired
    private StockTransferDetailsService stockTransferDetailsService;

    @Override
    public Page<Map<String, Object>> getPage(Map<String, String> condition) {

        QueryWrapper<Object> wrapper = Wrappers.query()
                .eq("st.status", StatusConstant.NO)
                .eq("st.del_flag", 0);

        return baseMapper.getPage(createPage(condition), wrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(List<StockTransferVo> stockTransferVoList) {

        ArrayList<StockTransferDetails> stockTransferDetailsList = new ArrayList<>();

        for (StockTransferVo stockTransferVo : stockTransferVoList) {
            String materialId = stockTransferVo.getMaterialId();
            List<StockTransferDetails> itemStockTransferDetailsList = stockTransferVo.getStockTransferDetailsList();

            Assert.notEmpty(stockTransferVo.getSubmitUser(), "提交人账号不能为空");
            Assert.notEmpty(stockTransferVo.getReceiveUser(), "接收人账号不能为空");
            Assert.notEmpty(materialId, "物料id不能为空");
            Assert.notEmpty(itemStockTransferDetailsList, "物料信息不能为空");

            // 赋值提交数量
            stockTransferVo.setSubmitNum(itemStockTransferDetailsList.size());
            // 赋值提交米数
            stockTransferVo.setSubmitMeters(itemStockTransferDetailsList.stream()
                    .map(StockTransferDetails::getQuantity)
                    .reduce(BigDecimal.ZERO, BigDecimal::add));
            // 赋值提交时间
            stockTransferVo.setSubmitTime(new Date());
            // 状态 未复核
            stockTransferVo.setStatus(StatusConstant.NO);
            // 保存
            save(stockTransferVo);

            // 转仓id
            Long id = stockTransferVo.getId();
            // 赋值明细
            for (StockTransferDetails stockTransferDetails : itemStockTransferDetailsList) {
                stockTransferDetails.setStockTransferId(id);
                stockTransferDetails.setMaterialId(materialId);
                stockTransferDetails.setOldQuantity(stockTransferDetails.getQuantity());
            }
            stockTransferDetailsList.addAll(itemStockTransferDetailsList);
        }

        stockTransferDetailsService.saveBatch(stockTransferDetailsList);

    }

    @Override
    public StockTransferVo details(Long id) {

        StockTransferVo stockTransferVo = baseMapper.StockTransferVo(id);

        List<StockTransferDetails> stockTransferDetailsList =
                stockTransferDetailsService.list(StockTransferDetails::getStockTransferId, id);
        stockTransferVo.setStockTransferDetailsList(stockTransferDetailsList);

        return stockTransferVo;
    }

    @Override
    public void check(StockTransferVo stockTransferVo) {
        Assert.notEmpty(stockTransferVo.getCheckUser(), "复核人账号不能为空");
        stockTransferVo.setCheckTime(new Date());
        stockTransferVo.setStatus(StatusConstant.YES);
        updateById(stockTransferVo);

        List<StockTransferDetails> stockTransferDetailsList = stockTransferVo.getStockTransferDetailsList();
        for (StockTransferDetails stockTransferDetails : stockTransferDetailsList) {
            stockTransferDetails.setMaterialId(stockTransferVo.getMaterialId());

            if (ObjectUtil.isEmpty(stockTransferDetails.getId())) {
                stockTransferDetails.setOldQuantity(BigDecimal.ZERO);
                stockTransferDetails.setStockTransferId(stockTransferVo.getId());
            }
        }
        stockTransferDetailsService.saveOrUpdateBatch(stockTransferDetailsList);
    }

    @Override
    public Map<String, Object> webStatistics(Condition condition) {
        QueryWrapper<?> wrapper = WrapperUtil.init(condition)
                .periodOfTime("st.submit_time")
                .notDelete("st")
                .getWrapper();

        String userId = condition.getStr("userId");

        wrapper.and(userId != null, q -> q.eq("uu.ID", userId).or().eq("uu2.ID", userId))
                .eq("st.status", StatusConstant.YES);

        return baseMapper.webStatistics(wrapper);
    }

    @Override
    public Page<Map<String, Object>> webPage(Condition condition) {
        QueryWrapper<?> wrapper = WrapperUtil.init(condition)
                .periodOfTime("st.submit_time")
                .notDelete("st")
                .getWrapper();

        String userId = condition.getStr("userId");

        wrapper.and(userId != null, q -> q.eq("uu.ID", userId).or().eq("uu2.ID", userId))
                .eq("st.status", StatusConstant.YES);

        return baseMapper.webPage(condition.getPage(), wrapper);
    }

}
