package com.cesgroup.homwork.mybatis;

import cn.hutool.core.lang.Console;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.cesgroup.homwork.mybatis.sample.entity.City;
import com.cesgroup.homwork.mybatis.sample.mapper.CityMapper;
import com.cesgroup.homwork.mybatis.sample.service.BatchService;
import org.junit.jupiter.api.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.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest
class MybatisApplicationTests {

    @Resource
    private CityMapper cityMapper;
    @Autowired
    private BatchService batchService;
    ///////////////////////////////////////////////////
    ////
    ////                   测试类型转换
    ////
    ///////////////////////////////////////////////////
    @Test
    void contextLoads() {
        City city = new City();
        Map<String, Object> context = new HashMap<>();
        context.put("a","aaa");
        context.put("b","bb");
        context.put("c","c");
        context.put("d","dddddddddd");
        city.setId(IdUtil.simpleUUID())
//                .setId("857b193a846a4246a2087358daa9c9b6")
                .setName(RandomUtil.randomString(4))
                .setContext(context);
        cityMapper.insert(city);
    }
    
    @Test
    void select() {
        City byId = cityMapper.findById("857b193a846a4246a2087358daa9c9b6");
        Console.log(byId);
        Console.log(JSONUtil.toJsonStr(byId));
    }

    ///////////////////////////////////////////////////
    ////
    ////                   测试批量处
    ////
    ///////////////////////////////////////////////////
    @Test
    void batch() {
        List<City> cities = new ArrayList<City>();
        for (int i = 0; i < 10000; i++) {
            City city = new City();
            city.setName(RandomUtil.randomString("是否是法发热人刚明年吧",4));
            cities.add(city);
        }
        batchService.batchInsertCity(cities);

        this.noBath(cities);
    }
    void noBath(List<City> cities){
        //批量保存执行前时间
        long start=System.currentTimeMillis();
        for (City city : cities) {
            city.setId(IdUtil.simpleUUID());
            cityMapper.insert(city);
        }
        long end=  System.currentTimeMillis();
        long time2= end-start;
        //批量保存执行后的时间
        Console.log("非批量执行时长"+time2);
    }
}
