package com.uas.eis.serviceImpl;

import com.uas.eis.dao.*;
import com.uas.eis.entity.EdiSuccessLog;
import com.uas.eis.entity.Sale;
import com.uas.eis.service.SaleService;
import com.uas.eis.service.StockService;
import com.uas.eis.utils.Constant;
import com.uas.eis.utils.HttpUtil;
import com.uas.eis.utils.JacksonUtil;
import com.uas.eis.utils.LogUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by luhg on 2018/4/26.
 * 销售订单
 */
@Service
public class SaleServiceImpl implements SaleService{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public static final String getSaleFromYundingUrl = "http://dc.oclean.com/getoutstorage";
    //public static final String getSaleFromYundingUrl = "http://127.0.0.1:8008/test/getoutstorage";

    @Autowired
    BaseDao baseDao;
    @Autowired
    EdiLogDao ediLogDao;
    @Autowired
    SaleDao saleDao;
    @Autowired
    EdiSuccessLogDao ediSuccessLogDao;
    @Autowired
    StockService stockService;

    @Override
    public void getSale() {
        String timestamp = String.valueOf(System.currentTimeMillis()/1000);

        Map<String,Object> postMapData = new HashMap<>();
        postMapData.put("app_key", Constant.yundingAppKey);
        postMapData.put("time_stamp",timestamp);
        postMapData.put("start_time","1970-01-01 00:00:00");
        postMapData.put("end_time","2099-01-01 00:00:00");
        postMapData.put("page_size",100);
        postMapData.put("page_index",0);

        String jsonData = JacksonUtil.toSortJson(postMapData);
        String responseText = null;
        try {
            HttpUtil.Response response = HttpUtil.doPostToYunding(getSaleFromYundingUrl,jsonData,timestamp);

            System.out.println("responseText:" + response.getResponseText());

            if(response.getStatusCode()!=200){
                responseText = "yunding server error";
                throw new RuntimeException(response.getResponseText());
            }

            responseText = response.getResponseText();
            Map<String,Object> responseMap = JacksonUtil.fromJson(response.getResponseText());

            if(!"0".equals(String.valueOf(responseMap.get("code")))){
                ediLogDao.save(LogUtil.getRequestFailLog(responseText));
                return;
            }

            if(responseMap.get("stockout_list")==null){
                return;
            }

            List<Map<String,Object>> datas = (List<Map<String,Object>>) responseMap.get("stockout_list");
            if(datas.size()>0){
                execCreateSaleProcedure(datas,responseText);
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("error",e);
            ediLogDao.save(LogUtil.getSaleFailLog(responseText,e.getMessage()));
        }
    }

    public void execCreateSaleProcedure(List<Map<String,Object>> datas,String responseText){
        String code = null;
        String wmscode = null;
        String out = null;
        EdiSuccessLog postSuccessHist = null;
        String type = "sale";
        for(Map<String,Object> data:datas){
            code = String.valueOf(data.get("trade_no"));
            wmscode = String.valueOf(data.get("order_no"));

            postSuccessHist = null;
            postSuccessHist = ediSuccessLogDao.findByCodeAndType(code,type);
            if(postSuccessHist!=null){
                stockService.postConfirmToYunding(wmscode,2);
                continue;
            }

            try {
                Sale sale = JacksonUtil.fromJson(data, Sale.class);
                sale = saleDao.save(sale);

                out = baseDao.callProcedure("SP_YUNDING_SALERECEIVE",new Object[]{sale.getId()});
                if (out!=null){
                    ediLogDao.save(LogUtil.getSaleFailLog(code,responseText,out));
                }else{
                    ediLogDao.save(LogUtil.getSaleSuccessLog(code,responseText));
                    ediSuccessLogDao.save(LogUtil.getLogToAvoidRepeatPost(code,type));
                    stockService.postConfirmToYunding(wmscode,2);
                }
            }catch (Exception e){
                e.printStackTrace();
                logger.error("error",e);
                ediLogDao.save(LogUtil.getSaleFailLog(code,responseText,e.getMessage()));
            }
        }
    }
}
