package com.uas.eis.serviceImpl;

import com.uas.eis.dao.*;
import com.uas.eis.entity.EdiSuccessLog;
import com.uas.eis.entity.SaleReturn;
import com.uas.eis.service.SaleReturnService;
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 SaleReturnServiceImpl implements SaleReturnService{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

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

    @Autowired
    BaseDao baseDao;
    @Autowired
    EdiLogDao ediLogDao;
    @Autowired
    SaleReturnDao saleReturnDao;
    @Autowired
    EdiSuccessLogDao ediSuccessLogDao;
    @Autowired
    StockService stockService;

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

        Map<String,Object> postMapData = new HashMap<String,Object>();
        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(getSaleReturnFromYundingUrl,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("data")==null){
                return;
            }

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

    public void execCreateSaleReturnProcedure(List<Map<String,Object>> datas,String responseText){
        String code = null;
        String out = null;
        EdiSuccessLog postSuccessHist = null;
        String type = "sale_return";
        for(Map<String,Object> data:datas){
            code = String.valueOf(data.get("refund_no"));

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

            try {
                SaleReturn saleReturn = JacksonUtil.fromJson(data, SaleReturn.class);
                saleReturn = saleReturnDao.save(saleReturn);

                out = baseDao.callProcedure("SP_YUNDING_SALERETURN",new Object[]{saleReturn.getId()});
                if (out!=null){
                    ediLogDao.save(LogUtil.getSaleReturnFailLog(code,responseText,out));
                }else{
                    ediLogDao.save(LogUtil.getSaleReturnSuccessLog(code,responseText));
                    ediSuccessLogDao.save(LogUtil.getLogToAvoidRepeatPost(code,type));
                    stockService.postConfirmToYunding(code,3);
                }
            }catch (Exception e){
                e.printStackTrace();
                logger.error("error",e);
                ediLogDao.save(LogUtil.getSaleReturnFailLog(code,responseText,e.getMessage()));
            }
        }
    }
}
