package com.cim.idm.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cim.idm.dao.PurchaseReturnServiceDao;
import com.cim.idm.framework.IDMFrameServiceProxy;
import com.cim.idm.model.po.MaterialReceiveRequest;
import com.cim.idm.model.PurchaseReturnDto;
import com.cim.idm.model.StockOutDto;
import com.cim.idm.service.PurchaseReturnService;
import com.cim.idm.utils.AjaxResult;
import com.cim.idm.wmsextend.generic.errorHandler.CustomException;
import com.cim.idm.wmspackage.materialpacking.MaterialPackingServiceProxy;
import com.cim.idm.wmspackage.materialpacking.management.data.MaterialPackingKey;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.cim.idm.service.Impl.InvoiceServiceImpl;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.*;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api("单据接口")
@RestController
@RequestMapping("/purchase")
@EnableAutoConfiguration
public class PurchaseReturnController {

	@Autowired
	private InvoiceServiceImpl InvoiceServiceImpl;

	@Autowired
	private PurchaseReturnServiceDao purchaseReturnServiceDao;

	@Autowired
	private PurchaseReturnService purchaseReturnService;

	/**
	 * 获取采购退货单号列表
	 * @param in
	 * @return
	 */
	@RequestMapping(value = "/getPurchaseReturnList", method = RequestMethod.POST)
	public AjaxResult getPurchaseReturnList(@RequestBody JSONObject in ){

		MaterialReceiveRequest materialReceiveRequest = JSON.toJavaObject(in, MaterialReceiveRequest.class);
		
		String receiverequestname = materialReceiveRequest.getReceiveRequestName() == null ? "" : materialReceiveRequest.getReceiveRequestName();
		String erpfactory = materialReceiveRequest.getErpFactory();
		String siteName = materialReceiveRequest.getSiteName();
		String user = materialReceiveRequest.getUser();
		receiverequestname = "%" + receiverequestname + "%";

        try {
            List<PurchaseReturnDto> purchaseReturnList =
					purchaseReturnService.getPurchaseReturnList(siteName, user, receiverequestname, erpfactory);
			//将List<PurchaseReturnDto>的key值转换成大写工具类
            List<Map<String, Object>> upperCaseList = purchaseReturnList.stream()
                    .map(dto -> toUpperCaseMap(dto))
                    .collect(Collectors.toList());
			return AjaxResult.me().setResultObj(upperCaseList);
        } catch (Exception e) {
			return AjaxResult.me().setErrorCode(500).setMessage("未找到对应的数据！");
        }
//
//        String sql = "SELECT\r\n" +
//				"	DISTINCT M.RECEIVEREQUESTNAME\r\n" +
//				"FROM\r\n" +
//				"	MATERIALRECEIVEREQUESTDETAIL M\r\n" +
//				"	LEFT JOIN MATERIALRECEIVEREQUEST R ON\r\n" +
//				"	R.RECEIVEREQUESTNAME = M.RECEIVEREQUESTNAME\r\n" +
//				"WHERE\r\n" +
//				"	M.SITENAME = :SITENAME\r\n" +
////				"	AND R.RECEIVEREQUESTTYPE = '45'\r\n" +
//				"	AND R.RETURNFLAG = 'Y'\r\n" +
//				"	AND R.RECEIVEREQUESTSTATE <> 'Completed'\r\n" +
//				"	AND M.ERPFACTORY = :ERPFACTORY\r\n" +
//				"	AND M.RECEIVEREQUESTNAME LIKE :RECEIVEREQUESTNAME";
//
//		Map<String, Object> bindMap = new HashMap<String, Object>();
//		bindMap.put("SITENAME",siteName);
//		bindMap.put("RECEIVEREQUESTNAME","%" + receiverequestname + "%");
//		bindMap.put("ERPFACTORY",erpfactory);
//		List<Map<String,Object>> list = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindMap);
//
//		if(Objects.isNull(list) || list.isEmpty()) {
//			return AjaxResult.me().setErrorCode(500).setMessage("未找到对应的数据！");
//		}
//		return AjaxResult.me().setResultObj(list);

	}
	
	/**
	 * 获取采购退货单信息
	 * @param in
	 * @return
	 */
	@RequestMapping(value = "/getPurchaseReturnInfo", method = RequestMethod.POST)
	public AjaxResult getPurchaseReturnInfo(@RequestBody JSONObject in ){

		 MaterialReceiveRequest materialReceiveRequest = JSON.toJavaObject(in,  MaterialReceiveRequest.class);
		
		String receiverequestname = materialReceiveRequest.getReceiveRequestName() == null ? "" : materialReceiveRequest.getReceiveRequestName();
		String erpfactory = materialReceiveRequest.getErpFactory();
		String siteName = materialReceiveRequest.getSiteName();

        try {
            List<PurchaseReturnDto> purchaseReturnInfo =
					purchaseReturnService.getPurchaseReturnInfo(siteName, materialReceiveRequest.getUser(), receiverequestname);
			List<Map<String, Object>> upperCaseList = purchaseReturnInfo.stream()
                    .map(dto -> toUpperCaseMap(dto))
                    .collect(Collectors.toList());
			return AjaxResult.me().setResultObj(purchaseReturnInfo);
        } catch (Exception e) {
			return AjaxResult.me().setErrorCode(500).setMessage("未找到对应的数据！");
        }
//
//        String sql = "SELECT A.RECEIVEREQUESTNAME,A.RECEIVEREQUESTDETAILNAME,C.MATERIALSPECNAME,A.DESCRIPTION,\r\n" +
//				"m.FNAME  MATERIALUNIT,A.REQUESTQUANTITY,A.CHARGE,A.RECEIVEDQUANTITY,C.DESC_CN,\r\n" +
//				"A.ERPLOCATION,D.ERPFACTORY,D.RETURNFLAG,D.SITENAME,'0' AS SELECTEDQUANTITY,A.SDK_ID,A.PHASE\r\n" +
//				"from\r\n" +
//				"MATERIALRECEIVEREQUESTDETAIL A LEFT JOIN MATERIALUNIT m ON  A.MATERIALUNIT = m.FNUMBER ,MATERIALSPEC C,MATERIALRECEIVEREQUEST D \r\n" +
//				"where  A.SITENAME  = :SITENAME\r\n" +
//				"AND  A.RECEIVEREQUESTNAME  = :RECEIVEREQUESTNAME\r\n" +
//				"AND D.RECEIVEREQUESTNAME = A.RECEIVEREQUESTNAME\r\n" +
//				"AND A.MATERIALSPECNAME = C.MATERIALSPECNAME\r\n" +
//				"AND D.RETURNFLAG='Y'\r\n" +
//				"ORDER BY A.RECEIVEREQUESTDETAILNAME";
//
//		Map<String, Object> bindMap = new HashMap<String, Object>();
//		bindMap.put("SITENAME",siteName);
//		bindMap.put("RECEIVEREQUESTNAME",receiverequestname);
//		List<Map<String,Object>> list = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindMap);
//
//		if(Objects.isNull(list) || list.isEmpty()) {
//			return AjaxResult.me().setErrorCode(500).setMessage("未找到对应的数据！");
//		}
//		return AjaxResult.me().setResultObj(list);

	}
	
	/**
	 * 备货或者取消
	 * @param in
	 * @return
	 */
	@Transactional
	@RequestMapping(value = "/purDessignOrAssign", method = RequestMethod.POST)
	public AjaxResult UnFIFODessignOrAssign(@RequestBody JSONObject in ){
		 MaterialReceiveRequest materialReceiveRequest = JSON.toJavaObject(in,  MaterialReceiveRequest.class);
		String type = materialReceiveRequest.getType();//Assign 备货 Dessign 解绑
		String materialPackingName = materialReceiveRequest.getMaterialPackingName();//标签
		String materialSpecName = materialReceiveRequest.getMaterialSpecName();
		String receiveRequestName = materialReceiveRequest.getReceiveRequestName();
		String materialQuantity = materialReceiveRequest.getMaterialQuantity();
		String materialQuantity2 = materialReceiveRequest.getMaterialQuantity2();
		String sdk_id = materialReceiveRequest.getSdk_id() == null ? "" : materialReceiveRequest.getSdk_id();
		String phase = materialReceiveRequest.getPhase() == null ? "" :  materialReceiveRequest.getPhase();
		String user = materialReceiveRequest.getUser();
		//根据条码查询库存状态
		String judge = "SELECT\r\n" + 
				"m.SDK_ID,MATERIALSPECNAME,\r\n" + 
				"m.PHASE,\r\n" + 
				"CASE WHEN MATERIALQUANTITY2 > 0 THEN MATERIALQUANTITY2\r\n" + 
				"ELSE MATERIALQUANTITY   END    MATERIALQUANTITY2 ,\r\n" + 
				"m.SHIPREQUESTNAME,\r\n" + 
				"m.STOCKSTATE,\r\n" + 
				"m.PACKINGGRADE ,\r\n" + 
				"m.OQARESULTSTATE,\r\n" + 
				"m.SPECIALSTATE,\r\n" + 
				"m.OQARESULT\r\n" + 
				"FROM\r\n" + 
				"MATERIALPACKING m\r\n" + 
				"WHERE\r\n" + 
				"m.MATERIALPACKINGNAME = :MATERIALPACKINGNAME AND \r\n" + 
				"m.PACKINGSTATE='Released' AND m.HOLDSTATE='N'";
		Map<String, Object> hashMap2 = new HashMap<String,Object> ();
		hashMap2.put("MATERIALPACKINGNAME", materialPackingName);
		List<Map<String, Object>> queryForList2 = IDMFrameServiceProxy.getSqlTemplate().queryForList(judge, hashMap2);
		if (queryForList2 != null && queryForList2.size() > 0) {
			materialSpecName = queryForList2.get(0).get("MATERIALSPECNAME") == null ? "" : queryForList2.get(0).get("MATERIALSPECNAME").toString();
			sdk_id = queryForList2.get(0).get("SDK_ID") == null ? "" : queryForList2.get(0).get("SDK_ID").toString();
			phase = queryForList2.get(0).get("PHASE") == null ? "" : queryForList2.get(0).get("PHASE").toString();
			materialQuantity2 = queryForList2.get(0).get("MATERIALQUANTITY2") == null ? "" : queryForList2.get(0).get("MATERIALQUANTITY2").toString();
			String  invoice = queryForList2.get(0).get("SHIPREQUESTNAME") == null ? "" : queryForList2.get(0).get("SHIPREQUESTNAME").toString();
			String stockState = queryForList2.get(0).get("STOCKSTATE") == null ? "" : queryForList2.get(0).get("STOCKSTATE").toString();
			String packinggrade = queryForList2.get(0).get("PACKINGGRADE") == null ? "" : queryForList2.get(0).get("PACKINGGRADE").toString();
//			String exp = queryForList2.get(0).get("EXP") == null ? "" : queryForList2.get(0).get("EXP").toString();
			String oqaresultstate = queryForList2.get(0).get("OQARESULTSTATE") == null ? "" : queryForList2.get(0).get("OQARESULTSTATE").toString();
//			String oqaresult = queryForList2.get(0).get("OQARESULT") == null ? "" : queryForList2.get(0).get("OQARESULT").toString();
			String specialstate = queryForList2.get(0).get("SPECIALSTATE") == null ? "" : queryForList2.get(0).get("SPECIALSTATE").toString();
			
			if (!"Stocked".equals(stockState)) {
				return AjaxResult.me().setSuccess(false).setMessage("条码不在库！");
			}
			if (!"NG".equals(packinggrade)) {
				return AjaxResult.me().setSuccess(false).setMessage("批次不能为合格！");
			}
//			if (!"1".equals(exp)) {
//				return AjaxResult.me().setSuccess(false).setMessage("批次已过期！");
//			}
			if ("PREOQA".equals(oqaresultstate)) {
				return AjaxResult.me().setSuccess(false).setMessage("质检状态不对！");
			}
//			if (!"".equals(invoice)) {
//				return AjaxResult.me().setSuccess(false).setMessage("条码已被" + invoice + "备货！");
//			}
			
			if (!"2".equals(specialstate)) {
				return AjaxResult.me().setSuccess(false).setMessage("批次不是退供应商状态！");
			}
			
			
			
		} else {
			return AjaxResult.me().setSuccess(false).setMessage("未找到相对应的条码！");
		}
		//查询单据类型
		String sql = "SELECT \r\n" + 
				"	m.RECEIVEREQUESTTYPE,\r\n" + 
				"	m.RECEIVEREQUESTDETAILTYPE,\r\n" + 
				"	t.RECEIVEREQUESTDETAILNAME,\r\n" + 
				"	t.MATERIALSPECNAME ,\r\n" + 
				"	SUM(t.REQUESTQUANTITY - t.RECEIVEDQUANTITY) MINUSQTY,t.SDK_ID,t.PHASE\r\n" + 
				"	FROM\r\n" + 
				"	MATERIALRECEIVEREQUESTDETAIL t\r\n" + 
				"	LEFT JOIN MATERIALRECEIVEREQUEST m ON\r\n" + 
				"	t.RECEIVEREQUESTNAME = m.RECEIVEREQUESTNAME\r\n" + 
				"	WHERE\r\n" + 
				"	m.RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME\r\n" + 
				"	AND t.MATERIALSPECNAME = :MATERIALSPECNAME\r\n" + 
				"	AND (:SDK_ID IS NULL\r\n" + 
				"	OR t.SDK_ID = :SDK_ID)\r\n" + 
				"	AND (:PHASE IS NULL OR t.PHASE = :PHASE)\r\n" + 
				"	GROUP BY m.RECEIVEREQUESTTYPE ,\r\n" + 
				"	m.RECEIVEREQUESTDETAILTYPE,t.RECEIVEREQUESTDETAILNAME,\r\n" + 
				"	t.MATERIALSPECNAME,t.SDK_ID,t.PHASE\r\n" + 
				"	ORDER BY\r\n" + 
				"	t.MATERIALSPECNAME ,\r\n" + 
				"	t.SDK_ID,\r\n" + 
				"	t.PHASE";
		Map<String, Object> hashMap = new HashMap<String,Object> ();
		hashMap.put("RECEIVEREQUESTNAME", receiveRequestName);
		hashMap.put("MATERIALSPECNAME", materialSpecName);
		hashMap.put("SDK_ID", sdk_id);
		hashMap.put("PHASE", phase);
		List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, hashMap);
		if(Objects.isNull(queryForList) || queryForList.isEmpty()) {
			return AjaxResult.me().setSuccess(false).setMessage("条码与单据无法匹配！");
		}
		String shipRequestType = queryForList.get(0).get("RECEIVEREQUESTTYPE").toString();
		String shipRequestDetailType = queryForList.get(0).get("RECEIVEREQUESTDETAILTYPE").toString();
		String receiveRequestDetailName = queryForList.get(0).get("RECEIVEREQUESTDETAILNAME").toString();
		String minusQty = queryForList.get(0).get("MINUSQTY").toString();
		BigDecimal FminusQty = new BigDecimal(minusQty);
		BigDecimal Fzero = new BigDecimal(0);
		//"SHIPREQUESTDETAILTYPE": "4Y-Cxx-03",//跨组织领料调拨单 
		//"BLSQ4K".equals(shipRequestType) || "4Y".equals(shipRequestType) || "CKSQ4I".equals(shipRequestType)
		int dy0 = FminusQty.compareTo(Fzero);
		MaterialPackingKey materialPackingKey = new MaterialPackingKey("SDK",materialPackingName);
		com.cim.idm.wmspackage.materialpacking.management.data.MaterialPacking selectByKey = MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(materialPackingKey);
		if ("Assign".equals(type)) {
			System.out.println("45".equals(shipRequestType) + "*****************");
			if (dy0 < 0) {//只能超发一个
				return AjaxResult.me().setSuccess(false).setMessage("采购退货不允许超发！");
			}
//			if ("4Y".equals(shipRequestType)) {//调拨单
//				if ( "4Y-Cxx-03".equals(shipRequestDetailType)) {
//					if (dy0 < 0) {//只能超发一个
//						return AjaxResult.me().setSuccess(false).setMessage("只能超发一个不能出库了！");
//					}
//				} 
//			} else if ("BLSQ4K".equals(shipRequestType)) {//领料
//				if (dy0 < 0) {//只能超发一个
//					return AjaxResult.me().setSuccess(false).setMessage("只能超发一个不能出库了！");
//				}
//			} else if ("CKSQ4I".equals(shipRequestType)) { //其他出库
//				if (dy0 < 0) {//只能超发一个
//					return AjaxResult.me().setSuccess(false).setMessage("只能超发一个不能出库了！");
//				}
//			} else if ("4C".equals(shipRequestType)) {
//				if (dy0 < 0) {//只能超发一个
//					return AjaxResult.me().setSuccess(false).setMessage("销售不允许超发！");
//				}
//			}else {
//				return AjaxResult.me().setSuccess(false).setMessage("单据类型不正确！");
//			}
		} else if ("Dessign".equals(type)) {
			
		}
		try {
			InvoiceServiceImpl.Reserve3(selectByKey, receiveRequestName,receiveRequestDetailName, materialSpecName,sdk_id, phase, type, "SDK", user,materialQuantity2,"N");
		} catch (CustomException e) {
			e.printStackTrace();
			return AjaxResult.me().setSuccess(false).setMessage(e.toString());
		}
		
		return  AjaxResult.me().setSuccess(true).setMessage("备货成功");
	}
	
	/**
	 * 查询单据时自动备货
	 * @param in
	 * @return
	 */
	@Transactional
	@RequestMapping(value = "/getPurPackingInfo", method = RequestMethod.POST)
	public AjaxResult getReservePackingInfo(@RequestBody JSONObject in ){
		 MaterialReceiveRequest materialShipRequest = JSON.toJavaObject(in,  MaterialReceiveRequest.class);
		String receiveRequestName = materialShipRequest.getReceiveRequestName() == null ? "" : materialShipRequest.getReceiveRequestName();
		String user = materialShipRequest.getUser();
			String ressSql = "SELECT\r\n" + 
					"	A.MATERIALPACKINGNAME ,A.MATERIALSPECNAME,A.MATERIALQUANTITY, CASE WHEN MATERIALQUANTITY2 > 0 THEN A.MATERIALQUANTITY2 \r\n" + 
					"	ELSE A.MATERIALQUANTITY END    MATERIALQUANTITY2,A.AREANAME ,A.SHELFNAME ,\r\n" + 
					"	A.CHARGE ,\r\n" + 
					"	TO_CHAR(A.RECEIVETIME, 'YYYY-MM-DD') RECEIVETIME,A.SDK_ID,A.PHASE,\r\n" + 
					"	be.DESCRIPTION ERPLOCATION,\r\n" + 
					"	s.DESCRIPTION LOCATIONNAME,\r\n" + 
					"	'Y' BHFLG, A.SHIPREQUESTNAME,A.SHIPREQUESTDETAILNAME, \r\n" + 
					"	'N' IS_CHECK\r\n" + 
					"	FROM\r\n" + 
					"	MATERIALPACKING A\r\n" + 
					"	LEFT JOIN SDK_SPEC SS ON\r\n" + 
					"	A.SDK_ID = SS.SDK_ID\r\n" + 
					"	LEFT JOIN \r\n" + 
					"	MATERIALSPEC B ON\r\n" + 
					"	A.MATERIALSPECNAME = B.MATERIALSPECNAME\r\n" + 
					"	LEFT JOIN BS_ERPLOCATION be ON\r\n" + 
					"	A.ERPLOCATION = be.ERPLOCATIONNAME\r\n" + 
					"	LEFT JOIN STORAGESPEC s ON\r\n" + 
					"	A.LOCATIONNAME = s.STORAGENAME AND A.ERPLOCATION = s.ERPLOCATION \r\n" + 
					"	WHERE\r\n" + 
					"	1 = 1\r\n" + 
					"	AND A.MATERIALSPECNAME = B.MATERIALSPECNAME\r\n" + 
					"	AND A.SITENAME = B.SITENAME\r\n" + 
					"	AND A.SITENAME =:SITENAME\r\n" + 
					"	AND A.SHIPREQUESTNAME = :SHIPREQUESTNAME\r\n" + 
					"	AND A.STOCKSTATE = 'Stocked'\r\n" + 
					"	AND A.PACKINGSTATE = 'Released'\r\n" + 
					"	AND A.HOLDSTATE = 'N'\r\n" + 
					"	AND A.PACKINGGRADE = 'NG'\r\n" + 
					"	AND A.MATERIALQUANTITY <> '0'\r\n" + 
					"	AND (A.NPFLAG <> 'Y'\r\n" + 
					"	OR A.NPFLAG IS NULL)\r\n" + 
					"	AND A.OQARESULTSTATE <> 'PREOQA'\r\n" + 
					"	AND A.SPECIALSTATE = '2'\r\n" + 
					"	AND to_char(A.EXPIRINGDATE, 'yyyymmdd') >= to_char(SYSDATE, 'yyyymmdd') ORDER BY A.MATERIALSPECNAME,A.SDK_ID,A.PHASE, A.RECEIVETIME";
		Map<String, Object> hashMap = new HashMap<String,Object> ();
		hashMap.put("SITENAME", "SDK");
		hashMap.put("SHIPREQUESTNAME", receiveRequestName);
		List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(ressSql, hashMap);
		return AjaxResult.me().setResultObj(queryForList);
	}

	@RequestMapping(value = "/CompleteReceiveRequest", method = RequestMethod.POST)
	public AjaxResult completeShipRequest(@RequestBody JSONObject in ){
		StockOutDto ms = JSON.toJavaObject(in, StockOutDto.class);
		String shipRequestName = ms.getShipRequestName();
		String siteName = "SDK";
		String user = ms.getUser();
        try {
            purchaseReturnService.completeReceiveRequest(siteName, user, shipRequestName);
        } catch (Exception e) {
			return AjaxResult.me().setErrorCode(500).setMessage(e.toString());
        }
        return AjaxResult.me().setResultObj(null);
	}

    private Map<String, Object> toUpperCaseMap(PurchaseReturnDto dto) {
        Map<String, Object> map = new HashMap<>();
		//采用循环的方式将dto的key值转换成大写放到map
		for (Field field : dto.getClass().getDeclaredFields()) {
			field.setAccessible(true);
			try {
				map.put(field.getName().toUpperCase(), field.get(dto));
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
        return map;
    }
}
