package com.iotechn.unimall.admin.api.shop.impl;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

import com.baidu.ccc.auth.api.token.ApiTokenV1;
import com.dangdang.openplatform.openapi.sdk.ApiException;
import com.dangdang.openplatform.openapi.sdk.SdkClient;
import com.dangdang.openplatform.openapi.sdk.internal.util.FileItem;
import com.dangdang.openplatform.openapi.sdk.request.order.*;
import com.dangdang.openplatform.openapi.sdk.requestmodel.order.EncryptDTO;
import com.dangdang.openplatform.openapi.sdk.requestmodel.order.OrderDetailsGet;
import com.dangdang.openplatform.openapi.sdk.response.order.*;
import com.dangdang.openplatform.openapi.sdk.responsemodel.order.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iotechn.unimall.data.domain.shop.ShopAccount;
import com.iotechn.unimall.data.domain.shop.ShopLog;
import com.iotechn.unimall.data.domain.shop.ShopTran;
import com.iotechn.unimall.data.dto.shop.ShopDTO;
import com.iotechn.unimall.data.dto.shop.XmlObject.OrderDetail;
import com.iotechn.unimall.data.dto.shop.XmlObject.SendGood;
import com.iotechn.unimall.data.dto.shop.XmlObject.SendGoodsInfo;
import com.iotechn.unimall.data.mapper.shop.ShopAccountMapper;
import com.iotechn.unimall.data.mapper.shop.ShopLogMapper;
import com.iotechn.unimall.data.mapper.shop.ShopTranMapper;
import com.iotechn.unimall.data.util.XMLUtil;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.iotechn.unimall.core.exception.ServiceException;
import com.iotechn.unimall.data.util.ExcelUtil;
import com.iotechn.unimall.data.mapper.shop.ShopOrderMapper;
import com.iotechn.unimall.data.domain.shop.ShopOrder;
import com.iotechn.unimall.admin.api.shop.IShopOrderService;
import com.iotechn.unimall.data.model.Page;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.transaction.annotation.Transactional;

/**
 * 电商订单表Service业务层处理
 *
 * @author jlb
 * @date 2022-05-28
 */
@Service
public class ShopOrderServiceImpl implements IShopOrderService {
    @Autowired
    private ShopOrderMapper shopOrderMapper;
    @Autowired
    private ShopAccountMapper shopAccountMapper;
    @Autowired
    private ShopTranMapper shopTranMapper;

    @Autowired
    private ShopLogMapper shopLogMapper;

    @Override
    public Boolean add(ShopOrder shopOrder, Long adminId) throws ServiceException {
        Date now = new Date();
        shopOrder.setGmtCreate(now);
        shopOrder.setGmtUpdate(now);
        shopOrder.setAdminId(adminId);
        return shopOrderMapper.insert(shopOrder) > 0;
    }

    @Override
    public Page<ShopOrder> list(Long accountId, String orderId, String dangOrder, String dangOrderStatus, String address, String provName, String cityName, String areaName, String orderStatus, String orderStatusName, String payStatus, String payName, String receiverName, String mobile, String receiver, Integer deleteFlag, Date gmtCreate, Date gmtUpdate, Long userId, Long adminId, String shopName, Integer page, Integer limit) throws ServiceException {
        Wrapper<ShopOrder> wrapper = new EntityWrapper<ShopOrder>();
        List<Long> param = new ArrayList<>();
        if (!StringUtils.isEmpty(shopName)) {
            Wrapper<ShopAccount> wrapper1 = new EntityWrapper<ShopAccount>();
            wrapper1.like("dang_name", shopName);
            List<ShopAccount> list = shopAccountMapper.selectList(wrapper1);
            for (ShopAccount shopAccount : list
            ) {
                param.add(shopAccount.getId());
            }
            wrapper.in("account_id", param);
        }
        if (!StringUtils.isEmpty(orderId)) {
            wrapper.eq("order_id", orderId);
        }
        if (!StringUtils.isEmpty(dangOrder)) {
            wrapper.eq("dang_order", dangOrder);
        }
        if (!StringUtils.isEmpty(address)) {
            wrapper.eq("address", address);
        }
        if (!StringUtils.isEmpty(provName)) {
            wrapper.eq("prov_name", provName);
        }
        if (!StringUtils.isEmpty(cityName)) {
            wrapper.eq("city_name", cityName);
        }
        if (!StringUtils.isEmpty(areaName)) {
            wrapper.eq("area_name", areaName);
        }
        if (!StringUtils.isEmpty(orderStatus)) {
            wrapper.eq("order_status", orderStatus);
        }
        if (!StringUtils.isEmpty(orderStatusName)) {
            wrapper.like("order_status_name", orderStatusName);
        }
        if (!StringUtils.isEmpty(payStatus)) {
            wrapper.eq("pay_status", payStatus);
        }
        if (!StringUtils.isEmpty(payName)) {
            wrapper.eq("pay_name", payName);
        }
        if (!StringUtils.isEmpty(receiverName)) {
            wrapper.eq("receiver_name", receiverName);
        }
        if (!StringUtils.isEmpty(mobile)) {
            wrapper.eq("mobile", mobile);
        }
        if (!StringUtils.isEmpty(receiver)) {
            wrapper.eq("receiver", receiver);
        }
        if (!StringUtils.isEmpty(deleteFlag)) {
            wrapper.eq("delete_flag", deleteFlag);
        }
        if (!StringUtils.isEmpty(gmtCreate)) {
            wrapper.eq("gmt_create", gmtCreate);
        }
        if (!StringUtils.isEmpty(gmtUpdate)) {
            wrapper.eq("gmt_update", gmtUpdate);
        }
        if (!StringUtils.isEmpty(userId)) {
            wrapper.eq("user_id", userId);
        }
        if (!StringUtils.isEmpty(adminId)) {
            wrapper.eq("admin_id", adminId);
        }
        if (!StringUtils.isEmpty(dangOrderStatus)) {
            wrapper.like("dang_order_status", dangOrderStatus);
        }
        wrapper.eq("delete_flag", 0);
        wrapper.orderBy("created_time", false);
        List<ShopOrder> list = shopOrderMapper.selectPage(new RowBounds((page - 1) * limit, limit), wrapper);
        for (ShopOrder shopOrder : list
        ) {
            ShopAccount shopAccount = shopAccountMapper.selectById(shopOrder.getAccountId());
            shopOrder.setShopAccount(shopAccount);
        }
        Integer count = shopOrderMapper.selectCount(wrapper);
        return new Page<ShopOrder>(list, page, limit, count);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(String id) {
        String[] ids = String.valueOf(id).split(",");
        for (String tt : ids) {
            ShopOrder tmp = shopOrderMapper.selectById(Long.parseLong(tt));
            if (tmp != null) {
                tmp.setDeleteFlag(1);
                shopOrderMapper.updateById(tmp);
            }
        }
        return true;
    }

    @Override
    public Boolean update(ShopOrder shopOrder, Long adminId) throws ServiceException {
        Date now = new Date();
        shopOrder.setGmtUpdate(now);
        shopOrder.setAdminId(adminId);
        return shopOrderMapper.updateById(shopOrder) > 0;
    }

    @Override
    public ShopOrder get(Long id) throws ServiceException {
        return shopOrderMapper.selectById(id);
    }

    @Override
    public String export(Long accountId, String orderId, String dangOrder, String address, String provName, String cityName, String areaName, String orderStatus, String orderStatusName, String payStatus, String payName, String receiverName, String mobile, String receiver, Integer deleteFlag, Date gmtCreate, Date gmtUpdate, Long userId, Long adminId, Integer page, Integer limit) throws ServiceException {
        Wrapper<ShopOrder> wrapper = new EntityWrapper<ShopOrder>();
        if (!StringUtils.isEmpty(accountId)) {
            wrapper.eq("account_id", accountId);
        }
        if (!StringUtils.isEmpty(orderId)) {
            wrapper.eq("order_id", orderId);
        }
        if (!StringUtils.isEmpty(dangOrder)) {
            wrapper.eq("dang_order", dangOrder);
        }
        if (!StringUtils.isEmpty(address)) {
            wrapper.eq("address", address);
        }
        if (!StringUtils.isEmpty(provName)) {
            wrapper.eq("prov_name", provName);
        }
        if (!StringUtils.isEmpty(cityName)) {
            wrapper.eq("city_name", cityName);
        }
        if (!StringUtils.isEmpty(areaName)) {
            wrapper.eq("area_name", areaName);
        }
        if (!StringUtils.isEmpty(orderStatus)) {
            wrapper.eq("order_status", orderStatus);
        }
        if (!StringUtils.isEmpty(orderStatusName)) {
            wrapper.like("order_status_name", orderStatusName);
        }
        if (!StringUtils.isEmpty(payStatus)) {
            wrapper.eq("pay_status", payStatus);
        }
        if (!StringUtils.isEmpty(payName)) {
            wrapper.eq("pay_name", payName);
        }
        if (!StringUtils.isEmpty(receiverName)) {
            wrapper.eq("receiver_name", receiverName);
        }
        if (!StringUtils.isEmpty(mobile)) {
            wrapper.eq("mobile", mobile);
        }
        if (!StringUtils.isEmpty(receiver)) {
            wrapper.eq("receiver", receiver);
        }
        if (!StringUtils.isEmpty(deleteFlag)) {
            wrapper.eq("delete_flag", deleteFlag);
        }
        if (!StringUtils.isEmpty(gmtCreate)) {
            wrapper.eq("gmt_create", gmtCreate);
        }
        if (!StringUtils.isEmpty(gmtUpdate)) {
            wrapper.eq("gmt_update", gmtUpdate);
        }
        if (!StringUtils.isEmpty(userId)) {
            wrapper.eq("user_id", userId);
        }
        if (!StringUtils.isEmpty(adminId)) {
            wrapper.eq("admin_id", adminId);
        }
        List<ShopOrder> list = shopOrderMapper.selectList(wrapper);
        ExcelUtil<ShopOrder> util = new ExcelUtil<ShopOrder>(ShopOrder.class);
        return util.exportExcel(list, "操作日志");
    }

    @Override
    public String syncOrderInfoList(ShopDTO shopDTO) throws Exception {
        for (ShopDTO tmp : shopDTO.getShopDTOS()
        ) {
            syncOrderInfo(tmp.getOrderId(), tmp.getDangId(), tmp.getDangOrder());
        }
        return "ok";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ShopOrder syncOrderInfo(String orderId, String dangId, String dangOrder) throws Exception {
        try {

            ShopAccount shopAccount = new ShopAccount();
            if (dangId != null) {
                shopAccount.setDangId(dangId);
            }
            //        if(fuziId != null){
            //            shopAccount.setFuziId(fuziId);
            //        }
            shopAccount = shopAccountMapper.selectOne(shopAccount);
            flushCookie(shopAccount);
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            HttpGet get = new HttpGet("https://shop.kongfz.com/buyer/order/getOrderInfo/?orderId=" + orderId);
            //这里可以设置请求参数，token等
            get.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
            get.addHeader("cookie", shopAccount.getFuziCookie());
            HttpResponse response = httpClient.execute(get);//执行获取响应
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {//根据状态码处理
                //返回字符串
                String res = unicodeToString(EntityUtils.toString(response.getEntity(), "UTF-8"));
                System.out.println(res);
                JSONObject datas = JSONObject.parseObject(res);//转换成JSON格式
                Boolean status = (Boolean) datas.get("status");//获取返回数据状态，get获取的字段需要根据提供的返回值去获取
                ShopOrder data = JSONObject.parseObject(datas.get("data").toString(), ShopOrder.class);//"data"是根据返回值设定
                ShopOrder tmp = new ShopOrder();
                tmp.setOrderId(data.getOrderId());
                tmp = shopOrderMapper.selectOne(tmp);
                data.setAccountId(shopAccount.getId());
                if (tmp == null) {
                    data.setDangOrder(dangOrder);
                    data.setGmtCreate(new Date());
                    data.setGmtUpdate(new Date());
                    shopOrderMapper.insert(data);
                } else {
                    data.setDangOrder(dangOrder);
                    data.setGmtUpdate(new Date());
                    shopOrderMapper.update(data, new EntityWrapper<ShopOrder>().eq("order_id", tmp.getOrderId()));
                }
                tmp = new ShopOrder();
                tmp.setOrderId(data.getOrderId());
                tmp = shopOrderMapper.selectOne(tmp);
                if (tmp.getOrderStatusName().equals("卖家已发货") && tmp.getDangOrderStatus().equals("未发货")) {
                    //调用当当API 更新发货状态
                    dangOrderDeal(shopAccount, tmp);
                }
                return tmp;
            } else {
                return null;
            }

        } catch (Exception e) {
            ShopLog shopLog = new ShopLog();
            shopLog.setGmtCreate(new Date());
            shopLog.setTitle("浏览器插件调用异常");
            shopLog.setContent(e.getMessage());
            shopLogMapper.insert(shopLog);
            e.printStackTrace();
            return null;
        }

    }

    @Override
    public ShopOrder callPhone(String mobile) throws Exception {

        ApiTokenV1.ApiAuthTokenV1Builder builder = new ApiTokenV1.ApiAuthTokenV1Builder();
        // 必填参数 ak,sk,uri,host,http method, 过期时间
        builder.ak("346da55bb3c248ea84e39b5913939f05");   // ak
        builder.sk("0628356ece284d87935f73017af1c0ce");   // sk
        builder.uri("/api/v3/console/realtime/status/create");                // 接口路径
        builder.host("aicc.bce.baidu.com");               // host
        builder.httpMethod("POST");                        // http method
        builder.expireInSeconds(1800);                    // 过期时间

        // 以下是非必须参数
        // 参与生成token的请求头, 此处若使用了x-bce-date，则调用外呼api接口时，请求头内必需带上x-bce-date
//        HashMap<String, String> headerMap = new HashMap<String, String>();
//        headerMap.put("x-bce-date", "2022-06-17T08:40:14Z");
//        builder.httpHeaderMap(headerMap);
        builder.httpHeader("Content-Type", "application/json");
        builder.httpHeader("Authorization", builder.build().getToken());
        // url里?带的参数，如/api/v1/robot/list?robotName=test, 没有？参数可以不调用此方法
        builder.queryStr("robotId=b304c245-ec71-40ef-b7b8-c94e6874e8ed&mobile="+mobile+"&secretType=2");

        System.out.println(builder.build().getToken());
        String token = builder.build().getToken();
        System.out.println("token=" + token);
        // 登陆 Url
        String loginUrl = "https://aicc.bce.baidu.com/api/v3/console/realtime/status/create";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 模拟登陆，按实际服务器端要求选用 Post 或 Get 请求方式
        HttpPost httpPost = new HttpPost(loginUrl);
        // 装填参数
        List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
        nvps.add(new BasicNameValuePair("robotId", "b304c245-ec71-40ef-b7b8-c94e6874e8ed"));
        nvps.add(new BasicNameValuePair("mobile", mobile));
        nvps.add(new BasicNameValuePair("secretType", "2"));
        // 设置参数到请求对象中
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));

        // 设置header信息
        // 指定报文头【Content-type】、【User-Agent】
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("Authorization", token);
        httpPost.setHeader("x-bce-date", "2022-06-17T08:40:14Z");

        // 执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            if (response.getStatusLine().getStatusCode() == 302) {
            }
            System.out.println(EntityUtils.toString(response.getEntity(), "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放链接
            response.close();
            httpClient.close();
        }

        return null;
    }

    public void flushCookie(ShopAccount shopAccount) {
        try {
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            HttpGet getMethod = new HttpGet("https://shop.kongfz.com/buyer/order/index/?pageCurr=1&pageShow=30");
            getMethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
            getMethod.addHeader("cookie", shopAccount.getFuziCookie());

            httpClient.execute(getMethod);
            CloseableHttpResponse response = httpClient.execute(getMethod);//执行获取响应
            try {
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {//根据状态码处理
                    String strTmp = EntityUtils.toString(response.getEntity(), "UTF-8");
                    //返回字符串
                    String res = unicodeToString(strTmp);
                    JSONObject datas = JSONObject.parseObject(res);//转换成JSON格式
                    Boolean status = (Boolean) datas.get("status");//获取返回数据状态，get获取的字段需要根据提供的返回值去获取
                    if (status) {
                        return;
                    }
                }
            } catch (Exception exception) {

            } finally {
                response.close();
                httpClient.close();
            }

            System.out.println("原cookies = " + shopAccount.getFuziCookie());

            // 登陆 Url
            String loginUrl = "https://login.kongfz.com/Pc/Login/account";
            BasicCookieStore store = new BasicCookieStore();
            httpClient = HttpClients.custom().setDefaultCookieStore(store).build();
            // 模拟登陆，按实际服务器端要求选用 Post 或 Get 请求方式
            HttpPost httpPost = new HttpPost(loginUrl);

            // 装填参数
            List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
            nvps.add(new BasicNameValuePair("loginName", shopAccount.getFuziAccount()));
            nvps.add(new BasicNameValuePair("loginPass", shopAccount.getFuziPassword()));
            // 设置参数到请求对象中
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));

            // 设置header信息
            // 指定报文头【Content-type】、【User-Agent】
            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");

            // 执行请求操作，并拿到结果（同步阻塞）
            response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 302) {
                List<org.apache.http.cookie.Cookie> cookielist = store.getCookies();
                String nCookie = "";
                for (org.apache.http.cookie.Cookie cookie : cookielist) {
                    String name = cookie.getName();
                    String value = cookie.getValue();
                    nCookie += name + "=" + value + ";";
                }
                System.out.println("nCookie:" + nCookie);
                shopAccount.setFuziCookie(nCookie);
                shopAccountMapper.updateById(shopAccount);
            }
            // 释放链接
            response.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void dangOrderDeal(ShopAccount shopAccount, ShopOrder shopOrder) throws Exception {
        /**
         * 获取一下店铺的所有静态参数
         */
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        SdkClient sdkClient = new SdkClient(shopAccount.getDangAppKey(), shopAccount.getDangAppSecret(), shopAccount.getDangSession(), shopAccount.getDangVersion());

        OrderDetailsGetRequest ss = new OrderDetailsGetRequest();
        OrderDetailsGet orderDetailsGet = new OrderDetailsGet();
        orderDetailsGet.setO(shopOrder.getDangOrder());
        ss.setOrderDetailsGet(orderDetailsGet);
        OrderDetailsGetResponse resultt = null;
        try {
            resultt = sdkClient.excute(ss);
        } catch (ApiException e) {
            e.printStackTrace();

        }

        /**
         * 从当当获取订单内应当有的所有图书
         */
        OrderDetailsGetRequest odgr = new OrderDetailsGetRequest();
        OrderDetailsGet ogg = new OrderDetailsGet();
        ogg.setO(shopOrder.getDangOrder());
        odgr.setOrderDetailsGet(ogg);
        OrderDetailsGetResponse odgrp = null;
        try {
            odgrp = sdkClient.excute(odgr);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        SdkClient jiemi = new SdkClient(shopAccount.getDangAppKey(), shopAccount.getDangAppSecret(), shopAccount.getDangSession(), shopAccount.getDangVersion());
        OrdersContentDecryptRequest ordersContentDecryptRequest = new OrdersContentDecryptRequest();

        List<EncryptDTO> encryptVOS = new ArrayList<EncryptDTO>();

        EncryptDTO encryptVO1 = new EncryptDTO();
        encryptVO1.setO(resultt.getOrderID().toString());
        encryptVO1.setEncrypt_content(resultt.getEncrypt_content());
        encryptVOS.add(encryptVO1);

        ordersContentDecryptRequest.setO_cryptStr(JSON.toJSONString(encryptVOS));
        OrdersContentDecryptResponse ordersContentDecryptResponse = null;
        try {
            ordersContentDecryptResponse = jiemi.excute(ordersContentDecryptRequest);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        List<OrdersContentDecryptDTO> data = ordersContentDecryptResponse.getData();
        CryptUserInfo cryptUserInfo = data.get(0).getCryptUserInfo();


        OrderDetail o = (OrderDetail) XMLUtil.convertXmlStrToObject(OrderDetail.class, odgrp.getBody());
        SendGoodsInfo sgi = new SendGoodsInfo();
        sgi.setConsigneeAddr(cryptUserInfo.getConsigneeAddr());
        sgi.setConsigneeMobileTel(cryptUserInfo.getConsigneeMobileTel());
        sgi.setConsigneeTel(cryptUserInfo.getConsigneeTel());
        sgi.setConsigneeName(cryptUserInfo.getConsigneeName());
        o.setSendGoodsInfo(sgi);
        List<com.iotechn.unimall.data.dto.shop.XmlObject.ItemInfo> itemInfo = o.getItemsList().getItemInfo();
        /**
         * 将多个图书拼接XML
         */
        String itemsStr = "";
        for (com.iotechn.unimall.data.dto.shop.XmlObject.ItemInfo ii : itemInfo) {
            Map<String, Object> hashMap = new HashMap<>();
            hashMap.put("DANG_DANG_ITEM_ID", ii.getItemID());
            hashMap.put("SHU_LIANG", ii.getOrderCount());
            hashMap.put("PRODUCT_ID", ii.getProductItemId());
            itemsStr += SendGood.processTemplate(SendGood.ONE_ITEM, hashMap);
        }


        /**
         * 组成OrderInfo
         */
        Wrapper wrapper = new EntityWrapper();
        wrapper.like("fuzi_name", shopOrder.getShippingComName());
        List<ShopTran> list = shopTranMapper.selectList(wrapper);
        if (list.size() == 0) {
            throw new Exception("物流公司不存在");
        }
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("DANG_DANG_ORDER", shopOrder.getDangOrder());
        stringObjectHashMap.put("KUAI_DI_GONG_SI", list.get(0).getName());
        stringObjectHashMap.put("KUAI_DI_BIANMA", list.get(0).getCode1());
        stringObjectHashMap.put("KUAI_DI_GONG_SI_DIAN_HUA", list.get(0).getPhone());
        stringObjectHashMap.put("KUAI_DI_DAN_HAO", shopOrder.getShipmentNum());
        stringObjectHashMap.put("SEND_ITEMS", itemsStr);

        String orderListStr = SendGood.processTemplate(SendGood.ONE_ORDER, stringObjectHashMap);
        HashMap<String, Object> tmplHash = new HashMap<>();
        tmplHash.put("SEND_TIME", dateFormat.format(new Date()));
        tmplHash.put("ORDER_LIST", orderListStr);

        String xmlFileStr = SendGood.processTemplate(SendGood.TMPL, tmplHash);
        System.out.println(xmlFileStr);
        PrintWriter out = null;
        try {
            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream("sendGoodNotPlat.xml"), "GBK")));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        out.write(xmlFileStr);
        out.close();
        System.out.println("XML文件创建成功！");


        /**
         * 发货！！
         */
        OrderGoodsSendRequest sendGoodsRequest = new OrderGoodsSendRequest();
        sendGoodsRequest.setSendGoodsFile(new FileItem(new File("sendGoodNotPlat.xml")));
        OrderGoodsSendResponse result = null;
        try {
            result = sdkClient.excute(sendGoodsRequest);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        System.out.println(result.toString());
        if (result.getResult().getOrdersList().get(0).getOrderOperCode() == 0) {
            shopOrder.setDangOrderStatus("已发货");
            shopOrderMapper.update(shopOrder, new EntityWrapper<ShopOrder>().eq("order_id", shopOrder.getOrderId()));
        }
    }

    /**
     * Unicode转 汉字字符串
     *
     * @param str \u6728
     * @return '木' 26408
     */
    public static String unicodeToString(String str) {

        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(str);
        char ch;
        while (matcher.find()) {
            // group 6728
            String group = matcher.group(2);
            // ch:'木' 26408
            ch = (char) Integer.parseInt(group, 16);
            // group1 \u6728
            String group1 = matcher.group(1);
            str = str.replace(group1, ch + "");
        }
        return str;
    }
}
