package com.weiqi.mis.impl;

import com.alibaba.fastjson.JSONObject;
import com.weiqi.mis.DateHelper;
import com.weiqi.mis.HttpUtil;
import com.weiqi.mis.PushService;
import com.weiqi.mis.bo.WxXrPemsOrderResult;
import com.weiqi.mis.domain.WxSgPolluteSds;
import com.weiqi.mis.domain.WxSgPolluteSdsExample;
import com.weiqi.mis.domain.WxXrPemsOrder;
import com.weiqi.mis.domain.WxXrPemsOrderPushLog;
import com.weiqi.mis.mapper.WxSgPolluteSdsMapper;
import com.weiqi.mis.mapper.WxXrPemsOrderMapper;
import com.weiqi.mis.mapper.WxXrPemsOrderPushLogMapper;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class PushServiceImpl implements PushService {
    @Autowired
    private WxSgPolluteSdsMapper wxSgPolluteSdsMapper;
    @Autowired
    private WxXrPemsOrderMapper wxXrPemsOrderMapper;
    @Autowired
    private WxXrPemsOrderPushLogMapper wxXrPemsOrderPushLogMapper;


        @Override
        public JSONObject pushorder(int id) {
            JSONObject jsret = new JSONObject();
            jsret.put("returncode", 0);
            jsret.put("message", "");

            try {

                WxXrPemsOrder wxXrPemsOrder = wxXrPemsOrderMapper.selectByPrimaryKey(id);
                log.info("{}", wxXrPemsOrder);
                //调用生成订单接口，返回订单编号
                JSONObject createorder = createorder(wxXrPemsOrder);
                //{"extmessage":null,"message":"操作成功","result":{"brandimg":"https://api.mycar369.com/api/carimg/14.jpg","orderid":"2024101418552975925900036","sname":"思域","platenum":"京atest1"},"returncode":2000}

                if (createorder.getInteger("returncode") != 2000) {
                    jsret.put("returncode", -1);
                    jsret.put("message", "调用接口生成订单失败");
                    return jsret;
                }
                String orderId = createorder.getJSONObject("result").getString("orderid");
                List<WxSgPolluteSds> wxSgPolluteSdsList = new ArrayList<>();

                List<WxXrPemsOrderResult.WxXrPemsOrderItemResult> wxXrPemsOrderItemResultList = new ArrayList<>();

                //查询订单检测结果list

                WxSgPolluteSdsExample example1 = new WxSgPolluteSdsExample();
                WxSgPolluteSdsExample.Criteria ca = example1.createCriteria();
                ca.andWxOrderIdEqualTo(id);
                wxSgPolluteSdsList = wxSgPolluteSdsMapper.selectByExample(example1);


                JSONObject pollutesave = pollutesave(wxXrPemsOrder, wxSgPolluteSdsList, orderId);
                if (pollutesave.getInteger("returncode") != 2000) {
                    jsret.put("returncode", -1);
                    jsret.put("message", "调用接口保存订单失败");
                    return jsret;
                }

            } catch (Exception e) {
                log.error("pushorder is error:{}", e);
                jsret.put("returncode", -1);
                jsret.put("message", e.getMessage());

            }

            return jsret;
        }

        /**
         * 【第一步】：
         * https://api.mycar369.com/api/sg/createorder?mid=22&userid=36&vin=0000&platenum=%E4%BA%ACatest1&licensingtime=2022-10-14&mileage=10&drivinglicenseimgsrc=&carimgsrc=&modelid=135&brandid=14&linkname=lxr&phonenum=13126679999&engine_air_count=4&exhaustsystem=2&appid=LANBBXCXtest&os=xiaochengxu&version=1.1.2&timestamp=1728900072&udid=000&noncestr=000&usid=36&_sign=77705A9803DCEBBD6006E07BF592882D
         * 发动机缸数
         * engine_air_count:4
         * 排气系统类型 1，单排  2，双排
         * exhaustsystem: 1 or 2
         * 维修门店id
         * mid:22
         * 操作用户id
         * usid:36   对应数据库里的用户id
         * userid:36  对应数据库里的用户id
         * 车系品牌id
         * modelid=135&brandid=14
         * <p>
         * 返回内容：
         * {"extmessage":null,"message":"操作成功","result":{"brandimg":"https://api.mycar369.com/api/carimg/14.jpg","orderid":"2024101418552975925900036","sname":"思域","platenum":"京atest1"},"returncode":2000}
         * returncode：2000 表示成功
         *
         * @param wxXrPemsOrder
         * @return
         */
        public JSONObject createorder(WxXrPemsOrder wxXrPemsOrder) {
            JSONObject js = new JSONObject();
            Map<String, String> fields = new HashMap<>();
            String body = "";
            try {
                fields.put("mid", wxXrPemsOrder.getMid()+"");
                fields.put("userid", wxXrPemsOrder.getOrderuserid()+"");
                fields.put("vin", wxXrPemsOrder.getVin());
                fields.put("platenum", wxXrPemsOrder.getPlatenumber());
                fields.put("licensingtime", DateHelper.serialize(wxXrPemsOrder.getAdmissiontime(), DateHelper.DATEFORMAT_ONLY_DATE));
                fields.put("mileage", wxXrPemsOrder.getKilometers().intValue()+"");
                fields.put("drivinglicenseimgsrc", wxXrPemsOrder.getDrivinglicensesrc() == null ? "" : wxXrPemsOrder.getDrivinglicensesrc());
                fields.put("carimgsrc", wxXrPemsOrder.getVehiclesrc() == null ? "" : wxXrPemsOrder.getVehiclesrc());
                fields.put("modelid", wxXrPemsOrder.getSeriesid() == null ? "" : wxXrPemsOrder.getSeriesid()+"");
                fields.put("brandid", wxXrPemsOrder.getBrandid() == null ? "" : wxXrPemsOrder.getBrandid()+"");
                fields.put("linkname", wxXrPemsOrder.getLinkname() == null ? "" : wxXrPemsOrder.getLinkname());
                fields.put("phonenum", wxXrPemsOrder.getLinktel() == null ? "" : wxXrPemsOrder.getLinktel());
                fields.put("engine_air_count", wxXrPemsOrder.getEnginestructurenumber()+"");
    //            排气系统类型 1，单排  2，双排  这个对应表中哪个字段，是排期构造？ exhau
                fields.put("exhaustsystem", "1");
    //            fields.put("exhaustsystem", wxXrPemsOrder.getExhauststructure());
                fields.put("appid", "LANBBXCXtest");
                fields.put("os", "xiaochengxu");
                fields.put("version", "1.1.2");
                fields.put("timestamp", (System.currentTimeMillis() / 1000)+"");
                fields.put("udid", "000");
                fields.put("noncestr", "000");
                fields.put("usid", wxXrPemsOrder.getOrderuserid()+"");
                fields.put("_sign", "77705A9803DCEBBD6006E07BF592882D");

                String url = "https://api.mycar369.com/api/sg/createorder?";
                body = HttpUtil.sendGetRequest(url, fields);

//                String url = "https://api.mycar369.com/api/sg/createorder?mid=22&userid=36&vin=0000&platenum=%E4%BA%ACatest1&licensingtime=2022-10-14&mileage=10&drivinglicenseimgsrc=&carimgsrc=&modelid=135&brandid=14&linkname=lxr&phonenum=13126679999&engine_air_count=4&exhaustsystem=2&appid=LANBBXCXtest&os=xiaochengxu&version=1.1.2&timestamp=1728900072&udid=000&noncestr=000&usid=36&_sign=77705A9803DCEBBD6006E07BF592882D";
//                body = HttpUtil.sendGetRequest(url);

                js = JSONObject.parseObject(body);

            } catch (Exception e) {
                log.error("createorder is error:{}", e);
                js.put("returncode", -1);
                js.put("message", "请求数据报错");
            } finally {
                WxXrPemsOrderPushLog record = new WxXrPemsOrderPushLog();
                record.setOrderno(wxXrPemsOrder.getOrderno());
                record.setWeixiuorderno("");
                record.setRequestparam(fields.toString());
                record.setResponse(body.length() > 1000 ? body.substring(0, 1000) : body);
                record.setStep(1);

                if (js.containsKey("returncode")) {
                    record.setStatus(js.getInteger("returncode"));
                } else {
                    record.setStatus(-1);
                }
                wxXrPemsOrderPushLogMapper.insert(record);
            }

            return js;
        }

        /**
         * 第二步】：
         * https://api.mycar369.com/api/sg/pollutesave?ordernum=2024101418552975925900036&categroy=2&jystco=0&jysthc=0&jystnox=0&cohigh1=1&hchigh=2&lambdahigh1=3&colow1=0&hclow1=0&lambdalow1=0&appid=LANBB00M&os=android-11-M2011K2C&version=1.1.2&timestamp=1728900609&udid=a97c068f-0ba3-3f3b-a25e-172087d538e2&noncestr=3PbaRn&usid=36&_sign=8F016C479C2D69561AE541A0A26C98C7
         * <p>
         * 第一步得到的订单id
         * ordernum:2024101418552975925900036
         * 污染数据-高怠速
         * categroy=2
         * 污染数据 cohigh1=1&hchigh=2&lambdahigh1=3  其它污染数据填0
         * 污染数据-低怠速
         * categroy=3
         * 污染数据 colow1=20&hclow1=20&lambdalow1=20  其它污染数据填0
         * 返回内容：
         * {"extmessage":null,"message":"操作成功","result":{"code":"0","message":"添加成功"},"returncode":2000}
         *
         * @param
         * @return
         */
        public JSONObject pollutesave(WxXrPemsOrder wxXrPemsOrder, List<WxSgPolluteSds> wxSgPolluteSdsList, String orderId) {
            JSONObject js = new JSONObject();
            js.put("returncode",-1);
            String body = "";
            Map<String, String> fields = new HashMap<>();
            try {
                for (WxSgPolluteSds wxSgPolluteSds : wxSgPolluteSdsList) {
                    String url = "https://api.mycar369.com/api/sg/pollutesave?";
                    fields = new HashMap<>();
                    fields.put("ordernum", orderId);
                    //高怠速
                    if (wxSgPolluteSds.getCategory() == 2) {
                        fields.put("categroy", wxSgPolluteSds.getCategory()+"");
                        fields.put("cohigh1", wxSgPolluteSds.getCo()+"");
                        fields.put("hchigh", wxSgPolluteSds.getHc()+"");
                        fields.put("lambdahigh1", wxSgPolluteSds.getLambda()+"");
                        fields.put("lambdalow1", "0");
                        fields.put("colow1", "0");
                        fields.put("hclow1", "0");
                    } else {
                        fields.put("categroy", "1");
                        fields.put("colow1", wxSgPolluteSds.getCo()+"");
                        fields.put("hclow1", wxSgPolluteSds.getHc()+"");
                        fields.put("lambdalow1", wxSgPolluteSds.getLambda()+"");
                        fields.put("lambdahigh1", "0");
                        fields.put("cohigh1", "0");
                        fields.put("hchigh", "0");
                    }
                    fields.put("jystco", "0");
                    fields.put("jysthc", "0");
                    fields.put("jystnox", "0");

                    fields.put("appid", "LANBBXCXtest");
                    fields.put("os", "xiaochengxu");
                    fields.put("version", "1.1.2");
                    fields.put("timestamp", (System.currentTimeMillis()/1000)+"");
                    fields.put("udid", "000");
                    fields.put("noncestr", "000");
                    fields.put("usid", wxXrPemsOrder.getOrderuserid()+"");
                    fields.put("_sign", "77705A9803DCEBBD6006E07BF592882D");
                    body= HttpUtil.sendGetRequest(url, fields);

                    try{
                        js = JSONObject.parseObject(body);
                    }catch (Exception e){
                        log.error("返回结果非json body={}",body);
                    }

                    WxXrPemsOrderPushLog record = new WxXrPemsOrderPushLog();
                    record.setOrderno(wxXrPemsOrder.getOrderno());
                    record.setWeixiuorderno("");
                    record.setRequestparam(fields.toString());
                    record.setResponse(body.length() > 1000 ? body.substring(1, 1000) : body);
                    record.setStep(2);
                    savelog(record, js);

                }
            } catch (Exception e) {
                log.error("pollutesave is error:{}", e);
                js.put("returncode", -1);
                js.put("message", "请求数据报错");
            }
            return js;
        }

        public void savelog(WxXrPemsOrderPushLog record, JSONObject js) {
            try {
                if (js.containsKey("returncode")) {
                    record.setStatus(js.getInteger("returncode"));
                } else {
                    record.setStatus(-1);
                }
                record.setCreateTime(new Date());
                record.setUpdateTime(new Date());
                wxXrPemsOrderPushLogMapper.insert(record);
            } catch (Exception e) {
                log.error("insert log error:{}", e);
            }
        }

}

