package com.prolog.upcloud.base.wh.operate.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.prolog.cs.biz.inbound.constant.BizConstant;
import com.prolog.framework.authority.core.dto.UserDTO;
import com.prolog.framework.authority.user.UserTemplate;
import com.prolog.framework.core.exception.PrologException;
import com.prolog.framework.utils.DateUtils;
import com.prolog.framework.utils.MapUtils;
import com.prolog.framework.utils.StringUtils;
import com.prolog.upcloud.base.wh.operate.model.WmsReplenishD;
import com.prolog.upcloud.base.wh.operate.resource.IntegrationResource;
import com.prolog.upcloud.base.wh.operate.vo.MoveConfirmParamsVO;
import com.prolog.upcloud.base.wh.operate.vo.ReplenishDetailVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Lazy
@Service
public class DeviceLocatorHandler {

	private static Logger logger = LoggerFactory.getLogger(DeviceLocatorHandler.class);

	@Autowired
	private IntegrationResource integrationResource;


	@Value("${prolog.integration.instockTransforId:284}")
	private String instockTransforId;

	@Autowired
	private UserTemplate userTemplate;

	@Value("${prolog.integration.token}")
	private String token;
	
	public void transfor2Device(List<WmsReplenishD> deviceWmsReplenishDList,MoveConfirmParamsVO confirmParamsVO) {
        logger.info("WmsReplenishH replenishH transfor2Device deviceWmsReplenishDList："+ JSONObject.toJSONString(deviceWmsReplenishDList));
        logger.info("WmsReplenishH replenishH transfor2Device confirmParamsVO："+ JSONObject.toJSONString(confirmParamsVO));
        WmsReplenishD wmsReplenishD = deviceWmsReplenishDList.get(0);
		UserDTO userDTO = userTemplate.getUserDTO();
		Map<String, Object> resultData = new HashMap<>();
		Map<String, Object> headMap = new HashMap<>();
        //由于WMS拣选时，可以跨单，所以HeadId重复冲突，detailId唯一解决
		headMap.put("djbh", wmsReplenishD.getDetailId());
		headMap.put("rq", new Date());
        String cargoOwnerId = wmsReplenishD.getCargoOwnerId();
        headMap.put("dwid", cargoOwnerId);
		headMap.put("ry_cgy", userDTO.getId());
		headMap.put("ry_czy", userDTO.getId());
		headMap.put("ry_shouhy", userDTO.getId());
		headMap.put("ry_zjy", userDTO.getId());
		headMap.put("shr", userDTO.getId());
		headMap.put("sf_wc", "0");
		headMap.put("sf_xc", "0");
		headMap.put("sf_zx", "0");
		headMap.put("djbh_sj", wmsReplenishD.getId());
		headMap.put("rktype", "5");
		headMap.put("yzid", cargoOwnerId);
		headMap.put("bz", "N/A");
		List<Map> dataItemList = new ArrayList<>();
        for (int i = 0; i < deviceWmsReplenishDList.size(); i++) {
            WmsReplenishD tempVO = deviceWmsReplenishDList.get(i);
			ReplenishDetailVO v=confirmParamsVO.getReplenishDetailVOList().stream().
					filter(t->t.getLineId().equals(tempVO.getDetailId())).findFirst().orElse(null);
		    Map<String, Object> table = new HashMap<>();
            table.put("djbh", wmsReplenishD.getDetailId());
            table.put("tptm", v==null?null:v.getSrcLineId());
            table.put("dj_sort", (i+1));
            table.put("spid", tempVO.getItemId());
            table.put("sl", tempVO.getPieceQuantity());
            table.put("js", tempVO.getPieceQuantity().divide(tempVO.getConversionRate(), 0));
            table.put("lss", 0);
            table.put("ph", tempVO.getManufacturerLotNum());
            table.put("rq_sc", DateUtils.format(tempVO.getBatchProductionDate(),"yyyy-MM-dd HH:mm:ss"));
            table.put("yxqz", DateUtils.format(tempVO.getBatchExpiredDate(),"yyyy-MM-dd HH:mm:ss"));
            table.put("sf_zx", "0");
            table.put("pch", tempVO.getBatchId());
            table.put("yspd", "1");
            table.put("cgdd_sort", 1);
            table.put("sl_ywc", 0);
            table.put("yzid", cargoOwnerId);
            table.put("dj_sort_sj", 1);
            table.put("bz", "N/A");
            table.put("task_id", tempVO.getDetailId());
            dataItemList.add(table);
        }
        headMap.put("data_itemlist", dataItemList);
		resultData.put("resultData", headMap);
		askIntegration(instockTransforId,resultData);
	}

	/**
	 * 调用接口平台
	 * @param interfaceId
	 * @param param
	 * @return
	 */
	public JSONObject askIntegration(String interfaceId, Map<String,Object> param){
		Map paramMap = MapUtils.put("token", token).put("interfaceId", interfaceId).getMap();
		if(param != null)
			paramMap.put("data",param);
		logger.info("integrationResource.httpService入参为interfaceId："+interfaceId +",data:"+JSONObject.toJSONString(param));
		String result = integrationResource.httpService(paramMap);
		logger.info("integrationResource.httpService返回为interfaceId："+interfaceId +",result:"+result);
		JSONObject json = JSONObject.parseObject(result);
		if (json.containsKey("success") && !json.getBoolean("success")) {
			throw new PrologException("接口平台调用错误:" + json);
		}
		return json;
	}

	private String convertRcvType(String rcvType) {
		String result = null;
		if (!StringUtils.isBlank(rcvType)) {
			if (BizConstant.PURCHASE_IN.equals(rcvType)) {
				result = "采购入库";
			}
			if (BizConstant.SALE_RETURN_IN.equals(rcvType)) {
				result = "销售退回";
			}
			if (BizConstant.ALLOT_IN.equals(rcvType)) {
				result = "调拨入库";
			}
			if (BizConstant.MOVE_IN.equals(rcvType)) {
				result = "移库入库";
			}
			if (BizConstant.ACCOUNT_REG_IN.equals(rcvType)) {
				result = "调账入库";
			}
			if (BizConstant.OVERSTEP_IN.equals(rcvType)) {
				result = "越库入库";
			}
			if (BizConstant.STRAIGHT_IN.equals(rcvType)) {
				result = "直调入库";
			}
			if (BizConstant.HOSTED_IN.equals(rcvType)) {
				result = "代管入库";
			}
			if (BizConstant.WAIT_CHECK_IN.equals(rcvType)) {
				result = "待检入库";
			}
			if (BizConstant.INSTRUMENT_IN.equals(rcvType)) {
				result = "器械入库";
			}
			if (BizConstant.FREE_IN.equals(rcvType)) {
				result = "赠品入库";
			}
			if (BizConstant.BLANK_ENTITY_IN.equals(rcvType)) {
				result = "空入入库(有实物)";
			}
			if (BizConstant.BLANK_IN.equals(rcvType)) {
				result = "空入入库(无实物)";
			}
			if (BizConstant.BLANK_RETURN_ENTITY_IN.equals(rcvType)) {
				result = "空退入库(有实物)";
			}
			if (BizConstant.BLANK_RETURN_IN.equals(rcvType)) {
				result = "空退入库(无实物)";
			}
			return result;
		}
		return result;
	}

	public static String getStringDate() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = formatter.format(currentTime);
		return dateString;
	}

	public static String convertStringDate(Date date) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = formatter.format(date);
		return dateString;
	}

	private String convertRqcResult(String result) {
		return "合格";
	}
}
