package abacus.springboot.example.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.abacus.pms.wsi.AccountServiceIF;
import com.abacus.pms.wsi.ProductServiceIF;
import com.abacus.xpos.foundation.wsi.EmployeeServiceIF;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import abacus.commons.exception.BusinessException;
import abacus.springboot.example.dao.JcBill;
import abacus.springboot.example.dao.JcBillInItem;
import abacus.springboot.example.dao.JcBillPhoto;
import abacus.springboot.example.dao.JcBillSourceItem;
import abacus.springboot.example.dao.JcSourceItem;
import abacus.springboot.example.util.DateUtil;
import abacus.springboot.example.vo.SiDepositlocation;
import abacus.springboot.example.wsi.JcBillServiceIF;

/**
 * <p>Title:JcBillInController</p>
   <p>Description: 前端相关-api</p>
   @author chuanZeng 
   @date 2026年8月18日
 */
@RestController
@RequestMapping(value = "/jc")
public class JcBillInController extends BaseServlet{

	private static final Logger LOG = LoggerFactory.getLogger(JcBillInController.class);
	
	@Autowired
	private JcBillServiceIF jcBillService;
	
	@Autowired
	private EmployeeServiceIF employeeService;
	
	@Autowired
	private ProductServiceIF productService;
	
	@Autowired
	private AccountServiceIF accountService;
	
	/**
	 * 	TODO （溯源入库-回购通知）--页面查询
	 * @param typ 1-溯源入库  2-回购通知
	 * @return
	 * @throws Throwable
	 */
	@RequestMapping(value = "queryJcBillPage", method = RequestMethod.POST)
	public JSONObject queryJcBillPage(
			@RequestParam(required = false) String from,
			@RequestParam(required = false) String thru,
			
			@RequestParam(required = false) String applicant,
			@RequestParam(required = false) String goods,
			@RequestParam(required = false) String id,
			@RequestParam(required = false) String billin,
			@RequestParam(required = false) String goodsid,
			@RequestParam(required = false) String product,
			@RequestParam(required = false) String status,
			@RequestParam(required = true) int typ,
			
			@RequestParam(required = true) int page,
			@RequestParam(required = true) int size
			)
	throws Throwable {
		try {
			
			// 申请起始时间
			String fromDate = null;
			if (StringUtils.isNotBlank(from)) {
				fromDate = DateUtil.formatDateTime(DateUtil.getFromDate(DateUtil.toDate(from)));
			}
			// 申请截止时间
			String thruDate = null;
			if (StringUtils.isNotBlank(thru)) {
				thruDate = DateUtil.formatDateTime(DateUtil.getThruDate(DateUtil.toDate(thru)));
			}
			
			// 当前页
//			int pageNumber = page/size + 1;
			Pageable pageable = PageRequest.of(page - 1, size);
			
			Page<JcBill> pages = jcBillService.queryJcBill(fromDate, thruDate, id, applicant,
					goods, billin, goodsid, product, status, typ, pageable);
			
			// 获取稽查单号集合
	        List<String> billIds = pages.getContent().stream()
                    .map(JcBill::getId) 
                    .collect(Collectors.toList());
	        
	        List<JcBillSourceItem> items = jcBillService.queryJcBillSourceItemInBillId(billIds);
	        
	        Map<String, JcBillSourceItem> mapItem = items.stream()
					.collect(Collectors.groupingBy(e -> {
						return e.getBillid();
					}, 
					Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0))
				));
	        
	        for(JcBill jcBill : pages.getContent()) {
	        	JcBillSourceItem item = mapItem.get(jcBill.getId());
	        	if(item != null) {
	        		jcBill.setRecsource(item.getRecsource());
	        		jcBill.setRecplatform(item.getRecplatform());
	        		jcBill.setChannel(item.getChannel());
	        	}
	        }
			
			JSONObject obj = new JSONObject();
			
			obj.put("list", pages.getContent());
			obj.put("total", pages.getTotalElements());
			
			return obj;
		}catch(Throwable e){
			LOG.error(e.getMessage(), e);
			e.printStackTrace();
			throw e;
		}
	}
		
	/**
	 * 	TODO 查询溯源详情
	 * @param billId
	 * @return
	 */
	@RequestMapping(value = "queryJcBillSourceItems", method = RequestMethod.POST)
	public List<JcBillSourceItem> queryJcBillSourceItems(
			@RequestParam(required = false) String billId
		)
	throws Throwable {
		try {
			
			List<JcBillSourceItem> items = jcBillService.queryJcBillSourceItemByBillId(billId);
			
			if(items == null) throw new BusinessException("溯源信息不存在！");
			
			Map<String, List<JcBillPhoto>> mapPhoto = jcBillService.queryJcBillPhoto(billId);
			
			for(JcBillSourceItem item : items) {
				
				// 稽查付款截图
				List<JcBillPhoto> fkts = mapPhoto.get(JcBillPhoto.JC_FK + "#" + String.valueOf(item.getIndexno()));
				if(fkts != null && fkts.size() >= 1) {
					List<String> fkList = new ArrayList<String>();
					
					for(JcBillPhoto fkt : fkts) {
						fkList.add(fkt.getUrlphoto());
					}
					
					item.setPaymentPhoto(fkList);
				}
				
				// 货品图
				List<JcBillPhoto> hpts = mapPhoto.get(JcBillPhoto.JC_HP + "#" + String.valueOf(item.getIndexno()) + "#" + item.getGoodsid());
				if(hpts != null && hpts.size() >= 1) {
					List<String> hpList = new ArrayList<String>();
					
					for(JcBillPhoto hpt : hpts) {
						hpList.add(hpt.getUrlphoto());
					}
					
					item.setGoodsPhotos(hpList);
					item.setHpts(hpts);
				}
			}
			
			return items;
		} catch(Throwable e){
			LOG.error(e.getMessage(), e);
			e.printStackTrace();
			throw e;
		}
	}

	/**
	 * 	TODO 查询溯源明细
	 * @param billId
	 * @return
	 */
	@RequestMapping(value = "queryJcSourceItems", method = RequestMethod.POST)
	public List<JcSourceItem> queryJcSourceItems(
			@RequestParam(required = true) String billId,
			@RequestParam(required = true) String srcItemId
		)
	throws Throwable {
		try {
			List<JcSourceItem> items = jcBillService.queryJcSourceItemByBillId(billId, srcItemId);
			
			return items;
		} catch(Throwable e){
			LOG.error(e.getMessage(), e);
			e.printStackTrace();
			throw e;
		}
	}
	
	
	/**
	 * 	TODO 确认溯源
	 * @param billId
	 * @param srcItemId
	 * @return
	 * @throws Throwable
	 */
	@RequestMapping(value = "querenSourceItems", method = RequestMethod.POST)
	public void querenSourceItems(
			@RequestParam(required = true) String billId,
			@RequestParam(required = true) String srcItemId,
			@RequestParam(required = true) String sourceItemId
		)
	throws Throwable {
		try {
//			JcBill jcBill = jcBillService.queryJcBillById(billId);
			
//			if(jcBill == null) throw new BusinessException("收货记录不存在！");
			
			JcBillSourceItem billItem = jcBillService.queryJcBillSourceItemById(Long.parseLong(srcItemId));
			
			if(billItem == null) throw new BusinessException("溯源信息不存在！");
			
			JcSourceItem sourceItem = jcBillService.queryJcSourceItemById(Long.parseLong(sourceItemId));
			
			if(sourceItem == null) throw new BusinessException("溯源明细不存在！");
			
//			 稽查收入记录
			
			// 溯源信息更新
			billItem.setStatus(JcBillSourceItem.STATUS_THREE);
			billItem.setLogisticsid(sourceItem.getLogisticsid());
			billItem.setBillout(sourceItem.getBillout());
			billItem.setBilloutdt(sourceItem.getBilloutdt());
			billItem.setBilloutwh(sourceItem.getBilloutwh());
			billItem.setBilloutwhname(sourceItem.getBilloutwhname());
			billItem.setProduct(sourceItem.getProduct());
			billItem.setProductname(sourceItem.getProductname());
			billItem.setAccount(sourceItem.getAccount());
			billItem.setAccountname(sourceItem.getAccountname());
			billItem.setOperator(sourceItem.getOperator());
			billItem.setOperatorname(sourceItem.getOperatorname());
			billItem.setGroupid(sourceItem.getGroupid());
			billItem.setGroupname(sourceItem.getGroupname());
			billItem.setSalearea(sourceItem.getSalearea());
			billItem.setSaleareaname(sourceItem.getSaleareaname());
			billItem.setSource(sourceItem.getSource());
			
			
			// 确认溯源明细
			sourceItem.setStatus(JcSourceItem.STATUS_ONE);
			
			jcBillService.saveQuerenBillSourceItem(billItem, sourceItem);
			
		} catch(Throwable e){
			LOG.error(e.getMessage(), e);
			e.printStackTrace();
			throw e;
		}
	}
	
	
	/**
	 * 	TODO 新增溯源明细信息
	 * @param billId
	 * @param srcItemId
	 * @return
	 * @throws Throwable
	 */
	@RequestMapping(value = "saveSourceItems", method = RequestMethod.POST)
	public JcSourceItem saveSourceItems(
			@RequestParam(required = true) String billid,
			@RequestParam(required = true) String srcitemid,
			@RequestParam(required = true) String goodsid,
			@RequestParam(required = true) String logisticsid,
			@RequestParam(required = true) String billout,
			@RequestParam(required = true) String billoutdt,
			@RequestParam(required = true) String billoutwh,
			@RequestParam(required = true) String billoutwhname,
			@RequestParam(required = true) String product,
			@RequestParam(required = true) String productname,
			@RequestParam(required = true) String account,
			@RequestParam(required = true) String accountname,
			@RequestParam(required = true) String operator,
			@RequestParam(required = true) String operatorname,
			@RequestParam(required = true) String groupid,
			@RequestParam(required = true) String groupname,
			@RequestParam(required = true) String salearea,
			@RequestParam(required = true) String saleareaname,
			@RequestParam(required = true) String source
		)
	throws Throwable {
		try {
			JcSourceItem sourceItem = new JcSourceItem();
			sourceItem.setStatus(JcSourceItem.STATUS_ZERO);
			sourceItem.setBillid(billid);
			sourceItem.setSrcitemid(srcitemid);
			sourceItem.setGoodsid(goodsid);
			sourceItem.setLogisticsid(logisticsid);
			sourceItem.setBillout(billout);
			sourceItem.setBilloutdt(DateUtil.toDate(billoutdt));
			sourceItem.setBilloutwh(billoutwh);
			sourceItem.setBilloutwhname(billoutwhname);
			sourceItem.setProduct(product);
			sourceItem.setProductname(productname);
			sourceItem.setAccount(account);
			sourceItem.setAccountname(accountname);
			sourceItem.setOperator(operator);
			sourceItem.setOperatorname(operatorname);
			sourceItem.setGroupid(groupid);
			sourceItem.setGroupname(groupname);
			sourceItem.setSalearea(salearea);
			sourceItem.setSaleareaname(saleareaname);
			sourceItem.setSource(source);
			
			JcSourceItem tempItem = jcBillService.saveJcSourceItem(sourceItem);
			
			return tempItem;
		} catch(Throwable e){
			LOG.error(e.getMessage(), e);
			e.printStackTrace();
			throw e;
		}
	}
	
	
	/**
	 * 	TODO 删除溯源明细信息
	 * @param billId
	 * @param srcItemId
	 * @return
	 * @throws Throwable
	 */
	@RequestMapping(value = "deleteSourceItem", method = RequestMethod.POST)
	public void deleteSourceItem(
			@RequestParam(required = true) String codes
		)
	throws Throwable {
		try {
			
			if (StringUtils.isEmpty(codes)) {
				throw new BusinessException("溯源明细信息编码不能为空");
			}
			
			List<Long> ids = JSON.parseArray(codes, Long.class);
			
			jcBillService.deleteJcSourceItem(ids);
			
		} catch(Throwable e){
			LOG.error(e.getMessage(), e);
			e.printStackTrace();
			throw e;
		}
	}
	
	/**
	 * 	TODO 溯源信息驳回
	 * @param billId
	 * @return
	 */
	@RequestMapping(value = "rejectJcSourceItems", method = RequestMethod.POST)
	public void rejectJcSourceItems(
			@RequestParam(required = true) String billId,
			@RequestParam(required = true) String srcItemId,
			@RequestParam(required = true) String reason
		)
	throws Throwable {
		try {
			JcBill jcBill = jcBillService.queryJcBillById(billId);
			
			if(jcBill == null) throw new BusinessException("收货记录不存在！");
			
			JcBillSourceItem billItem = jcBillService.queryJcBillSourceItemById(Long.parseLong(srcItemId));
			
			if(billItem == null) throw new BusinessException("溯源信息不存在！");
			
			jcBill.setStatus(JcBill.STATUS_MINUS_TWO);
			
			billItem.setStatus(JcBillSourceItem.STATUS_MINUS_TWO);
			billItem.setReason(reason);
			
			jcBillService.saveRejectJcSourceItems(billItem, jcBill);
			
		} catch(Throwable e){
			LOG.error(e.getMessage(), e);
			e.printStackTrace();
			throw e;
		}
	}
	
	
	/**
	 * 	TODO 修改收货仓库
	 * @param billId
	 * @return
	 */
	@RequestMapping(value = "updateWarehouse", method = RequestMethod.POST)
	public JcBill updateWarehouse(
			@RequestParam(required = true) String billId,
			@RequestParam(required = true) String warehouse,
			@RequestParam(required = true) String warehouseName
		)
	throws Throwable {
		try {
			JcBill jcBill = jcBillService.queryJcBillById(billId);
			
			if(jcBill == null) throw new BusinessException("收货记录不存在！");
			
			// 老对象保存为JSONString
			jcBill.setOldJson(JSON.toJSONString(jcBill));
			
			jcBill.setWarehouse(warehouse);
			jcBill.setWarehousename(warehouseName);
			
			jcBillService.updateWarehouse(jcBill);
			
			return jcBill;
		} catch(Throwable e){
			LOG.error(e.getMessage(), e);
			e.printStackTrace();
			throw e;
		}
	}
	
	
	/**
	 * 	TODO 生成入库单
	 * @param billId
	 * @return
	 */
	@RequestMapping(value = "createStockIn", method = RequestMethod.POST)
	public JcBill createStockIn(
			@RequestParam(required = true) String billId
		)
	throws Throwable {
		try {
			JcBill jcBill = jcBillService.queryJcBillById(billId);
			
			if(jcBill == null) throw new BusinessException("收货记录不存在！");
			
			jcBill.setStatus(JcBill.STATUS_FOUR);
			
			jcBillService.createStockIn(jcBill);
			
			return jcBill;
		} catch(Throwable e){
			LOG.error(e.getMessage(), e);
			e.printStackTrace();
			throw e;
		}
	}
	
	/**
	 * 	TODO 撤回
	 * @param billId
	 * @return
	 */
	@RequestMapping(value = "rejectBill", method = RequestMethod.POST)
	public JcBill rejectBill(
			@RequestParam(required = false) String billId,
			@RequestParam(required = false) int status
		)
	throws Throwable {
		try {
			JcBill jcBill = jcBillService.queryJcBillById(billId);
			
			if(jcBill == null) throw new BusinessException("收货记录不存在！");
			
			List<JcBillInItem> inItems = jcBillService.queryJcBillInItemByBillId(billId);
			
			List<JcBillSourceItem> sourceItems = jcBillService.queryJcBillSourceItemByBillId(billId);
			if(sourceItems == null) throw new BusinessException("收货明细不存在！");
			
			if(JcBill.STATUS_FOUR == status) {// 入库待审核   进行撤回（事件生成—进行事件删除）

				SiDepositlocation sd = jcBillService.querySiDepositlocation(jcBill.getId());
				
				if(sd == null) {// WDT
					throw new BusinessException("该单据需要通知仓库在旺店通删除入库单，并联系信息部撤回。");
				} else {
					if(sd.getPush() == 1) {// WMS
						
						JSONObject obj = jcBillService.gwisSubCancelOrder(jcBill.getId(), "QTRK");
						
						if(obj.getBooleanValue("success")) {
							
							jcBill.setStatus(JcBill.STATUS_THREE);
						} else {
							throw new BusinessException(obj.getString("body"));
						}
					} else {
						throw new BusinessException("该单据需要通知仓库在旺店通删除入库单，并联系信息部撤回。");
					}
				}
			} else {// 待入库撤回
				jcBill.setStatus(JcBill.STATUS_TWO);
				
				for(JcBillSourceItem item : sourceItems) {
					item.setStatus(JcBillSourceItem.STATUS_TWO);
				}
			}
			
			jcBillService.saveRejectBill(status, jcBill, inItems, sourceItems);
			return jcBill;
		} catch(Throwable e){
			LOG.error(e.getMessage(), e);
			e.printStackTrace();
			throw e;
		}
	}
	
	
	/**
	 * 	TODO 查询溯源明细-已确认
	 * @param billId
	 * @return
	 */
	@RequestMapping(value = "queryJcSourceItemsQue", method = RequestMethod.POST)
	public List<JcSourceItem> queryJcSourceItemsQue(
			@RequestParam(required = true) String billId,
			@RequestParam(required = true) String srcItemId
		)
	throws Throwable {
		try {
			List<JcSourceItem> items = jcBillService.queryJcSourceItemByBillId(billId, srcItemId, 1);
			
			return items;
		} catch(Throwable e){
			LOG.error(e.getMessage(), e);
			e.printStackTrace();
			throw e;
		}
	}
	
}





		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		



