package com.yeejoin.equipmanage.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.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yeejoin.equipmanage.common.entity.*;
import com.yeejoin.equipmanage.common.enums.EquipStatusEnum;
import com.yeejoin.equipmanage.mapper.EquipmentDetailMapper;
import com.yeejoin.equipmanage.mapper.EquipmentOnCarMapper;
import com.yeejoin.equipmanage.mapper.StockDetailMapper;
import com.yeejoin.equipmanage.mapper.StockMapper;
import com.yeejoin.equipmanage.service.IEquipmentCategoryService;
import com.yeejoin.equipmanage.service.IEquipmentDetailService;
import com.yeejoin.equipmanage.service.IEquipmentService;
import com.yeejoin.equipmanage.service.IStockDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 库存明细 服务实现类
 *
 * @author wujiang
 * @date 2020-07-07
 */
@Service
public class StockDetailServiceImpl extends ServiceImpl<StockDetailMapper, StockDetail> implements IStockDetailService {
    @Lazy
    @Autowired
    private IEquipmentDetailService iEquipmentDetailService;
    @Lazy
    @Autowired
    private IEquipmentService iEquipmentService;

    @Autowired
    private IEquipmentCategoryService iEquipmentCategoryService;

    @Autowired
    private EquipmentDetailMapper equipmentDetailMapper;

    @Autowired
    private EquipmentOnCarMapper equipmentOnCarMapper;

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private StockDetailMapper stockDetailMapper;

    @Override
    public Page<StockDetail> pageCategoryStock(Page<EquipmentDetail> pageBean, String category,
                                               Long warehouseStructureId) {

        Page<EquipmentDetail> page = iEquipmentDetailService.page(pageBean, category);
        List<EquipmentDetail> list = page.getRecords();
        List<StockDetail> stockDetailList = new ArrayList<StockDetail>();
        for (EquipmentDetail equipmentDetail : list) {
            StockDetail stockDetail = this
                    .getOne(new QueryWrapper<StockDetail>().eq("equipment_detail_id", equipmentDetail.getId())
                            .eq("warehouse_structure_id", warehouseStructureId)
                            .eq("status", EquipStatusEnum.REPERTORY.getCode()));
            if (stockDetail == null) {
                stockDetail = new StockDetail();
                stockDetail.setAmount(0.0);
            }
            stockDetail.setEquipmentDetail(equipmentDetail);
            String img = equipmentDetail.getEquipment().getImg();
            if (img != null && !"".equals(img)) {
                stockDetail.setImg(img);
            }
            stockDetailList.add(stockDetail);
        }
        Page<StockDetail> pageStock = new Page<StockDetail>(pageBean.getCurrent(), pageBean.getSize());
        pageStock.setRecords(stockDetailList);
        pageStock.setTotal(page.getTotal());
        return pageStock;
    }

    @Override
    public IPage<StockDetail> pageStockCategory(Page<StockDetail> pageBean, String category,
                                                Long warehouseStructureId) {
        char[] chars = category.toCharArray();
        String newcategory = "";
        for (int i = chars.length - 1; i >= 0; i--) {
            if ("0".equals(String.valueOf(chars[i]))) {
                newcategory = category.substring(0, i);
            } else {
                break;
            }
        }
        List<EquipmentCategory> categoryList = iEquipmentCategoryService
                .list(new QueryWrapper<EquipmentCategory>().likeRight("code", newcategory));
        List<EquipmentDetail> list = equipmentDetailMapper.pageCategory(pageBean.offset(), Long.MAX_VALUE,
                categoryList);
        List<Long> idList = new ArrayList<Long>();
        for (EquipmentDetail equipmentDetail : list) {
            idList.add(equipmentDetail.getId());
        }
        IPage<StockDetail> page;
        List<Long> wareId = equipmentDetailMapper.getWareId(warehouseStructureId);
        wareId.add(warehouseStructureId);
        if (idList.size() > 0) {
            page = this.page(pageBean,
                    new QueryWrapper<StockDetail>().in("warehouse_structure_id", wareId)
                            .eq("status", EquipStatusEnum.REPERTORY.getCode()).in("equipment_detail_id", idList));
        } else {
            page = new Page<>();
        }

        List<StockDetail> resultList = page.getRecords();
        for (StockDetail stockDetail : resultList) {
            EquipmentDetail equipmentDetail = iEquipmentDetailService.getById(stockDetail.getEquipmentDetailId());
            Equipment equipment = iEquipmentService.getById(equipmentDetail.getEquipmentId());
            equipmentDetail.setEquipment(equipment);
            stockDetail.setEquipmentDetail(equipmentDetail);
            String img = equipmentDetail.getEquipment().getImg();
            if (img != null && !"".equals(img)) {
                stockDetail.setImg(img);
            }
        }
        return page;
    }

    @Override
    public IPage<StockDetail> pagePlaceEquip(Page<StockDetail> pageBean, Long equipmentDetailId,
                                             Long warehouseStructureId) {
        int[] status = new int[]{7, 11};
        IPage<StockDetail> page = this.page(pageBean,
                new QueryWrapper<StockDetail>().eq("equipment_detail_id", equipmentDetailId)
                        .eq("warehouse_structure_id", warehouseStructureId).notIn("status", Arrays.asList(status)));
        List<StockDetail> list = page.getRecords();
        for (StockDetail stockDetail : list) {
            EquipmentDetail equipmentDetail = iEquipmentDetailService.getById(stockDetail.getEquipmentDetailId());
            stockDetail.setEquipmentDetail(equipmentDetail);
            // Equipment equipment =
            // iEquipmentService.getById(equipmentDetail.getEquipmentId());
            // equipmentDetail.setEquipment(equipment);
        }
        return page;
    }

    @Override
    public List<StockDetail> loadOnPerson(List<Map<String, Number>> stocks) {
        List<StockDetail> list = new ArrayList<>();
        stocks.forEach(x -> {
            StockDetail stockDetail = this.baseMapper.selectById(Long.valueOf(x.get("stockDetailId").toString()));
            if (null == stockDetail) {
                throw new RuntimeException("id 为"+ x + "的StockDetail不存在 ！");
            }
            double stockAmount = stockDetail.getAmount() - Double.parseDouble(x.get("amount").toString());
            if (stockAmount < 0) {
                throw new RuntimeException("库存不足");
            } else if (stockAmount == 0) {
                stockDetail.setStatus(String.valueOf(EquipStatusEnum.LOAD.getCode()));
            }
            stockDetail.setAmount(stockAmount);
            this.baseMapper.updateById(stockDetail);
            list.add(stockDetail);
        });
        return list;
    }

    @Override
    public StockDetail unloadOnCar(Map<String, Object> map) {
        Long warehouseId = Long.valueOf(String.valueOf(map.get("warehouseId")));
        Long structureId = Long.valueOf(String.valueOf(map.get("warehouseStructureId")));
        Long stockDetailId = Long.valueOf(String.valueOf(map.get("stockDetailId")));
        Long equipmentOnCarId = Long.valueOf(String.valueOf(map.get("equipmentOnCarId")));
        String area = String.valueOf(map.get("area"));



        StockDetail stockDetail = this.baseMapper.selectById(stockDetailId);
        EquipmentOnCar equipmentOnCar = equipmentOnCarMapper.selectById(equipmentOnCarId);
        if (null == equipmentOnCar) {
            throw new RuntimeException("车辆装载的此装备不存在！");
        }
        if (null == stockDetail) {
            throw new RuntimeException("车辆装载的此装备没有记录在库！");
        }
        if(area!=null){
        iEquipmentDetailService.update(new UpdateWrapper<EquipmentDetail>().eq("id", equipmentOnCar.getEquipmentDetailId()).set("area", area));

        }
        equipmentOnCarMapper.deleteById(equipmentOnCarId);
        stockDetail.setAmount(equipmentOnCar.getAmount());
        if (structureId != null && structureId.longValue() != stockDetail.getWarehouseStructureId()) {
            Stock stock = changeStock(warehouseId, stockDetail.getEquipmentDetailId(), stockDetail.getOrgCode());
            stockDetail.setStockId(stock.getId());
        }
        stockDetail.setWarehouseId(warehouseId);
        stockDetail.setWarehouseStructureId(structureId);
        stockDetail.setStatus(String.valueOf(EquipStatusEnum.REPERTORY.getCode()));
        updateStock(stockDetail, stockDetail.getAmount());
        return stockDetail;
    }

    @Override
    public StockDetail unloadPerson(Map<String, Object> map) {
        Long stockDetailId = Long.valueOf(String.valueOf(map.get("stockDetailId")));
        double amount = Double.parseDouble(String.valueOf(map.get("amount")));
        if (amount == 0) {
            throw new RuntimeException("数量不能为空");
        }
        StockDetail stockDetail = this.baseMapper.selectById(stockDetailId);
        stockDetail.setStatus(String.valueOf(EquipStatusEnum.REPERTORY.getCode()));//陈浩修改，原本退装枚举值所对应的jcs逻辑是回库，现确定为在位状态
        stockDetail.setAmount(stockDetail.getAmount() + amount);
        this.baseMapper.updateById(stockDetail);
        return stockDetail;
    }

    private Stock changeStock(Long warehouseId, Long equipmentDetailId, String orgCode) {
        Map<String, Object> columnMap = new HashMap<String, Object>();
        columnMap.put("equipment_detail_id", equipmentDetailId);
        columnMap.put("warehouse_id", warehouseId);
        List<Stock> stock = stockMapper.selectByMap(columnMap);
        Stock stock1 = new Stock();
        if (null == stock && stock.size() > 0) {
            stock1.setAmount(0d);
            stock1.setEquipmentDetailId(equipmentDetailId);
            stock1.setWarehouseId(warehouseId);
            stock1.setOrgCode(orgCode);
            stockMapper.insert(stock1);
        }
        return stock1;
    }

    private void updateStock(StockDetail detail, double amount) {
        Stock stock = stockMapper.selectById(detail.getStockId());
        stock.setAmount(stock.getAmount() + amount);
        stockMapper.updateById(stock);
        stockDetailMapper.updateById(detail);
    }

    @Override
    public boolean updateBatch(List<EquipmentOnCar> list, Long status) {
        for (EquipmentOnCar equipmentOnCar : list) {
            stockDetailMapper.updateStatus(equipmentOnCar, status);
        }
        return Boolean.TRUE;
    }

}
