package com.iotechn.unimall.admin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
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.OrderDetailsGetRequest;
import com.dangdang.openplatform.openapi.sdk.request.order.OrderGoodsSendRequest;
import com.dangdang.openplatform.openapi.sdk.request.order.OrdersContentDecryptRequest;
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.OrderDetailsGetResponse;
import com.dangdang.openplatform.openapi.sdk.response.order.OrderGoodsSendResponse;
import com.dangdang.openplatform.openapi.sdk.response.order.OrdersContentDecryptResponse;
import com.dangdang.openplatform.openapi.sdk.responsemodel.order.CryptUserInfo;
import com.dangdang.openplatform.openapi.sdk.responsemodel.order.OrdersContentDecryptDTO;
import com.iotechn.unimall.data.domain.shop.ShopAccount;
import com.iotechn.unimall.data.domain.shop.ShopLog;
import com.iotechn.unimall.data.domain.shop.ShopOrder;
import com.iotechn.unimall.data.domain.shop.ShopTran;
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.ShopOrderMapper;
import com.iotechn.unimall.data.mapper.shop.ShopTranMapper;
import com.iotechn.unimall.data.util.XMLUtil;
import org.apache.http.HttpStatus;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author:chengchangjiang
 * @Description:
 * @Date:Created in 12:34 2022-06-16
 */
@Component
public class MyApplicationLisenter implements ApplicationListener<ContextRefreshedEvent> {

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

    @Autowired
    private ShopAccountMapper shopAccountMapper;

    @Autowired
    private ShopLogMapper shopLogMapper;
    @Autowired
    private ShopOrderMapper shopOrderMapper;
    @Autowired
    private ShopTranMapper shopTranMapper;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent e) {
        logger.info("实现了ApplicationListener的onApplicationEvent方法");
        new Thread(new Runnable() {
            @Override
            public void run() {
                doSomething2();
            }
        }).start();
    }
    private void doSomething2() {
        try{
            List<ShopAccount> list = shopAccountMapper.selectList(new EntityWrapper<ShopAccount>().orderBy("id",false));
            for (ShopAccount shopAccount:list
            ) {
                flushCookie(shopAccount);
                for (int i = 1; i <= 5; i++) {
                    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
                    HttpGet get = new HttpGet("https://shop.kongfz.com/buyer/order/index/?pageCurr=" + i + "&pageShow=300&orderStatus=ShippedToReceipt");
                    //这里可以设置请求参数，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());

                    CloseableHttpResponse response = httpClient.execute(get);//执行获取响应
                    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获取的字段需要根据提供的返回值去获取
                            List<ShopOrder> data = JSONArray.parseArray(datas.get("data").toString(), ShopOrder.class);//"data"是根据返回值设定
                            if (data.size() == 0) {
                                break;
                            }
                            for (ShopOrder tmp : data
                            ) {
                                //正则表达式，用于匹配非数字串，+号用于匹配出多个非数字串
                                String regEx = "[^0-9]+";
                                Pattern pattern = Pattern.compile(regEx);
                                //用定义好的正则表达式拆分字符串，把字符串中的数字留出来
                                String[] cs = pattern.split(tmp.getRemarkText());
                                String dangOrder = "";
                                for (String str : cs
                                ) {
                                    if (dangOrder.length() >= 11 || str.equals("*")) {
                                        break;
                                    }
                                    dangOrder += str;
                                }
                                tmp.setDangOrder(dangOrder);
                                tmp.setAccountId(shopAccount.getId());
                                Long time  = Long.parseLong(tmp.getShippingTime())+8*60*60;
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
                                String time1 = sdf.format(new Date(time * 1000));
                                tmp.setShippingTime(time1);
                                tmp.setDeleteFlag(0);
                                tmp.setGmtUpdate(new Date());
                                tmp.setGmtCreate(new Date());
                                if (tmp.getShippingComName().equals("快递包裹") || tmp.getShippingComName().equals("挂号印刷品")) {
                                    tmp.setShippingComName("中国邮政");
                                }
                                ShopOrder tt = new ShopOrder();
                                tt.setOrderId(tmp.getOrderId());
                                tt = shopOrderMapper.selectOne(tt);
                                if (tt == null) {
                                    shopOrderMapper.insert(tmp);
                                } else {
                                    if (tt.getDangOrderStatus().equals("未发货") && !tt.getDangOrder().equals(tmp.getDangOrder())) {
                                        shopOrderMapper.update(tmp, new EntityWrapper<ShopOrder>().eq("order_id", tt.getOrderId()));
                                    }
                                }
                            }
                        }
                    } catch (IOException e) {
                        throw e;
                    } finally {
                        response.close();
                        httpClient.close();
                    }
                }
            }
            doSomething2();
        }
        catch (Exception e){
            ShopLog shopLog = new ShopLog();
            shopLog.setGmtCreate(new Date());
            shopLog.setTitle("爬取定时任务异常");
            shopLog.setContent(e.getMessage());
            shopLogMapper.insert(shopLog);
            e.printStackTrace();
        }

    }
    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");
                    JSONObject datas = JSONObject.parseObject(strTmp);//转换成JSON格式
                    Boolean status = (Boolean) datas.get("status");//获取返回数据状态，get获取的字段需要根据提供的返回值去获取
                    if (status) {
                        return;
                    }
                }
            } catch (Exception e) {
                throw e;
            } 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);
                ShopLog shopLog = new ShopLog();
                shopLog.setGmtCreate(new Date());
                shopLog.setTitle("更新cookie成功");
                shopLog.setContent("账号：" + shopAccount.getFuziAccount() + ",cookie：" + nCookie);
                shopLogMapper.insert(shopLog);
            } else {
                ShopLog shopLog = new ShopLog();
                shopLog.setGmtCreate(new Date());
                shopLog.setTitle("更新cookie失败");
                shopLog.setContent(response.toString());
                shopLogMapper.insert(shopLog);
            }
            // 释放链接
            response.close();

        } catch (Exception e) {
            e.printStackTrace();
            ShopLog shopLog = new ShopLog();
            shopLog.setGmtCreate(new Date());
            shopLog.setTitle("更新cookie异常");
            shopLog.setContent(e.getMessage());
            shopLogMapper.insert(shopLog);
        }

    }


    /**
     * 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;
    }

}
