package com.cim.idm.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cim.idm.framework.IDMFrameServiceProxy;
import com.cim.idm.model.PalletizingDto;
import com.cim.idm.utils.AjaxResult;
import com.cim.idm.utils.CodeGenerator;
import io.swagger.annotations.Api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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 java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api("库内管理组托拆托接口")
@RestController
@RequestMapping("/api/Palletizing")
@EnableAutoConfiguration
public class PalletizingController {
	
	 private static Log log = LogFactory.getLog(PalletizingController.class);


	 @Autowired
	 private CodeGenerator codeGenerator;

	 
	@RequestMapping(value = "/scanCode", method = RequestMethod.POST)
	public AjaxResult ScanCode(@RequestBody JSONObject in ) throws Exception{

		PalletizingDto pallet = JSON.toJavaObject(in, PalletizingDto.class);

		String materialPackingName = pallet.getMaterialPackingName();
		String palletNo = pallet.getPalletNo();

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("MATERIALPACKINGNAME", materialPackingName);

		String PackSql = "SELECT * FROM MATERIALPACKING m WHERE STOCKSTATE = 'Stocked' AND MATERIALPACKINGNAME = :MATERIALPACKINGNAME";

		List<Map<String,Object>> pckList = IDMFrameServiceProxy.getSqlTemplate().queryForList(PackSql, map);

		if(pckList.isEmpty()) {
			 return AjaxResult.me().setSuccess(false).setMessage("未找到在库的相关扫描条码！");
		}

		String charge = pckList.get(0).get("CHARGE").toString();

		String malSql = "SELECT * FROM MATERIALPACKINGPALLET m WHERE  MATERIALPACKINGNAME = :MATERIALPACKINGNAME AND UNBINDFLAG != 'Y'";

		List<Map<String,Object>> list = IDMFrameServiceProxy.getSqlTemplate().queryForList(malSql, map);

		String newPalletNo;

		if(list.isEmpty() && palletNo.isEmpty()) {
			// 生成条码
			newPalletNo = CodeGenerator.generateCode();
			ArrayList<Object> arr = new ArrayList<>();
			Map<String, Object> objMap = new HashMap<String, Object>();
			objMap.put("MATERIALPACKINGNAME", materialPackingName);
			objMap.put("PALLETNO", newPalletNo);
			objMap.put("CHARGE", charge);
			arr.add(objMap);

			return AjaxResult.me().setResultObj(arr);

		}else {

			// 如果扫描的托盘号不存在，则用之前扫的条码托盘号，如果扫描的托盘号存在，则用扫的托盘号带出所有的这个托盘号的条码
			if(list.isEmpty()) {
				ArrayList<Object> arrList = new ArrayList<>();
				Map<String, Object> plMap = new HashMap<String, Object>();
				plMap.put("MATERIALPACKINGNAME", materialPackingName);
				plMap.put("PALLETNO", palletNo);
				plMap.put("CHARGE", charge);
				arrList.add(plMap);

				return AjaxResult.me().setResultObj(arrList);
			}else {
				newPalletNo = list.get(0).get("PALLETNO") == null ? "" : list.get(0).get("PALLETNO").toString();

				if(!palletNo.isEmpty() && !palletNo.equals(newPalletNo)) {
					return AjaxResult.me().setSuccess(false).setMessage("扫描条码已绑定的托盘号与之前扫描的条码托盘号不一致");
				}
				String pallNoSql = "SELECT * FROM MATERIALPACKINGPALLET m WHERE  PALLETNO = :PALLETNO AND UNBINDFLAG != 'Y'";
				map.put("PALLETNO", newPalletNo);
				List<Map<String,Object>> pallNoList = IDMFrameServiceProxy.getSqlTemplate().queryForList(pallNoSql, map);

				return AjaxResult.me().setResultObj(pallNoList);
			}

		}

	}

	@RequestMapping(value = "/addPalletizing", method = RequestMethod.POST)
	@Transactional
	public AjaxResult AddPalletizing(@RequestBody JSONObject in ) throws Exception{
		PalletizingDto pallet = JSON.toJavaObject(in, PalletizingDto.class);
		String userId = pallet.getUserId();

		List<Map<String, Object>> boxList = pallet.getBoxList();
		for (Map<String, Object> map : boxList) {
			String materialPackingName = map.get("MATERIALPACKINGNAME").toString();
			String palletNo = map.get("PALLETNO").toString();
			String charge = map.get("CHARGE").toString();

			Map<String, Object> map1 = new HashMap<String, Object>();
			map1.put("MATERIALPACKINGNAME", materialPackingName);
			map1.put("PALLETNO", palletNo);
			map1.put("CHARGE", charge);
			map1.put("USERID", userId);
			map1.put("UNBINDFLAG", "N");
			String qSql = "SELECT * FROM MATERIALPACKINGPALLET m WHERE  m.MATERIALPACKINGNAME = :MATERIALPACKINGNAME AND m.PALLETNO = :PALLETNO  AND m.UNBINDFLAG != 'Y'";
			List<Map<String,Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(qSql, map1);
			if(queryForList.size() == 0) {
				String sql = "INSERT INTO MATERIALPACKINGPALLET (MATERIALPACKINGNAME,PALLETNO,CHARGE,USERID,MAKEDATE,UNBINDFLAG) VALUES (:MATERIALPACKINGNAME,:PALLETNO,:CHARGE,:USERID,SYSDATE,:UNBINDFLAG)";
				IDMFrameServiceProxy.getSqlTemplate().update(sql, map1);
			}else {
				String updSql = "UPDATE MATERIALPACKINGPALLET m SET m.UNBINDFLAG=:UNBINDFLAG,m.MAKEDATE=SYSDATE,m.USERID=:USERID WHERE m.MATERIALPACKINGNAME = :MATERIALPACKINGNAME AND m.PALLETNO = :PALLETNO";
				IDMFrameServiceProxy.getSqlTemplate().update(updSql, map1);
			}

		}
		return AjaxResult.me().setResultObj(null);
	}

	@RequestMapping(value = "/delPalletizing", method = RequestMethod.POST)
	public AjaxResult DelPalletizing(@RequestBody JSONObject in ) throws Exception{
		PalletizingDto pallet = JSON.toJavaObject(in, PalletizingDto.class);
		String materialPackingName = pallet.getMaterialPackingName();
		String palletNo = pallet.getPalletNo();
		String unbindUserId = pallet.getUnbindUserId();



		Map<String, Object> map = new HashMap<String, Object>();
		map.put("MATERIALPACKINGNAME", materialPackingName);
		map.put("PALLETNO", palletNo);
		String qsql = "SELECT * FROM MATERIALPACKINGPALLET m WHERE  m.MATERIALPACKINGNAME = :MATERIALPACKINGNAME AND m.PALLETNO = :PALLETNO";
		List<Map<String,Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(qsql, map);
		if(queryForList.size() == 0) {
			return AjaxResult.me().setSuccess(false).setMessage("此标签不存在，未先组托保存，请先组托！");
		}

//		String sql = "DELETE FROM MATERIALPACKINGPALLET m WHERE  m.MATERIALPACKINGNAME = :MATERIALPACKINGNAME AND m.PALLETNO = :PALLETNO";
		String sql = "UPDATE MATERIALPACKINGPALLET m SET m.UNBINDFLAG=:UNBINDFLAG,m.UNBINDDATE=SYSDATE,m.UNBINDUSERID=:UNBINDUSERID WHERE m.MATERIALPACKINGNAME = :MATERIALPACKINGNAME AND m.PALLETNO = :PALLETNO";
		map.put("UNBINDFLAG", "Y");
		map.put("UNBINDUSERID", unbindUserId);
		IDMFrameServiceProxy.getSqlTemplate().update(sql, map);

		return AjaxResult.me().setResultObj(null);
	}

}
