package com.hw.wms.service.impl;

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

import com.hw.common.core.constant.SecurityConstants;
import com.hw.common.core.constant.WmsConstants;
import com.hw.common.core.domain.R;
import com.hw.common.core.exception.ServiceException;
import com.hw.common.security.utils.SecurityUtils;
import com.hw.mes.api.RemoteMesService;
import com.hw.mes.api.domain.MesBaseBarcodeInfo;
import com.hw.wms.domain.WmsBaseLocation;
import com.hw.wms.domain.WmsRawStock;
import com.hw.wms.domain.vo.WmsRawInstockVo;
import com.hw.wms.mapper.WmsBaseLocationMapper;
import com.hw.wms.mapper.WmsRawInstockDetailMapper;
import com.hw.wms.mapper.WmsRawStockMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

import com.hw.common.core.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.hw.wms.domain.WmsRawInstockDetail;
import com.hw.wms.mapper.WmsRawInstockMapper;
import com.hw.wms.domain.WmsRawInstock;
import com.hw.wms.service.IWmsRawInstockService;

import javax.annotation.Resource;
import javax.annotation.Resources;

/**
 * 原材料入库记录Service业务层处理
 *
 * @author xs
 * @date 2023-12-20
 */
@Service
public class WmsRawInstockServiceImpl implements IWmsRawInstockService {
    @Autowired
    private WmsRawInstockMapper wmsRawInstockMapper;

    @Autowired
    private WmsRawInstockDetailMapper wmsRawInstockDetailMapper;

    @Autowired
    private WmsBaseLocationMapper wmsBaseLocationMapper;

    @Autowired
    private WmsRawStockMapper wmsRawStockMapper;

    @Resource
    private RemoteMesService remoteMesService;


    /**
     * 查询原材料入库记录
     *
     * @param rawInstockId 原材料入库记录主键
     * @return 原材料入库记录
     */
    @Override
    public WmsRawInstock selectWmsRawInstockByRawInstockId(Long rawInstockId) {
        return wmsRawInstockMapper.selectWmsRawInstockByRawInstockId(rawInstockId);
    }

    /**
     * 查询原材料入库记录列表
     *
     * @param wmsRawInstock 原材料入库记录
     * @return 原材料入库记录
     */
    @Override
    public List<WmsRawInstock> selectWmsRawInstockList(WmsRawInstock wmsRawInstock) {
        return wmsRawInstockMapper.selectWmsRawInstockList(wmsRawInstock);
    }


    /**
     * 新增原材料入库记录(适用于移动手持端)
     *
     * @param wmsRawInstock 原材料入库记录
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertWmsRawInstock(WmsRawInstock wmsRawInstock) {
        int rows = wmsRawInstockMapper.insertWmsRawInstock(wmsRawInstock);
        insertWmsRawInstockDetail(wmsRawInstock);
        return rows;
    }

    /**
     * 修改原材料入库记录
     *
     * @param wmsRawInstock 原材料入库记录
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateWmsRawInstock(WmsRawInstock wmsRawInstock) {
        wmsRawInstockMapper.deleteWmsRawInstockDetailByRawInstockId(wmsRawInstock.getRawInstockId());
        insertWmsRawInstockDetail(wmsRawInstock);
        return wmsRawInstockMapper.updateWmsRawInstock(wmsRawInstock);
    }

    /**
     * 批量删除原材料入库记录
     *
     * @param rawInstockIds 需要删除的原材料入库记录主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteWmsRawInstockByRawInstockIds(Long[] rawInstockIds) {
        wmsRawInstockMapper.deleteWmsRawInstockDetailByRawInstockIds(rawInstockIds);
        return wmsRawInstockMapper.deleteWmsRawInstockByRawInstockIds(rawInstockIds);
    }

    /**
     * 删除原材料入库记录信息
     *
     * @param rawInstockId 原材料入库记录主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteWmsRawInstockByRawInstockId(Long rawInstockId) {
        wmsRawInstockMapper.deleteWmsRawInstockDetailByRawInstockId(rawInstockId);
        return wmsRawInstockMapper.deleteWmsRawInstockByRawInstockId(rawInstockId);
    }

    /**
     * 新增原材料入库记录明细信息
     *
     * @param wmsRawInstock 原材料入库记录对象
     */
    public void insertWmsRawInstockDetail(WmsRawInstock wmsRawInstock) {
        List<WmsRawInstockDetail> wmsRawInstockDetailList = wmsRawInstock.getWmsRawInstockDetailList();
        Long rawInstockId = wmsRawInstock.getRawInstockId();
        if (StringUtils.isNotNull(wmsRawInstockDetailList)) {
            List<WmsRawInstockDetail> list = new ArrayList<WmsRawInstockDetail>();
            for (WmsRawInstockDetail wmsRawInstockDetail : wmsRawInstockDetailList) {
                wmsRawInstockDetail.setRawInstockId(rawInstockId);
                list.add(wmsRawInstockDetail);
            }
            if (list.size() > 0) {
                wmsRawInstockMapper.batchWmsRawInstockDetail(list);
            }
        }
    }


    /**
     * 新增原材料入库记录(适用于移动手持端)
     *
     * @param wmsRawInstockVo 原材料入库记录
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertWmsRawInstock(WmsRawInstockVo wmsRawInstockVo) {

        String materialBarcode = wmsRawInstockVo.getMaterialBarcode();
//        R<MesBaseBarcodeInfo> baseBarcodeInfoR = remoteMesService.getBarcode(materialBarcode, SecurityConstants.INNER);
//        MesBaseBarcodeInfo baseBarcodeInfo = baseBarcodeInfoR.getData();
//        if (baseBarcodeInfo == null) {
//            throw new ServiceException("物料编码有误");
//        }

        String locationCode = wmsRawInstockVo.getLocationCode();
        WmsBaseLocation baseLocation = wmsBaseLocationMapper.selectWmsBaseLocationByLocationCode(locationCode);
        if (baseLocation == null) {
            throw new ServiceException("库位编码有误");
        }
        //todo 入库人权限判断
        //todo 物料类型判断是否可以入此库位


        Date currentDate = new Date();
        String userName = SecurityUtils.getUsername();//todo 是否改成nickname
        WmsRawInstock wmsRawInstock = new WmsRawInstock();
        wmsRawInstock.setWarehouseId(baseLocation.getWarehouseId());
        wmsRawInstock.setLocationCode(locationCode);
        wmsRawInstock.setPoNo(wmsRawInstockVo.getPoNo());
        wmsRawInstock.setOperationType(WmsConstants.WMS_OPERATION_TYPE_MANUAL);
        wmsRawInstock.setInstockType(WmsConstants.RAW_INSTOCK_INSTOCK_TYPE_PURCHASE);
        wmsRawInstock.setExecuteStatus(WmsConstants.WMS_EXECUTE_STATUS_FINISH);
        //todo：根据系统参数判断保存审核状态
        wmsRawInstock.setAuditStatus(WmsConstants.WMS_AUDIT_STATUS_TOAUDIT);
        wmsRawInstock.setApplyBy(userName);
        wmsRawInstock.setApplyDate(currentDate);

        //插入记录
        int rows = wmsRawInstockMapper.insertWmsRawInstock(wmsRawInstock);

        //插入明细
        insertWmsRawInstockDetail(wmsRawInstock, wmsRawInstockVo);

        //更新库存
        updateRawStock(wmsRawInstock, wmsRawInstockVo, baseLocation, userName, currentDate);

        //todo：同步erp
        return rows;
    }


    /**
     * 插入原材料入库明细，手持采购入库使用
     * @param wmsRawInstock
     * @param wmsRawInstockVo
     */
    public void insertWmsRawInstockDetail(WmsRawInstock wmsRawInstock, WmsRawInstockVo wmsRawInstockVo) {
        WmsRawInstockDetail wmsRawInstockDetail = new WmsRawInstockDetail();
        wmsRawInstockDetail.setRawInstockId(wmsRawInstock.getRawInstockId());
        wmsRawInstockDetail.setLocationCode(wmsRawInstock.getLocationCode());
        wmsRawInstockDetail.setMaterialBarcode(wmsRawInstockVo.getMaterialBarcode());
        wmsRawInstockDetail.setInstockBatch(wmsRawInstockVo.getBatchCode());
        wmsRawInstockDetail.setMaterialId(wmsRawInstockVo.getMaterialId());
        wmsRawInstockDetail.setPoNo(wmsRawInstock.getPoNo());
        wmsRawInstockDetail.setPlanAmount(wmsRawInstockVo.getInstockAmount());
        wmsRawInstockDetail.setInstockAmount(wmsRawInstockVo.getInstockAmount());
        wmsRawInstockDetail.setExecuteStatus(WmsConstants.WMS_EXECUTE_STATUS_FINISH);
        wmsRawInstockDetail.setInstockPerson(wmsRawInstock.getApplyBy());
        wmsRawInstockDetail.setInstockTime(wmsRawInstock.getApplyDate());
        wmsRawInstockDetail.setInstockWay(WmsConstants.RWA_INSTOCK_DETAIL_INSTOCK_WAY_MOBILE);
        wmsRawInstockDetailMapper.insertWmsRawInstockDetail(wmsRawInstockDetail);
    }

    /**
     * 更新原材料库存
     *
     * @param wmsRawInstock
     * @param wmsRawInstockVo
     * @param baseLocation
     * @param userName
     * @param currentDate
     */
    public void updateRawStock(WmsRawInstock wmsRawInstock,  WmsRawInstockVo wmsRawInstockVo, WmsBaseLocation baseLocation,
                               String userName, Date currentDate) {
        String instockBatch = wmsRawInstockVo.getBatchCode();
        String locationCode = wmsRawInstock.getLocationCode();

        //判断此库位的数量限制，是否还能入库
        WmsRawStock queryRawStock = new WmsRawStock();
        queryRawStock.setLocationCode(locationCode);
        BigDecimal totalAmount = wmsRawStockMapper.getRawStockTotalAmount(queryRawStock);
        totalAmount = totalAmount == null ? BigDecimal.ZERO : totalAmount;
        if (totalAmount.add(wmsRawInstockVo.getInstockAmount()).compareTo(baseLocation.getQtyLimit()) > 0) {
            throw new ServiceException("已超出库位数量限制，请重新选择库位");
        }

        //如果是同一库位入同一批次，则更新数量
        WmsRawStock wmsRawStock = wmsRawStockMapper.selectRawStockByLocationAndBatch(locationCode, instockBatch);
        if (wmsRawStock != null) {
//            wmsRawStock.setQualityStatus(wmsRawInstockVo.getQualityStatus());
            wmsRawStock.setTotalAmount(wmsRawStock.getTotalAmount().add(wmsRawInstockVo.getInstockAmount()));
            wmsRawStock.setUpdateBy(userName);
            wmsRawStock.setUpdateDate(currentDate);
            wmsRawStockMapper.updateWmsRawStock(wmsRawStock);
        } else {
            wmsRawStock = new WmsRawStock();
            wmsRawStock.setWarehouseId(wmsRawInstock.getWarehouseId());
            wmsRawStock.setLocationCode(locationCode);
            wmsRawStock.setStockType(WmsConstants.RWA_STOCK_STOCK_TYPE_RAW);
            wmsRawStock.setMaterialId(wmsRawInstockVo.getMaterialId());
            wmsRawStock.setInstockBatch(instockBatch);
//            wmsRawStock.setLastOutstockTime(baseBarcodeInfo.getLastOutstockDate());
//            wmsRawStock.setQualityStatus(wmsRawInstockVo.getQualityStatus());
            wmsRawStock.setTotalAmount(wmsRawInstockVo.getInstockAmount());
            wmsRawStock.setCreateBy(userName);
            wmsRawStock.setCreateDate(currentDate);
            wmsRawStockMapper.insertWmsRawStock(wmsRawStock);
        }
    }

    public void syncToErp() {
        //todo 根据质检状态是通过的同步给ERP
    }

}
