package com.reptileclient.jlifeapp.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.reptileclient.jlifeapp.PostorderApplication;
import com.reptileclient.jlifeapp.dao.jz.HmRightsItemMapper;
import com.reptileclient.jlifeapp.dao.jz.HmRightsShopMapper;
import com.reptileclient.jlifeapp.dao.jz.HmRightsShopOriginMapper;
import com.reptileclient.jlifeapp.dao.jz.HmRightsSuppliersMapper;
import com.reptileclient.jlifeapp.dao.qg.JzOrderQgMapper;
import com.reptileclient.jlifeapp.dto.HmCreateRightRequestDTO;
import com.reptileclient.jlifeapp.dto.HmRightResultDTO;
import com.reptileclient.jlifeapp.entity.jz.HmRightsItems;
import com.reptileclient.jlifeapp.entity.jz.HmRightsShop;
import com.reptileclient.jlifeapp.entity.jz.HmRightsShopOrigin;
import com.reptileclient.jlifeapp.entity.jz.HmRightsSuppliers;
import com.reptileclient.jlifeapp.entity.qg.JzOrderQg;
import com.reptileclient.jlifeapp.service.HmBookTradeOrderService;
import me.ihxq.projects.pna.PhoneNumberInfo;
import me.ihxq.projects.pna.PhoneNumberLookup;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = PostorderApplication.class)
@ActiveProfiles("prod")
public class OkHttpUtilTest {


    @Autowired
    private HmRightsShopMapper rightsShopMapper;

    @Autowired
    private HmRightsShopOriginMapper rightsShopOriginMapper;

    @Autowired
    private HmRightsSuppliersMapper suppliersMapper;

    @Autowired
    private HmRightsItemMapper itemMapper;

    @Autowired
    private JzOrderQgMapper jzOrderQGMapper;

    @Autowired
    private HmBookTradeOrderService hmBookTradeOrderService;

//    @Test
//    public void test1() {
//        System.setProperty("webdriver.chrome.driver", "C:\\WebDriver\\bin\\chromedriver.exe");
//        ChromeOptions chromeOptions = new ChromeOptions();
//        chromeOptions.setExperimentalOption("excludeSwitches", new String[]{"enable-automation"});
//        // window.navigator.webdriver 避免淘宝检测
////        chromeOptions.setExperimentalOption("useAutomationExtension", false);
//        chromeOptions.addArguments("--disable-blink-features");
//        chromeOptions.addArguments("--incognito", "--disable-blink-features=AutomationControlled");
////        chromeOptions.addArguments("headless");
//        ChromeDriver driver = new ChromeDriver(chromeOptions);
//        String loginHtml = "https://cbbs.tmall.com/login?from=https%3A%2F%2Fworkbench.ssc.tmall.com/pages/sscstuf/sscsupplier_work_order_management%2F";
//        driver.get(loginHtml);
//        String username = "zhaiyicheng2@yeah.net";
//        String pwd = "Zyc123456.";
//        Random random = new Random();
//        try {
//            Thread.sleep(random.nextInt(3000));
//            List<WebElement> elements = driver.findElements(By.className("next-tabs-tab-inner"));
//            Thread.sleep(random.nextInt(1500));
//            WebElement webElement = elements.get(1);
//            webElement.click();
//            WebElement iframe = driver.findElement(By.xpath("//iframe[contains(@src,'https://login.taobao.com/member/login.jhtml?style=mini&sub=true')]"));
//            Thread.sleep(random.nextInt(1500));
//            driver.switchTo().frame(iframe);
//            WebElement element = new WebDriverWait(driver, 2)
//                    .until(webDriver -> webDriver.findElement(By.xpath("//input[starts-with(@name,'fm')]")));
//            element.click();
//            Thread.sleep(random.nextInt(1200));
//            for (int i = 0; i < username.length(); i++) {
//                Thread.sleep(random.nextInt(1000));
//                element.sendKeys("" + username.charAt(i));
//            }
//
//            WebElement pwdElement = new WebDriverWait(driver, 2).until(webDriver -> webDriver.findElement(By.id("fm-login-password")));
//            Thread.sleep(random.nextInt(2000));
//            pwdElement.click();
//            Thread.sleep(random.nextInt(1000));
//            for (int i = 0; i < pwd.length(); i++) {
//                Thread.sleep(random.nextInt(1000));
//                pwdElement.sendKeys("" + pwd.charAt(i));
//            }
//            //出现的浮动条
////            Actions action = new Actions(driver);
////            WebElement secondIrfame = driver.findElement(By.xpath("//iframe[contains(@id,'baxia-dialog-content')]"));
////            driver.switchTo().frame(secondIrfame);
////            WebElement moveButton = driver.findElement(By.id("nc_1_n1z"));
////            action.clickAndHold(moveButton);
////            Thread.sleep(random.nextInt(2000));
////            action.moveByOffset(258, 0).perform();
////            action.release();
//            WebElement loginElement = driver.findElementByClassName("password-login");
//            Thread.sleep(random.nextInt(1500));
//            loginElement.click();
//            while (loginHtml.equals(driver.getCurrentUrl())) {
//
//            }
//            driver.navigate().refresh();
//            System.out.println(driver.manage().getCookies());
//            Cookie scmsessid = driver.manage().getCookieNamed("SCMSESSID");
//            System.out.println(scmsessid.getValue());
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        } finally {
//            driver.quit();
//        }
//
//
//    }

//    @Test
//    public void test2() {
//        System.out.println(OkHttpUtil.getQgLoginToken());
//        String startTime = LocalDateTime.now().minusHours(1).withMinute(0).withSecond(0).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//        System.out.println("startTime = " + startTime);
//    }


//    @Test
//    public void test3() {
//        System.setProperty("webdriver.chrome.driver", "C:\\WebDriver\\bin\\chromedriver.exe");
//        ChromeOptions chromeOptions = new ChromeOptions();
//        chromeOptions.setExperimentalOption("excludeSwitches", new String[]{"enable-automation"});
//        // window.navigator.webdriver 避免淘宝检测
////        chromeOptions.setExperimentalOption("useAutomationExtension", false);
//        chromeOptions.addArguments("--disable-blink-features");
//        chromeOptions.addArguments("--incognito", "--disable-blink-features=AutomationControlled");
//        chromeOptions.addArguments("headless");
//        ChromeDriver driver = new ChromeDriver(chromeOptions);
//        String loginHtml = "https://login.portal.hemaos.com/login";
//        driver.get(loginHtml);
//        String username = "15629121030";
//        String pwd = "18268734704a";
//        Random random = new Random();
//        try {
//            WebElement iframe = driver.findElement(By.xpath("//iframe[contains(@src,'https://havanalogin.taobao.com/mini_login.htm')]"));
//            Thread.sleep(random.nextInt(1500));
//            driver.switchTo().frame(iframe);
//            WebElement element = driver.findElement(By.id("fm-login-id"));
//            element.click();
//            Thread.sleep(random.nextInt(1200));
//            inputUserNameAndPwd(username, random, element);
//            WebElement pwdElement = new WebDriverWait(driver, 2).until(webDriver -> webDriver.findElement(By.id("fm-login-password")));
//            Thread.sleep(random.nextInt(2000));
//            pwdElement.click();
//            Thread.sleep(random.nextInt(1000));
//            inputUserNameAndPwd(pwd, random, pwdElement);
//            pwdElement.sendKeys("" + pwd.charAt(11));
//            Thread.sleep(random.nextInt(1000));
//            WebElement loginElement = driver.findElementByClassName("password-login");
//            Thread.sleep(random.nextInt(1500));
//            loginElement.click();
//            driver.switchTo().defaultContent();
//            WebElement iframe1 = new WebDriverWait(driver, 3).until(a -> a.findElement(By.xpath("//iframe[contains(@id,'NOT_USE_PORTAL_SELECT')]")));
//            driver.switchTo().frame(iframe1);
//            WebElement selectElement = driver.findElement(By.xpath("//input[starts-with(@id,'merchant')]"));
//            selectElement.click();
//            WebElement webElement = new WebDriverWait(driver, 2).until(webDriver -> webDriver.findElement(By.className("next-menu-item-text")));
//            webElement.click();
//            Thread.sleep(3000);
//            List<WebElement> elements = driver.findElements(By.className("next-btn-primary"));
//            WebElement confirmEle = elements.get(1);
//            confirmEle.click();
//            driver.switchTo().defaultContent();
//            while (loginHtml.equals(driver.getCurrentUrl())) {
//
//            }
//            driver.navigate().refresh();
//            System.out.println(driver.manage().getCookies());
//            Cookie scmsessid = driver.manage().getCookieNamed("WDKSESSID");
//            System.out.println(scmsessid.getValue());
//        } catch (InterruptedException e) {
//            System.out.println(e.getMessage());
//        } finally {
//            driver.quit();
//        }
//    }


    @Test
    public void test5() {
        JSONObject js = new JSONObject();
        js.put("addrDetail", "1-2-801（不用敲门，放门口就行，辛苦啦！谢谢)");
        js.put("addrName", "雍景四季");
        js.put("agreementNo", "2021111417268131");
        js.put("arrivedFlag", false);
        js.put("beginTime", "2021-11-16 17:30:00-18:30:00");
        js.put("bookOrderNo", 14043636);
        js.put("bookTradeNo", 123);
        js.put("cancelFlag", false);
        js.put("confirmFlag", false);
        js.put("finishFlag", false);
        js.put("modifyFlag", false);
        js.put("itemId", 631854032132L);
        js.put("duration", 60);
        js.put("endTime", "2021-11-16 18:30:00");
        js.put("itemName", "洗衣机蒸洗1台 鲸致生活");
        js.put("operName", "王琮");
        js.put("paymentNo", "2021111427269160");
        js.put("position", "116.204360,39.932509");
        js.put("servantId", 1496002);
        js.put("servantName", "曹建伟");
        js.put("servantPhone", "15231177004");
        js.put("serviceContractNo", 2021111414042682L);
        js.put("serviceType", 2);
        js.put("shopCode", "BJ9019");
        js.put("startTime", "2021-11-16 17:30:00");
        js.put("stationCode", "70001");
        js.put("stationName", "北京品类站");
        js.put("status", 1);
        js.put("userName", "邵冬雪");
        js.put("userPhone", "15910869971");
        System.out.println(js);
    }

    @Test
    public void test6() {
        String s = "上海上海市浦东新区花木街道-锦康路389弄香梅花园5期1号楼1703";
        System.out.println(s.substring(0, 2));
    }

    @Test
    public void test7() {
        PhoneNumberLookup phoneNumberLookup = new PhoneNumberLookup();
        PhoneNumberInfo phoneNumberInfo = phoneNumberLookup.lookup("13602501683").get();
        System.out.println(phoneNumberInfo.getAttribution().getCity());
        System.out.println(phoneNumberInfo.getAttribution().getProvince());
    }

    @Test
    public void test8() {
        String info = OkHttpUtil.getHmRightShop();
        try {
            List<HmRightsShopOrigin> shops = JSONArray.parseArray(info, HmRightsShopOrigin.class);
            shops.forEach(a -> a.setCreateTime(new Date()).setUpdateTime(new Date()));
            rightsShopOriginMapper.batchInsert(shops);
            String regex = "((废弃|关闭|禁止)+\\S+\\s*\\S+)|\\S+\\s*\\S+放弃+";
            String city = "(上海|深圳|南京|杭州|苏州|北京)+\\S+\\s*\\S+";
            List<HmRightsShop> aliveShops = shops.stream().filter(a -> !a.getShopName().matches(regex))
                    .filter(a -> a.getShopName().matches(city))
                    .map(a -> new HmRightsShop().setShopName(a.getShopName().replaceAll("（\\S+）", "")).setShopCode(a.getShopCode()).setCreateTime(a.getCreateTime()).setUpdateTime(a.getUpdateTime()))
                    .collect(Collectors.toList());
            rightsShopMapper.batchInsert(aliveShops);
        } catch (Exception e) {
            throw new RuntimeException("获取盒马门店信息失败，失败原因：" + e.getMessage());
        }

    }

    @Test
    public void test9() {
        List<HmRightsSuppliers> suppliers = suppliersMapper.selectAll();
        List<HmRightsShop> shops = rightsShopMapper.selectAll();
        String regEx_special = "[`~!@#$%^&*()=|{}':;,\\[\\].<>/?！￥…（）—【】‘；：”“’。，、？]";
        Pattern compile = Pattern.compile(regEx_special, Pattern.CASE_INSENSITIVE);
        for (HmRightsSuppliers supplier : suppliers) {
            for (HmRightsShop shop : shops) {
                String hmRightServiceItem = OkHttpUtil.getHmRightServiceItem(supplier.getSupplyCode(), shop.getShopCode());
                HmRightResultDTO resultDTO = JSONObject.parseObject(hmRightServiceItem, HmRightResultDTO.class);
                if (resultDTO.getSuccess()) {
                    List<HmRightsItems> hmRightsItems = JSONArray.parseArray(resultDTO.getData(), HmRightsItems.class);
                    if (null != hmRightsItems && !hmRightsItems.isEmpty()) {
                        HmRightsItems items = hmRightsItems.get(0);
                        System.out.println("items = " + items);
                        if (null != items.getItems() && !items.getItems().isEmpty()) {
                            items.getItems().forEach(a -> a.setSkuName(compile.matcher(a.getSkuName()).replaceAll("").replaceAll("\\u00A0", " ")).setShopCode(items.getShopCode()
                            ).setSupplyCode(supplier.getSupplyCode()));
                            itemMapper.batchInsert(items.getItems());
                        }
                    }

                }

            }
        }

    }


    /**
     * 生成权益单
     */
    @Test
    public void test10() {
        HmCreateRightRequestDTO dto = new HmCreateRightRequestDTO();
        dto.setItemId("668562452648");
        dto.setSupplierCode("282160323");
        dto.setShopCode("8090");
        dto.setUserName("luke");
        dto.setUserPhone("18555065889");
        dto.setUseTimes("3");
        dto.setRefHmOrderNo("123435667");
        dto.setUseCode("05");
        dto.setUserRemark("test");
        String rightOrder = OkHttpUtil.createHmRightOrder(dto);
        System.out.println("rightOrder = " + rightOrder);

    }

    /**
     * 查询权益单详情
     */
    @Test
    public void test11() {
        String key = "2022031715397120";
        String hmRightDetail = OkHttpUtil.getHmRightDetail(key);
        System.out.println("hmRightDetail = " + hmRightDetail);


    }


    @Test
    public void test2(){
        LocalDateTime nowTime = LocalDateTime.now();
        LocalDateTime startTime = nowTime.minusMonths(12);
        long now = nowTime.atZone(ZoneId.systemDefault()).toEpochSecond() * 1000;
        for (int i = 0; i < 12; i++) {
            long startTimeStamp= startTime.plusMonths(i).atZone(ZoneId.systemDefault()).toEpochSecond() * 1000;
            long endTimeStamp= startTime.plusMonths(i+1).atZone(ZoneId.systemDefault()).toEpochSecond() * 1000;
            List<JzOrderQg> qgList = jzOrderQGMapper.selectByCreateTime(startTimeStamp, endTimeStamp);
            System.out.println("startTime="+startTime.plusMonths(i)+"endTime="+startTime.plusMonths(i+1)+",qgList = " + qgList);
        }
    }

}
