package com.foreverwin.mesnac.production.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.foreverwin.mesnac.common.constant.Constants;
import com.foreverwin.mesnac.common.enums.HandleEnum;
import com.foreverwin.mesnac.common.service.CommonService;
import com.foreverwin.mesnac.common.util.StringUtil;
import com.foreverwin.mesnac.meapi.dto.WorkCenterDto;
import com.foreverwin.mesnac.meapi.model.Inventory;
import com.foreverwin.mesnac.meapi.model.Resrce;
import com.foreverwin.mesnac.meapi.service.InventoryService;
import com.foreverwin.mesnac.meapi.service.ResrceService;
import com.foreverwin.mesnac.production.dto.LoadInventoryDto;
import com.foreverwin.mesnac.production.mapper.LoadInventoryMapper;
import com.foreverwin.mesnac.production.model.LoadInventory;
import com.foreverwin.mesnac.production.model.LoadInventoryLog;
import com.foreverwin.mesnac.production.service.LoadInventoryLogService;
import com.foreverwin.mesnac.production.service.LoadInventoryService;
import com.foreverwin.modular.core.exception.BaseException;
import com.foreverwin.modular.core.util.CommonMethods;
import com.foreverwin.modular.core.util.FrontPage;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 上料表 服务实现类
 * </p>
 *
 * @author Philip
 * @since 2021-07-09
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class LoadInventoryServiceImpl extends ServiceImpl<LoadInventoryMapper, LoadInventory> implements LoadInventoryService {

    @Autowired
    private ResrceService resrceService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private InventoryService inventoryService;
    @Autowired
    private LoadInventoryMapper loadInventoryMapper;
    @Autowired
    private LoadInventoryLogService loadInventoryLogService;

    @Override
    public IPage<LoadInventory> selectPage(FrontPage<LoadInventory> frontPage, LoadInventory loadInventory) {
        QueryWrapper<LoadInventory> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(loadInventory);
        return super.page(frontPage.getPagePlus(), queryWrapper);
    }

    @Override
    public List<LoadInventory> selectList(LoadInventory loadInventory) {
        QueryWrapper<LoadInventory> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(loadInventory);
        return super.list(queryWrapper);
    }

    @Override
    public HashMap<String, Object> getLoadInventoryList(WorkCenterDto workCenterDto) {
        String site = CommonMethods.getSite();
        String resrce = workCenterDto.getResrce();
        String workCenter = workCenterDto.getWorkCenter();
        String handle = HandleEnum.RESOURCE.getHandle(site, resrce);
        Resrce byId = resrceService.getById(handle);
        if (byId==null){
            throw new BaseException("设备"+resrce+"不存在");
        }
        //校验
        String workShopBo = commonService.getWorkShopBo(handle);
        if (StringUtil.isBlank(workShopBo)) {
            throw new BaseException("资源 " + resrce + " 未匹配到车间");
        }
        if (!workCenter.equals(StringUtil.trimHandle(workShopBo))) {
            throw new BaseException("资源 " + resrce + " 与车间不匹配");
        }
        String description = byId.getDescription();
        List<LoadInventoryDto> loadInventoryList = loadInventoryMapper.getLoadInventoryList(site, resrce, LocaleContextHolder.getLocale().getLanguage());
        HashMap<String, Object> map = new HashMap<>();
        map.put("resrceDesc",description);
        map.put("loadInventoryList",loadInventoryList);

        return map;
    }

    @Override
    public void loadInventory(LoadInventory loadInventory) {
        String site = CommonMethods.getSite();
        String resrce = loadInventory.getResrce();
        String handle = HandleEnum.RESOURCE.getHandle(site, resrce);
        Resrce byId = resrceService.getById(handle);
        String inventoryId = loadInventory.getInventoryId();
        BigDecimal loadQty = loadInventory.getLoadQty();
        if (byId==null){
            throw new BaseException("设备"+resrce+"不存在");
        }
        if (loadQty.doubleValue()<=0){
            throw new BaseException("上料数量不能小于0");
        }
        Inventory inventory = inventoryService.getById(HandleEnum.INVENTORY.getHandle(site, inventoryId));
        if (inventory==null){
            throw new BaseException("库存"+inventoryId+"不存在");
        }
        if (inventory.getQtyOnHand().compareTo(loadQty)<0){
            throw new BaseException("上料数量不能大于剩余数量"+inventory.getQtyOnHand());
        }
        //设备派工单组件是否包含
        Integer bomComponent = loadInventoryMapper.findBomComponent(site, resrce, inventory.getItemBo());
        if (bomComponent<1){
            throw new BaseException("不是设备上产品需要的物料");
        }
        BigDecimal remainQty = inventory.getQtyOnHand().subtract(loadQty);
        //扣减库存
        commonService.updateInventory(site,inventoryId,remainQty);
        //保存上料数据
        LocalDateTime now = LocalDateTime.now();
        String user = CommonMethods.getUser();
        loadInventory.setHandle(HandleEnum.LOAD_INVENTORY.getHandle(site, UUID.randomUUID().toString()));
        loadInventory.setSite(site);
        loadInventory.setResrce(resrce);
        loadInventory.setItem(StringUtil.trimHandle(inventory.getItemBo()));
        loadInventory.setQtyOnHand(loadInventory.getLoadQty());
        loadInventory.setCreateUser(user);
        loadInventory.setCreatedDateTime(now);
        loadInventory.setModifyUser(user);
        loadInventory.setModifiedDateTime(now);
        save(loadInventory);
        LoadInventoryLog loadInventoryLog=new LoadInventoryLog();
        BeanUtils.copyProperties(loadInventory,loadInventoryLog);
        loadInventoryLog.setActionCode(Constants.ACTION_CODE_LOAD);
        loadInventoryLog.setHandle(UUID.randomUUID().toString());
        loadInventoryLogService.save(loadInventoryLog);
    }

    @Override
    public void unLoadInventory(List<LoadInventoryDto> inventoryDtoList) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();

        for (LoadInventoryDto loadInventoryDto: inventoryDtoList) {
            String handle = loadInventoryDto.getHandle();
            LoadInventory loadInventory = getById(handle);
            String inventoryId = loadInventory.getInventoryId();
            if(loadInventory==null){
                throw new BaseException("未找到上料记录");
            }
            Inventory inventory = inventoryService.getById(HandleEnum.INVENTORY.getHandle(site, inventoryId));
            if (inventory==null){
                throw new BaseException("库存"+inventoryId+"不存在");
            }
            //增加库存
            commonService.updateInventory(site,inventoryId,inventory.getQtyOnHand().add(loadInventory.getQtyOnHand()));
            //删除卸料数据
            removeById(handle);
            LoadInventoryLog loadInventoryLog=new LoadInventoryLog();
            BeanUtils.copyProperties(loadInventory,loadInventoryLog);
            loadInventoryLog.setActionCode(Constants.ACTION_CODE_UNLOAD);
            loadInventoryLog.setCreatedDateTime(LocalDateTime.now());
            loadInventoryLog.setCreateUser(user);
            loadInventoryLog.setHandle(UUID.randomUUID().toString());
            loadInventoryLogService.save(loadInventoryLog);
        }
    }

    @Override
    public Inventory consumption(LoadInventory loadInventory, BigDecimal costQty) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        String inventoryId = loadInventory.getInventoryId();
        BigDecimal qtyOnHand = loadInventory.getQtyOnHand();
        Inventory inventory = inventoryService.getById(HandleEnum.INVENTORY.getHandle(site, inventoryId));
        LoadInventoryLog loadInventoryLog=new LoadInventoryLog();
        BeanUtils.copyProperties(loadInventory,loadInventoryLog);
        loadInventoryLog.setActionCode(Constants.ACTION_CODE_CONSUMPTION);
        loadInventoryLog.setCreatedDateTime(LocalDateTime.now());
        loadInventoryLog.setCreateUser(user);
        loadInventoryLog.setHandle(UUID.randomUUID().toString());
        if (inventory==null){
            throw new BaseException("库存"+inventoryId+"不存在");
        }
        if (costQty.compareTo(qtyOnHand)>=0){
            //删除卸料数据
            removeById(loadInventory.getHandle());
        }else {
            //减少设备数量
            loadInventoryLog.setQtyOnHand(costQty);
            LoadInventory entity = new LoadInventory();
            entity.setQtyOnHand(qtyOnHand.subtract(costQty));
            UpdateWrapper<LoadInventory> updateWrapper=new UpdateWrapper<>();
            updateWrapper.eq(LoadInventory.HANDLE,loadInventory.getHandle());
            update(entity, updateWrapper);
        }
        //增加库存
        commonService.updateInventory(site,inventoryId,inventory.getQtyOnHand().add(costQty));
        loadInventoryLogService.save(loadInventoryLog);
        return inventory;
    }


}