package com.sifang.modules.supply.order.service;



import cn.hutool.core.collection.CollectionUtil;
import com.sifang.modules.q7link.entity.WuziOrder;
import com.sifang.modules.supply.order.constant.DeliverOrderConstants;
import com.sifang.modules.supply.order.dao.CrmSupplyMaterialDeliverOrderDao;
import com.sifang.modules.supply.order.dao.MaterialDeliverDetailDao;
import com.sifang.modules.supply.order.dao.MaterialDeliverOrderMsgDao;
import com.sifang.modules.supply.order.entity.CrmSupplyMaterialDeliverOrder;
import com.sifang.modules.supply.order.entity.CrmSupplyMaterialDeliverOrderDetail;
import com.sifang.modules.supply.order.vo.OrderDetailVo;
import com.sifang.modules.supply.order.vo.OrderTbQqVO;
import com.sifang.modules.supply.setting.dao.CrmSupplyWarehouseDao;
import com.sifang.modules.supply.setting.entity.CrmSupplyWarehouse;
import com.sifang.modules.supply.stock.dao.MaterialStockDao;
import com.sifang.modules.supply.stock.dao.SupplyMaterialDao;
import com.sifang.modules.supply.stock.entity.MaterialWarehouseStocks;
import com.sifang.modules.supply.stock.entity.SupplyMaterial;
import com.sifang.modules.supply.stock.service.SupplyMaterialKeepService;
import com.sifang.modules.supply.warehouse.entity.CrmSupplyMaterialKeep;
import com.sifang.modules.supply.warehouse.entity.SupplyMaterialBatch;
import com.sifang.modules.supply.warehouse.service.SupplyMaterialBatchService;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.entity.Operator;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Service
public class CrmSupplyMaterialDeliverOrderService extends BaseService {


    @Resource
    private CrmSupplyMaterialDeliverOrderDao crmSupplyMaterialDeliverOrderDao;
    @Autowired
    private SupplyMaterialBatchService batchService;
    @Autowired
    private SupplyMaterialKeepService materialKeepService;

    @Autowired
    CrmSupplyWarehouseDao warehouseDao;

    @Autowired
    MaterialDeliverOrderMsgDao deliverOrderMsgDao;

    @Autowired
    MaterialStockDao materialStockDao;

    @Autowired
    MaterialDeliverDetailDao deliverDetailDao;
    @Autowired
    private SupplyMaterialDao materialDao;




    public String queryCrmSupplyMaterialDeliverOrderId(String name){
        return crmSupplyMaterialDeliverOrderDao.queryCrmSupplyMaterialDeliverOrderId(name);
    }

    public void queryQqList(LayuiPage page, Map<String, String> map){
        page.setData(crmSupplyMaterialDeliverOrderDao.queryQqList(page, map));
        page.setCount(crmSupplyMaterialDeliverOrderDao.queryQqCount(map));
    }

    public void queryInStockList(LayuiPage page, Map<String, String> map){
        page.setData(crmSupplyMaterialDeliverOrderDao.queryInStockList(page, map));
        page.setCount(crmSupplyMaterialDeliverOrderDao.queryInStockCount(map));
    }

    /**
     * 同步到企企的订单信息
     * @param number
     * @return
     */
    public OrderTbQqVO tbDate(String number){
        OrderTbQqVO obj=  crmSupplyMaterialDeliverOrderDao.tbDate(number);
        return obj;
    }

    public OrderDetailVo queryOrderById(String id,String status){
      return   crmSupplyMaterialDeliverOrderDao.queryOrderById(id,status);
    }

    /**
     * 企企同步过来的订单根据条件暂存签收
     * @param map
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean orderSubmit(Map map, User user){
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
        CrmSupplyMaterialDeliverOrder order = crmSupplyMaterialDeliverOrderDao.get(String.valueOf(map.get("id")));
        //操作记录
        if(map.containsKey("submit") && "1".equals(map.get("submit"))){
            deliverOrderMsgDao.saveOptMsg(order.getId(), DeliverOrderConstants.OPT_RK, null, operator);
        }
        boolean result = crmSupplyMaterialDeliverOrderDao.orderSubmit(map);
        if(result && map.containsKey("submit") && "1".equals(map.get("submit"))) {
            CrmSupplyWarehouse warehouse = warehouseDao.get(order.getInWarehouseId());
            if (warehouse == null) {
                logger.error("warehouse未获取到信息, inWarehouseId：{}", order.getInWarehouseId());
                throw new IllegalArgumentException("入库仓库信息有误");
            }
            //warehouse.getType();//归属  1.供应链(平台)  2.经销商 3.供应商
            if (!"1".equals(warehouse.getType())) {
                logger.info("warehouse:{}, 不归属平台", warehouse);
                throw new IllegalArgumentException("入库仓库信息有误，只能归属于供应链");
            }
            List<CrmSupplyMaterialDeliverOrderDetail> details = deliverDetailDao.listDetailByOrderId(order.getId());
            if(CollectionUtil.isEmpty(details)){
                logger.info("details:{}, 订单详情", details);
                throw new IllegalArgumentException("订单详情为空");
            }
            for (CrmSupplyMaterialDeliverOrderDetail detail : details) {
                MaterialWarehouseStocks stocks = materialStockDao.findByWarehouse(detail.getMaterialId(), order.getInWarehouseId());
                SupplyMaterial material = materialDao.getById(detail.getMaterialId());
                if (material == null) {
                    logger.info("material is null, code : {}", detail.getMaterialCode());
                    throw new IllegalArgumentException("入库物料-" + detail.getMaterialCode() + " 信息有误");
                }
                //TODO 物料仓库库存调整
                if (stocks != null) {
                  materialStockDao.updateStock(detail,warehouse,material);
                } else {
                    stocks = materialStockDao.saveStock(detail,warehouse,material);
                }
                BigDecimal warning=stocks.getWarning().add(detail.getInAmount());
                //盘盈 入库 生成新批次
                String keepId = IdGen.uuid();
                SupplyMaterialBatch batch = batchService.createBatchForDeliver(order, detail, keepId);
                //生成入库记录
                CrmSupplyMaterialKeep keep = materialKeepService.createMaterialKeepForDeliver(order,detail,warning,
                        user,"1",batch,keepId,material);
            }
        }
        return result;
    }

    public int saveEntity(String orderId,String qqCode,String qqId){
        return crmSupplyMaterialDeliverOrderDao.saveEntity(orderId,qqCode,qqId);
    }

    public boolean saveWuziInfo(WuziOrder order){
        return crmSupplyMaterialDeliverOrderDao.saveWuziInfo(order);
    }

    public boolean savePickingIssue(String qqOrderId,String pickingIssueId,String pickingIssueCode){
        return crmSupplyMaterialDeliverOrderDao.savePickingIssue(qqOrderId, pickingIssueId, pickingIssueCode);
    }

    public WuziOrder getWuziOrder(String qqOrderId){
        return crmSupplyMaterialDeliverOrderDao.getWuziOrder(qqOrderId);
    }

}
