package com.neusoft.smart.pos.gateway.service;


import com.alibaba.fastjson.JSON;
import com.neusoft.smart.pos.constants.DictionaryConstant;
import com.neusoft.smart.pos.dto.org.response.PostShopResponse;
import com.neusoft.smart.pos.dto.printer.request.PostPrinterOrderRequest;
import com.neusoft.smart.pos.dto.trade.request.PutPrinterFlagRequest;
import com.neusoft.smart.pos.dto.trade.response.GetOrderInfoByOrderNumberResponse;
import com.neusoft.smart.pos.framework.constants.ApplicationConstants;
import com.neusoft.smart.pos.framework.dto.ResponseData;
import com.neusoft.smart.pos.framework.exception.BusinessCommonException;
import com.neusoft.smart.pos.framework.task.TaskExecutor;
import com.neusoft.smart.pos.framework.utils.DateUtils;
import com.neusoft.smart.pos.gateway.service.feignService.RemoteOrderService;
import com.neusoft.smart.pos.gateway.service.feignService.RemotePrinterService;
import com.neusoft.smart.pos.gateway.service.feignService.RemoteShopService;
import com.neusoft.smart.pos.gateway.task.PrinterTask;
import lombok.val;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service("printerService")
public class PrinterService {
    
    private final static Logger logger = LoggerFactory.getLogger(PrinterService.class);
    
    @Autowired
    private RemoteOrderService remoteOrderService;
    
    @Autowired
    private RemotePrinterService remotePrinterService;
    
    @Autowired
    private RemoteShopService shopService;
    
    @Autowired
    private TaskExecutor taskExecutor;
    
    /**
     * 根据订单号推送打印服务接口
     *
     * @return
     */
    public void pushPrinterTaskByOrderNumber(String orderNumber,String operationType) {
        //1.根据订单编号获取订单详情信息
        GetOrderInfoByOrderNumberResponse orderInfo = queryOrderDetails(orderNumber);
        //2.判断订单是否已经推送至打印服务
        if(orderInfo.getPrinterFlag().equals("2")||null == orderInfo.getOrderDetailList() || orderInfo.getOrderDetailList().size() == 0){
            return;
        }
        
        //4.支付完成后将订单信息推送至打印服务
        PrinterTask printerTask = new PrinterTask();
        printerTask.setOrderInfo(orderInfo);
        printerTask.setOperationType(operationType);
        taskExecutor.getExecutorService().submit(printerTask);
    }
    
//    /**
//     * 根据订单号推送打印服务接口
//     *
//     * @return
//     */
//    public void pushPrinterTaskByOrderNumber(String orderNumber,String templateType) {
//        //3.推送数据至打印服务
//        GetOrderInfoByOrderNumberResponse orderInfo = queryOrderDetails(orderNumber);
//        pushPrinterTaskByOrderNumber(orderInfo,templateType);
//    }
    
    /**
     * 根据订单号推送打印服务接口
     *
     * @return
     */
    public void pushPrinterTaskByOrderNumber(GetOrderInfoByOrderNumberResponse orderInfo,String operationType) {
        String templateType = "";   //模板类型@1:后结下单模板@2:前结结算模板@3:后结结算模板
        //查询门店结算方式1:前结; 2:后结
        ResponseData<PostShopResponse> shopResponseData = shopService.getShopDetail(orderInfo.getShopId());
        if(operationType.equals(DictionaryConstant.PRINTER_OPERATION_TYPE_1.getCode())){
            if(shopResponseData.getResult().getSettle().equals("1")){
                //1:前结下单
                templateType = "";
            }else if(shopResponseData.getResult().getSettle().equals("2")){
                //2:后结下单
                templateType = "1";
            }
        }else if(operationType.equals(DictionaryConstant.PRINTER_OPERATION_TYPE_2.getCode())){
            if(shopResponseData.getResult().getSettle().equals("1")){
                //1:前结结算
                templateType = "2";
            }else if(shopResponseData.getResult().getSettle().equals("2")){
                //2:后结结算
                templateType = "3";
            }
        }
    
        //4.更新订单打印状态
        PutPrinterFlagRequest printerFlagRequest = new PutPrinterFlagRequest();
        printerFlagRequest.setOrderNumber(orderInfo.getOrderNumber());
        remoteOrderService.updatePrinterFlag(printerFlagRequest);
        
        //3.推送数据至打印服务
        val postPrinterOrderResponse = remotePrinterService.printerOrder(printerDataHandle(orderInfo,templateType));
        if (null == postPrinterOrderResponse || !ApplicationConstants.SUCCESS_CODE.equals(postPrinterOrderResponse.getCode())) {
//            throw new BusinessCommonException(postPrinterOrderResponse);
            logger.error(JSON.toJSONString(postPrinterOrderResponse));
        }
    }
    
    /**
     * 根据订单编号查询订单详情信息
     * @param orderNumber
     */
    private GetOrderInfoByOrderNumberResponse queryOrderDetails(String orderNumber){
        val orderInfoResponseData = remoteOrderService.queryOrderInfoByOrderNumber(orderNumber);
        if (null == orderInfoResponseData || !ApplicationConstants.SUCCESS_CODE.equals(orderInfoResponseData.getCode())) {
            throw new BusinessCommonException(orderInfoResponseData);
        }
        return orderInfoResponseData.getResult();
    }
    
    /**
     * 将订单数据转换为打印数据
     * @param orderInfo
     * @return
     */
    private PostPrinterOrderRequest printerDataHandle(GetOrderInfoByOrderNumberResponse orderInfo,String templateType){
        //1.整单订单数据信息
        PostPrinterOrderRequest printerOrderRequest = new PostPrinterOrderRequest();
        printerOrderRequest.setTemplateType(templateType);
        printerOrderRequest.setOrgId(orderInfo.getOrgId());
        printerOrderRequest.setShopId(orderInfo.getShopId());
        printerOrderRequest.setOrderNumber(orderInfo.getOrderNumber());
        printerOrderRequest.setLocationNo(orderInfo.getLocationNo());
        printerOrderRequest.setOrderAmount(orderInfo.getOrderAmount());
        printerOrderRequest.setRealPayAmount(orderInfo.getRealPayAmount());
        printerOrderRequest.setDiscountAmount(orderInfo.getDiscountAmount());
        printerOrderRequest.setOrderStatus(orderInfo.getOrderStatus());
        printerOrderRequest.setOrderStatusName(getOrderStatusName(orderInfo.getOrderStatus()));
        printerOrderRequest.setOrderType(orderInfo.getOrderType());
        printerOrderRequest.setPaidTime(DateUtils.format(orderInfo.getPaidTime()));
        
        //2.整理明细数据信息
        List<PostPrinterOrderRequest.OrderDetail> orderDetailsPrinterList = new ArrayList<>();
        List<GetOrderInfoByOrderNumberResponse.OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        if(null != orderDetailList && orderDetailList.size() > 0){
            orderDetailList.forEach(orderDetail -> {
                if (!StringUtils.isEmpty(orderDetail.getItemNumber())) {
                    PostPrinterOrderRequest.OrderDetail orderDetailTemp = new PostPrinterOrderRequest.OrderDetail();
                    orderDetailTemp.setItemNumber(Integer.parseInt(orderDetail.getItemNumber()));
                    orderDetailTemp.setItemName(orderDetail.getItemName());
                    orderDetailTemp.setCategoryName(orderDetail.getCategoryName());
                    orderDetailTemp.setCategoryNumber(orderDetail.getCategoryNumber());
                    orderDetailTemp.setUnitPrice(orderDetail.getUnitPrice());
                    orderDetailTemp.setQuantity(orderDetail.getQuantity());
                    orderDetailTemp.setDiscountAmount(orderDetail.getDiscountAmount());
                    orderDetailTemp.setFinalPrice(orderDetail.getFinalPrice());
                    orderDetailsPrinterList.add(orderDetailTemp);
                }
            });
        }
        printerOrderRequest.setOrderDetails(orderDetailsPrinterList);
        return printerOrderRequest;
    }
    
    /**
     * 根据订单状态获取订单状态名称
     *
     * @param orderStatus
     * @return
     */
    private String getOrderStatusName(String orderStatus) {
        String orderStatusName = "";
        if (!StringUtils.isEmpty(orderStatus)) {
            DictionaryConstant dict = DictionaryConstant.getEnumByCode(DictionaryConstant.ORDER_STATUS.getCode(), orderStatus);
            orderStatusName = dict.getValue();
        }
        return orderStatusName;
    }
}
