package com.chinacreator.video.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chinacreator.video.bean.OrderInfo;
import com.chinacreator.video.dto.DataOutPipe;
import com.chinacreator.video.exception.BusinessException;
import com.chinacreator.video.exception.BussinessException;
import com.chinacreator.video.mapper.DictionaryDao;
import com.chinacreator.video.mapper.EcbDiscntNewDao;
import com.chinacreator.video.restful.util.JsonUtil;
import com.chinacreator.video.service.CsCommonOrderService;
import com.chinacreator.video.util.URLUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * 畅视统一订购接口（60元订购退订，20元退订）
 * @author shuchuan.jin
 * @date 20190912
 */
@RestController
public class CsCommonOrderControl {

    private static final Logger logger = LoggerFactory.getLogger(CsCommonOrderControl.class);

    private static final  Logger log = LoggerFactory.getLogger("csCommonOrder");

    @Autowired
    private CsCommonOrderService service;

    @Autowired
    private EcbDiscntNewDao ecbDiscntNewDao;

    @Autowired
    private DictionaryDao dictionaryDao;

    @RequestMapping("/csCommonOrder")
    public DataOutPipe<?> hand(OrderInfo orderInfo) throws Exception {
        Map<String,Object> logmap = new HashMap<String,Object>();
//        Map<String,Object> data = new HashMap<>();
        DataOutPipe outpipe = new DataOutPipe();
        String resultcode = "";
        String errorinfo = "";
        logmap.put("forward","csOrder");
        logmap.put("userInfo",orderInfo);

        try {
        	orderInfo.setInvokeface("csCommonOrder");
            service.busiCheck(orderInfo);
            logmap.put("userInfo",orderInfo);
            if("0".equals(orderInfo.getType())){  //订购60
                String numberlimit = dictionaryDao.getValue("Numberlimit");
                if (numberlimit != null && numberlimit.indexOf(orderInfo.getUserid().substring(0, 7)) != -1) {
                    throw new BussinessException("9010", "用户为黑名单用户");
                }
                String orderUrl = service.getOrderUrl(orderInfo);
                logmap.put("orderUrl", orderUrl);
                String result = doHandle(orderUrl);
                if(!JSON.parseObject(result).get("resultcode").equals("0")) {
                    throw new BussinessException(JSON.parseObject(result).get("resultcode").toString(),JSON.parseObject(result).get("errorinfo").toString());
                }
                resultcode = "0";
                errorinfo = "ok";

            }else{ //退订

                List<Map> flag = ecbDiscntNewDao.queryByUserid(orderInfo.getUserid(),"0");

                //判断是否存在资费记录
                //存在
                if(flag.size() > 0){  //  退订60元
                    String orderUrl = service.getOrderUrl(orderInfo);
                    logmap.put("orderUrl",orderUrl);
                    String result = doHandle(orderUrl);
                    if(!JSON.parseObject(result).get("resultcode").equals("0")) {
                        throw new BussinessException(JSON.parseObject(result).get("resultcode").toString(),JSON.parseObject(result).get("errorinfo").toString());
                    }
                    resultcode = "0";
                    errorinfo = "ok";

                }else{   //退订20元
                    //不存在
                    String queryUrl = service.getQueryUrl(orderInfo);
                    logmap.put("queryUrl",queryUrl);
                    String re = doHandle(queryUrl);
                    if(!JSON.parseObject(re).get("resultcode").equals("9901") && !JSON.parseObject(re).get("resultcode").equals("9902") && !JSON.parseObject(re).get("resultcode").equals("01") && !JSON.parseObject(re).get("resultcode").equals("0")) {
                        throw new BussinessException(JSON.parseObject(re).get("resultcode").toString(),JSON.parseObject(re).get("errorinfo").toString());
                    }

                    String sign = JSON.parseObject(re).get("sign").toString();
                    sign = URLEncoder.encode(sign,"UTF-8");
                    String productinfos = JSON.parseObject(re).get("productinfos").toString();
                    productinfos = StringUtils.strip(productinfos.toString(),"[]").replace("\\","");
                    JSONObject obj = JSON.parseObject(productinfos);
                    String discntCode = obj.getString("discntCode");
                    List<String> lists = ecbDiscntNewDao.findWhiteDiscnts();
                    int bj = 0;

                    for (String list : lists){
                        if(list.equals(discntCode)){
                            bj = 1;
                        }
                    }

                    if(bj == 0){
                        throw new BussinessException("10099","未订购畅视20元产品，不能退订");
                    }
                    productinfos = URLEncoder.encode(productinfos,"UTF-8");
                    String cancerUrl = service.getCancerUrl(orderInfo);
                    cancerUrl += "&orderType=1&productinfos="+productinfos+"&sign="+sign;
                    logmap.put("cancerUrl",cancerUrl);
                    String result = doHandle(cancerUrl);
                    if(!JSON.parseObject(result).get("resultcode").equals("0")) {
                        throw new BussinessException(JSON.parseObject(result).get("resultcode").toString(),JSON.parseObject(result).get("errorinfo").toString());
                    }
                    resultcode = "0";
                    errorinfo = "ok";

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultcode = "80003";
            errorinfo = "出现异常，"+e.getMessage();
            if(e instanceof BussinessException) {
                resultcode = ((BussinessException) e).getCode();
                errorinfo = ((BussinessException) e).getMessage();
                throw e;
            }else {
                throw new BussinessException(resultcode, errorinfo);
            }
        } finally {
            outpipe.setResultcode(resultcode);
            outpipe.setErrorinfo(errorinfo);
            logmap.put("resultcode", resultcode);
            logmap.put("errorinfo", errorinfo);
            log.info(JSON.toJSONString(logmap));
        }

        return outpipe;
    }


    public static void main(String args[]){

    }



    public String doHandle(String url) throws Exception {
        return  URLUtil.get(url,60000);
    }

}
