package com.diaoyun.zion;

import com.diaoyun.zion.chinafrica.constant.KeyConstant;
import com.diaoyun.zion.chinafrica.dao.TbCfIssueCouponDao;
import com.diaoyun.zion.chinafrica.entity.TbCfIssueCouponEntity;
import com.diaoyun.zion.chinafrica.service.SpiderService;
import com.diaoyun.zion.chinafrica.service.TbCfCouponService;
import com.diaoyun.zion.chinafrica.service.TbCfIssueCouponService;
import com.diaoyun.zion.chinafrica.service.TbCfUserInfoService;
import com.diaoyun.zion.master.thread.TaskLimitSemaphore;
import com.diaoyun.zion.master.util.AESUtils;
import com.diaoyun.zion.master.util.IdUtil;
import com.diaoyun.zion.master.util.SMSUtil;
import com.stripe.exception.StripeException;
import freemarker.template.Configuration;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.message.BasicNameValuePair;
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.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.*;
import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ZionApplicationTests {

    @Autowired
    private Configuration config;

    @Autowired
    private SpiderService spiderService;

    @Autowired
    private TbCfIssueCouponDao tbCfIssueCouponDao;
    @Autowired
    private TbCfCouponService tbCfCouponService;
    @Autowired
    private RedisTemplate redisTemplate;
    private TaskLimitSemaphore taskLimitSemaphore = new TaskLimitSemaphore(12);
    @Autowired
    private TbCfUserInfoService tbCfUserInfoService;
    //private List<Map<String, Object>> futureList = new ArrayList<Map<String, Object>>();

    @Test
    public void contextLoads() throws InterruptedException, URISyntaxException, IOException, ExecutionException, StripeException, TimeoutException {
        Map map=new HashMap();
        map.entrySet();
        /*Template t = config.getTemplate("email-template.ftl");
        Map<String,String> model=new HashMap<>();
        model.put("Name","yonghuming");
        model.put("location","zhongguo");
        String html = FreeMarkerTemplateUtils.processTemplateIntoString(t, model);
        HtmlEmail email=new HtmlEmail();//创建一个HtmlEmail实例对象
        email.setHostName("smtp.yeah.net");//邮箱的SMTP服务器，一般123邮箱的是smtp.123.com,qq邮箱为smtp.qq.com
        email.setCharset(Consts.UTF_8.name());//设置发送的字符类型
        email.addTo("zhengfanguang@163.com");//设置收件人
        email.setFrom("chinafrica@yeah.net","chinafrica");//发送人的邮箱为自己的，用户名可以随便填
        email.setAuthentication("chinafrica@yeah.net","diaoyun2019");//设置发送人的邮箱和用户名和授权码(授权码是自己设置的)
        email.setSubject("测试22");//设置发送主题
        email.setMsg(html);//设置发送内容
        email.send();//进行发送*/
        /*List<Map<String,Object>> returnList=new ArrayList<>();
        String s=JSONUtils.toJSONString(returnList);
        System.out.println(s);*/
        /*test copyProperties*/

        /*TbCfUserInfoVo tbCfUserInfoVo = new TbCfUserInfoVo();
        TbCfUserInfoEntity tbCfUserInfoEntity =new TbCfUserInfoEntity();
        tbCfUserInfoVo.setAccount("11111");
        BeanUtils.copyProperties(tbCfUserInfoVo,tbCfUserInfoEntity);
        System.out.println(JSON.toJSONString(tbCfUserInfoEntity));*/
        /*test copyProperties*/
        /*String password=PasswordProvider.encrypt("123456");
        System.out.println("password:"+password);
        String password2=PasswordProvider.encrypt(password);
        System.out.println("password2:"+password2);*/


        /*String url="http://dev.diaosaas.com/zion/chinafrica/order";
        HttpClient client = HttpClientBuilder.create().build();//构建一个Client
        Map<String,String> paramMap=new HashMap<>();
        paramMap.put("beginTime","1564548584");
        paramMap.put("endTime","1564558584");
        List<NameValuePair> formparams = setHttpParams(paramMap);
        String param = URLEncodedUtils.format(formparams, Consts.UTF_8.name());
        HttpGet httpGet = new HttpGet();    //构建一个GET请求
        httpGet.setURI(URI.create(url + "?" + param));
        HttpResponse response = client.execute(httpGet);//提交GET请求
        HttpEntity result = response.getEntity();//拿到返回的HttpResponse的"实体"
        String content = EntityUtils.toString(result);
        JSONArray res = JSONArray.fromObject(content);//把信息封装为jsonarray
        System.out.println(res);*/


        /*爬取淘宝数据*/
        /*String url="https://item.taobao.com/item.htm?spm=a230r.1.14.21.22543186dllgZW&id=538082050316&ns=1&abbucket=18#detail";
        URI uri=new URIBuilder(url).build();

        //创建一个HttpContext对象，用来保存Cookie
        //HttpClientContext httpClientContext = HttpClientContext.create();


        //构造自定义的HttpClient对象
        CloseableHttpClient httpClient = HttpClientUtil.createBrowserClient();

        //构造请求对象
        HttpUriRequest httpUriRequest = RequestBuilder.get().setUri(uri).build();

        *//*****************获取商品详情链接********************//*
        //执行请求，传入HttpContext，将会得到请求结果的信息
        HttpResponse httpResponse=httpClient.execute(httpUriRequest);
        HttpEntity result = httpResponse.getEntity();//拿到返回的HttpResponse的"实体"
        String content = EntityUtils.toString(result);
        //获取商品详情url
        Map<String,String> infoMap= JsoupUtil.getTbItemDetail(content);
        String usableSibUrl=infoMap.get("sibUrl");
        //解析商品sku信息
        Map<String,Object> propMap=JsoupUtil.getPropMap(content);
        //httpClient.close();
        System.out.println("时间："+System.currentTimeMillis());
        //翻译
        //translateProp(propMap);
        for(Map<String,Object> futureMap:futureList) {

            Future<Map<String,Object>> future= (Future<Map<String, Object>>) futureMap.get("future");
            Map<String,Object> valeMap = (Map<String,Object> ) futureMap.get("value");
            while(!future.isDone());//Future返回如果没有完成，则一直循环等待，直到Future返回完成
            System.out.println("翻译完成！！！");
            Map<String,Object> resultMap=future.get();
            String targetText="unknow";
            if(resultMap!=null&&(int)resultMap.get("ret")==0) {
                Map<String,Object> dataMap=(Map<String,Object>)resultMap.get("data");
                targetText= (String) dataMap.get("target_text");
                valeMap.put("translate",targetText);
            } else {
                System.out.println("翻译出错");
            }
        }
        //关闭线程池
        taskLimitSemaphore.shutdown();
        System.out.println("时间："+System.currentTimeMillis());
        *//*****************获取商品详情********************//*
        //删除需要登录的模块
        usableSibUrl=deleteLoginModule(usableSibUrl);
        URI sibUri=new URIBuilder(usableSibUrl).build();
        //构造请求对象
        HttpUriRequest sibUriRequest = RequestBuilder.get().setUri(sibUri).build();
        BasicHeader basicHeader=new BasicHeader("referer", url);
        //构造自定义的HttpClient对象
        CloseableHttpClient sibClient = HttpClientUtil.createBrowserClient(basicHeader);
        //创建一个HttpContext对象，用来保存Cookie
        //HttpClientContext sibClientContext = HttpClientContext.create();
        //执行请求，传入HttpContext，将会得到请求结果的信息
        HttpResponse sibResponse=sibClient.execute(sibUriRequest);
        HttpEntity sibResult = sibResponse.getEntity();//拿到返回的HttpResponse的"实体"
        String sibContent = EntityUtils.toString(sibResult);
        //unicode 解码
        sibContent=StringEscapeUtils.unescapeJava(sibContent);
        Map sibMap=JSONObject.fromObject(sibContent);
        sibMap.put("Jprop",propMap);
        System.out.println(JSONObject.fromObject(propMap));
        //从请求结果中获取Cookie，此时的Cookie已经带有登录信息了
        //CookieStore store = httpClientContext.getCookieStore();
        sibClient.close();*/

        ///////////////////////*获取淘宝数据 END*//////////////

        /*腾讯词性分析*//////////////////////////////////
        /*ExecutorService threadPool = Executors.newSingleThreadExecutor();
        TencentWordsegParam param=new TencentWordsegParam ("夏季短袖衬衫男韩版修身免烫中袖衬衣男潮流帅气休闲五分袖黑色寸");
        Future<Map<String, Object>> future = threadPool.submit(new WordposCallable(param));
        while(!future.isDone());//Future返回如果没有完成，则一直循环等待，直到Future返回完成

        Map<String,Object> resultMap=future.get();
        System.out.println(resultMap);*/
        /*腾讯词性分析*/////END/////////////////////////////
        //BigDecimal rate=spiderService.getExchangeRate(null);

        /*BigDecimal rate2=new BigDecimal("0.1");
        BigDecimal rate3=new BigDecimal("0.2");
        BigDecimal realityPay=rate2.subtract(rate3);
        List<TbCfCouponEntity> tbCfCouponList=new ArrayList<>();
        for(int i=0;i<5;i++) {
            TbCfCouponEntity tbCfCouponEntity = new TbCfCouponEntity();
            int random= (int) (Math.random()*1000);
            BigDecimal rate=BigDecimal.valueOf(0.101*random);
            tbCfCouponEntity.setDeductAmount(rate);
            tbCfCouponList.add(tbCfCouponEntity);
        }

        //根据抵扣金额排序
        Collections.sort(tbCfCouponList, Comparator.comparing(TbCfCouponEntity::getDeductAmount));

        Collections.reverse(tbCfCouponList);*/
        /*String str="2019083112151135770172";
        //Long a=Long.parseLong(str);
        Long a=Long.valueOf(str);

        System.out.println(a);*/
        /*redisTemplate.opsForValue().set("orderNo:156556263124101022", "dadada", 5, TimeUnit.SECONDS);
        while (true) {

        }*/

       /* String a="dd:ff:"+""+":";
        String array[]=a.split(":");
        for(String b:array) {
            if(b!=null) {
                System.out.println(b);
            }
            System.out.println(b);
        }
        System.out.println(array);*/

        //Stripe.apiKey = "sk_test_Gsm7T9FaRePdD7grZdpZYSxv005PqQlGqS";

        /*Map<String, Object> chargeParams = new HashMap<String, Object>();
        chargeParams.put("amount", 2000);
        chargeParams.put("currency", "hkd");
        chargeParams.put("description", "Charge for jenny.rosen@example.com");
        chargeParams.put("source", "tok_1FEpzdD6H43jAEw6TWDzAJpF");
// ^ obtained with Stripe.js cardid "card_1FEpzcD6H43jAEw6GrSZVany"
        Charge charge=Charge.create(chargeParams);
        System.out.println(new Gson().toJson(charge));*/
        /*加密解密*/
        /*String key = "``8d47e4d5f4r7d4"; // 128 bit key
        String encryptStr=AESUtils.encrypt(KeyConstant.AES_KEY,"pk_test_uljWJWUuD8fzZXPlGtDZ1fxx00o1ZKr7QL");
        String decryptStr=AESUtils.decrypt(key,encryptStr);
        System.out.println(encryptStr);
        System.out.println(decryptStr);*/
        /*加密解密*/
        /*BigDecimal a=new BigDecimal("1.32");
        BigDecimal b=new BigDecimal("100");
        BigDecimal c=BigDecimal.valueOf(1.32);*/

        /*批量爬取*/
        /*String url="https://item.taobao.com/item.htm?id=557199852598&ali_refid=a3_430585_1006:1106497657:N:2wUULxiBbwexwSVFuKhIgA%3D%3D:5ade3f0953f72451a97c3d237c7ab881&ali_trackid=1_5ade3f0953f72451a97c3d237c7ab881&spm=a230r.1.14.11";
        ExecutorService threadPool = Executors.newFixedThreadPool(20);
        for(int i=0;i<100;i++) {
            threadPool.submit(()->{
                try {
                    Map<String,Object> itemMap=spiderService.getItemDetail(url);
                    System.out.println(new Gson().toJson(itemMap));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
            });
        }

        while (true) {

        }*/

        /*批量爬取*/

        /*天猫爬取*/
       /* String url="https://detail.tmall.com/item.htm?spm=a220m.1000858.1000725.71.5eac174fM6rzkB&id=570475903407&skuId=4611686588903291311&user_id=1689254786&cat_id=2&is_b=1&rn=cf06f08b8565fadd6e8f12c0c5bf581a";
        JSONObject json=spiderService.getItemDetail(url);
        System.out.println(json);
*/

       /*分词********************/
        /*ExecutorService threadPool = Executors.newFixedThreadPool(20);
        TbCfOrderServiceImpl tbCfOrderServiceImpl =new TbCfOrderServiceImpl();
        long a=System.currentTimeMillis();
        List<Map<String, Object>> futureList= new ArrayList<>();
        for(int i=0;i<10;i++) {
            Map<String, Object> titleMap = new HashMap();
            String text = "夏季短袖衬衫男韩版修身免烫中袖衬衣男潮流帅气休闲五分袖黑色寸";
            titleMap.put("text", text);
            WordposHelper.separeteText(futureList, titleMap, text);
        }
        WordposHelper.waitForResult(futureList);
        long b=System.currentTimeMillis();
        System.out.println(b-a);

        while (true) {

        }*/
        /*分词 END*****************8***/
        /*String url="http://shd.kjwlxt.com/api/track.php";
        Map<String,Object> paramMap= new HashMap<>();
        List<Map<String,String>> data=new ArrayList<>();
        Map<String,String> dataMap=new HashMap<>();
        dataMap.put("order_no","ceshi20190917");
        data.add(dataMap);
        paramMap.put("user_no","shd806");
        paramMap.put("token","d44426bd5b64dd2");
        paramMap.put("data",data);
        String res=HttpClientUtil.sendPostWithBodyParameter(url,paramMap);
        Map map=GsonUtil.GsonToMaps(res);*/

        long b=IdUtil.createLongIdByDate();
        System.out.println(b);


    }

    /*private void translateProp(Map<String, Object> propMap) throws ExecutionException, InterruptedException {
     *//*腾讯翻译*//*

        for(Map.Entry<String,Object>entry : propMap.entrySet()) {
            String key=entry.getKey();
            Map <String,Object> value= (Map<String, Object>) entry.getValue();
            //翻译属性名
            if(ValidateUtils.isContainChinese(key)) {
                translateText(value,key);
                //value.put("translate",translate);
            }
            //翻译sku title
            if(value!=null&&value.size()>0) {
                translateTitle(value);
            }

        }



    }

    private void translateTitle(Map<String, Object> skuMap) throws ExecutionException, InterruptedException {
        for(Map.Entry<String,Object>entry : skuMap.entrySet()) {
            String key=entry.getKey();
            if(entry.getValue() instanceof Map) {
                Map<String, Object> value = (Map<String, Object>) entry.getValue();
                String title = (String) value.get("title");
                if (StringUtils.isNotBlank(title)) {
                    //翻译属性名
                    if (ValidateUtils.isContainChinese(title)) {
                        translateText(value,title);
                        //value.put("translate", translate);
                    }
                }
            }
        }
    }

    private void translateText(Map<String,Object> valeMap,String text) throws ExecutionException, InterruptedException {
        TencentTranslateParam tencentTranslateParam =new TencentTranslateParam(text);
        Future<Map<String,Object>> future = null;
        try {
            future = taskLimitSemaphore.submit(new TranslateCallable(tencentTranslateParam));
            Map<String,Object> map=new HashMap<>();
            map.put("future",future);
            map.put("value",valeMap);
            futureList.add(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/

    /**
     * 去除需要登录或者不需要返回的参数
     *
     * @param usableSibUrl
     * @return
    */
    private String deleteLoginModule(String usableSibUrl) {
        usableSibUrl = usableSibUrl.replaceAll("couponActivity", "");
        usableSibUrl = usableSibUrl.replaceAll("soldQuantity", "");
        usableSibUrl = usableSibUrl.replaceAll("tradeContract", "");
        usableSibUrl = usableSibUrl.replaceAll("upp", "");
        //TOOD 运费格式有问题，暂去除
        usableSibUrl = usableSibUrl.replaceAll("deliveryFee", "");
        usableSibUrl = usableSibUrl.replaceAll("delivery", "");
        return usableSibUrl;
    }


    //使用序列化的方式保存CookieStore到本地文件，方便后续的读取使用
    private static void saveCookieStore(CookieStore cookieStore, String savePath) throws IOException {

        FileOutputStream fs = new FileOutputStream(savePath);
        ObjectOutputStream os = new ObjectOutputStream(fs);
        os.writeObject(cookieStore);
        os.close();

    }

    //读取Cookie的序列化文件，读取后可以直接使用
    private static CookieStore readCookieStore(String savePath) throws IOException, ClassNotFoundException {

        FileInputStream fs = new FileInputStream(savePath);//("foo.ser");
        ObjectInputStream ois = new ObjectInputStream(fs);
        CookieStore cookieStore = (CookieStore) ois.readObject();
        ois.close();
        return cookieStore;


    }

    private List<NameValuePair> setHttpParams(Map<String, Object> paramsMap) {
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        for (String key : paramsMap.keySet()) {
            list.add(new BasicNameValuePair(key, String.valueOf(paramsMap.get(key))));
        }
        return list;
    }


    @Test
    public void testDate() throws ParseException {

        String res = "2019-10-2 10:04:59";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(res);
        long it = date.getTime();
        String s = String.valueOf(it);
        System.out.println(s);

    }

    @Test
   public void testP(){

        BigDecimal decimal=new BigDecimal("699");
        BigDecimal de=new BigDecimal("100");
        decimal.divide(de,2,BigDecimal.ROUND_HALF_UP);

    }

    @Test
    public  void testAesut(){

     String a =  AESUtils.encrypt(KeyConstant.AES_KEY,"sk_test_tGl2q7Omxehpli7R3Z6xU6G900iL1eX32c");
        System.out.println(a);
    }

    @Test
    public  void test(){
        redisTemplate.opsForValue().set("hello","helloworld");
        Object hello = redisTemplate.opsForValue().get("hello");
        System.out.println(hello);
        redisTemplate.delete("hello");
        System.out.println("==============="+redisTemplate.opsForValue().get("hello"));

    }
    @Autowired
    private TbCfIssueCouponService tbCfIssueCouponService;
    @Test
    public void testLogin(){
        TbCfIssueCouponEntity issue = new TbCfIssueCouponEntity();
        String coupon_id = "";
        String issuseCoupon_id = IdUtil.createIdbyUUID();
        //把上面获取到的值，赋值到实体类中
        issue.setCouponId("1087f4a682354843b145d36c27d2d902");
        issue.setIssueId("5308312b76cd4819b7d94f01dea12ab8");
        issue.setCreateTime(new Date().toString());
        issue.setUserId("5308312b76cd4819b7d94f01dea12ab8");
        issue.setNick("avatar");
        issue.setEnableFlag(0);
        tbCfIssueCouponService.save(issue);
    }

    @Test
    public void testInsert(){
        TbCfIssueCouponEntity issue = new TbCfIssueCouponEntity();

        String issuseCoupon_id = IdUtil.createIdbyUUID();
        //把上面获取到的值，赋值到实体类中
        issue.setCouponId("1087f4a682354843b145d36c27d2d90e");
        issue.setCouponIssuetableId(issuseCoupon_id);
        issue.setCreateTime(new Date().toString());
        issue.setUserId(issuseCoupon_id);
        issue.setNick("都比");
        issue.setEnableFlag(1);
        tbCfIssueCouponService.save(issue);
    }
    @Test
    public void testCouponStatus(){
        String userId="c45e8b04b9d44cf4b48e2d5cdb18fbcd";
        String couponId="1087f4a682354843b145d36c27d2d90e";
        tbCfIssueCouponDao.changeCoupnStatus(userId,couponId);
    }

    @Test
    public void testPhone() throws IOException {
        //SMSUtil.yzCode("13751400455");
    }
}
