package cn.estsh.i3plus.core.apiservice.controller;

import cn.estsh.i3plus.core.api.iservice.busi.*;
import cn.estsh.i3plus.core.apiservice.controller.busi.ComputePi;
import cn.estsh.i3plus.core.apiservice.controller.busi.PersonnelController;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.bean.BaseBean;
import cn.estsh.i3plus.pojo.base.codemaker.SnowflakeIdMaker;
import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.ImppEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.ResourceEnumUtil;
import cn.estsh.i3plus.pojo.model.platform.UserDetailModel;
import cn.estsh.i3plus.pojo.platform.bean.*;
import cn.estsh.i3plus.pojo.platform.platbean.SysLogSystem;
import cn.estsh.impp.framework.boot.eureka.EurekaClientHealthCheck;
import cn.estsh.impp.framework.boot.exception.ImppBusiException;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.util.ImppRedis;
import cn.estsh.impp.framework.boot.util.ResultBean;
import cn.estsh.impp.framework.boot.util.ValidatorBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * @Description : IMPP性能测试
 * @Reference :
 * @Author : yunhao
 * @CreateDate : 2019-02-19 11:29
 * @Modify:
 **/
@RestController
@Api(description = "IMPP性能测试")
@RequestMapping("/impp/white/sys-test")
public class DemoTestingController {
    public static final Logger LOGGER = LoggerFactory.getLogger(DemoTestingController.class);

    String TEXT = "飓风黑兹尔是1954年大西洋飓风季期间造成死亡人数最多、经济损失最惨重的飓风。这场风暴夺走了海地多达1000人的生命，然后又以四级飓风强度从南、北卡罗莱纳州边境附近袭击美国，造成95人丧生。之后黑兹尔转变成温带风暴，但仍然致使81人遇难，其中大部分来自多伦多。由于风暴造成了重大人员伤亡和财产损失，其名称“黑兹尔”因此从大西洋风暴命名名单上退役。黑兹尔摧毁了海地40%的咖啡树和50%的可可作物，对当地经济的影响持续了数年之久。飓风在南、北卡罗莱纳州登陆，冲击点附近的大部分海滨住宅被毁。气旋从北卡罗莱纳州沿大西洋海岸北上，先后影响了弗吉尼亚州、西弗吉尼亚州、马里兰州、特拉华州、新泽西州、宾夕法尼亚州和纽约州，产生的阵风时速有近160公里，造成的经济损失高达3.08亿美元。多伦多市内及周边有许多溪流溢出，导致严重的洪涝灾害。加拿大遭受的损失达到1.35亿加拿大元。由于缺少应对热带气旋的经验，加上风暴强度的保持时间异常之长，多伦多所受影响的严重程度是前所未有的";

    SnowflakeIdMaker snowflakeIdMaker = new SnowflakeIdMaker();

    @Autowired
    private PersonnelController personnelController;

    @Autowired
    private IPersonnelService personnelService;

    @Autowired
    private ISysLogSystemService syslogSystemService;

    @Autowired
    private ISysToolService sysToolService;

    @Autowired
    private EntityManager entityManager;

    @Autowired
    public ISystemResourceService systemResourceService;

    @Autowired
    private ITestService testService;

    @Autowired
    private EurekaClientHealthCheck healthCheck;

    @Autowired
    private ISysPositionService positionService;

    @Autowired
    private ISysOrganizeService organizeService;

    @Autowired
    private ISysDepartmentService departmentService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private ISysRoleService roleService;

    @Resource(name = "redisRes")
    private ImppRedis redisRes;

    /**
     * 压力测试
     *
     * @param num      对象生成数量/π计算线程数
     * @param cpu      是否进行cpu测试
     * @param piLength π精确位数
     * @param piLength π精确位数
     * @param ram      是否进行内存测试
     * @return
     */
    @GetMapping(value = "/test-pressure")
    @ApiOperation(value = "压力测试", notes = "压力测试")
    public ResultBean testPressure(int num, boolean cpu, int piLength, boolean ram) {
        try {
            long time = System.currentTimeMillis();
            //测试内存
            if (ram) {
                SysUser user;
                SysDepartment sysDepartment;
                List userList = new ArrayList();
                List deptList = new ArrayList();

                for (int i = 0; i < num; i++) {
                    // 生成部门计划
                    for (int j = 0; j < 10; j++) {
                        sysDepartment = new SysDepartment();
                        sysDepartment.setName("部门名称");
                        sysDepartment.setDepartmentCode("code");
                        sysDepartment.setDepartmentSort(j);
                        deptList.add(sysDepartment);
                    }

                    user = new SysUser();
                    user.setDepartmentList(deptList);
                    userList.add(user);
                }
            }

            // 测试cpu性能
            if (cpu) {
                for (int i = 0; i < num; i++) {
                    System.out.println(ComputePi.computePi(piLength));
                }
            }

            return ResultBean.success("查询成功 耗时：" + (System.currentTimeMillis() - time))
                    .setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    /**
     * 数据库操作测试
     *
     * @param num         操作数量
     * @param insert      是否进行新增测试
     * @param update      是否进行修改测试
     * @param batchUpdate 是否批量修改
     * @param delete      是否进行删除测试
     * @param batchDelete 是否批量删除
     * @return
     */
    @GetMapping(value = "/test-db")
    @ApiOperation(value = "数据库操作测试", notes = "数据库操作测试")
    public ResultBean testDBCRUD(int num, boolean mongo, boolean insert, boolean update, boolean batchUpdate, boolean delete, boolean batchDelete,long min,long max) {
        try {
            long time = System.currentTimeMillis();
            Pager page = new Pager();
            page.setCurrentPage(1);
            page.setPageSize(num);
            List list;
            SysTool sysTool;
            SysLogSystem sysLogSystem;
            int insertAffect = 0;
            int updateAffect = 0;
            long deleteAffect = 0;

            long t1 = System.currentTimeMillis();

            // 新增数据
            if (insert) {
                for (int i = 0; i < num; i++) {
                    t1 = System.currentTimeMillis();
                    if (!mongo) {
                        sysTool = new SysTool();
                        sysTool.setName("新增测试");
                        sysTool.setToolTypeId(1073140662133723136L);
                        sysTool.setToolIp("192.168.1.35");
                        sysTool.setToolPort(8888);
                        sysTool.setToolDescription("描述新增测试");

                        sysToolService.insertSysTool(sysTool);
                    } else {
                        sysLogSystem = new SysLogSystem();
                        sysLogSystem.setLogClass("新增测试class");
                        sysLogSystem.setLogMethod("新增测试method");
                        sysLogSystem.setLogArgs("新增测试参数");
                        sysLogSystem.setExecuteTime(0L);
                        sysLogSystem.setArgsCount(1);
                        sysLogSystem.setLogDetail("2333");
                        sysLogSystem.setLogLevel(ImppEnumUtil.LOG_LEVEL.DEBUG.getValue());
                        sysLogSystem.setLogModuleId(CommonEnumUtil.SOFT_TYPE.CORE.getValue());
                        sysLogSystem.setLogTitle("新增测试");

                        syslogSystemService.insertSysLogSystem(sysLogSystem);
                    }
                    LOGGER.info("插入耗时：" + (System.currentTimeMillis() - t1) + ",idx：" + i);
                    insertAffect++;
                }
            }

            if (update || delete) {
                // 查询批量修改或删除的数据
                if (mongo) {
                    list = syslogSystemService.querySysLogSystemByPager(null, page).getObjectList();
                } else {
                    list = sysToolService.findSysToolByTop(num);
                }

                // 是否进行修改测试，并判断进行批量或逐次修改
                if (!mongo && update && batchUpdate) {
                    Long[] ids = new Long[num];
                    for (int i = 0; i < num; i++) {
                        ids[i] = ((SysTool) list.get(i)).getId();
                    }
                    updateAffect = sysToolService.updateSysToolStatusByIds(ids, (int) (Math.random() * 1000));
                } else if (!mongo && update) {
                    for (int i = 0; i < num; i++) {
                        sysTool = (SysTool) list.get(i);
                        sysTool.setName("修改测试" + System.currentTimeMillis());
                        sysTool.setToolTypeId(1073140662133723136L);
                        sysTool.setToolIp("192.168.1.35");
                        sysTool.setToolPort(8888);
                        sysTool.setToolDescription("描述修改测试" + System.currentTimeMillis());

                        sysToolService.updateSysTool(sysTool);
                    }
                }

                // 是否进行删除测试，并判断进行批量或逐次删除
                if (delete && batchDelete) {
                    Long[] ids = new Long[num];
                    for (int i = 0; i < num; i++) {
                        if (mongo) {
                            ids[i] = ((SysLogSystem) list.get(i)).getId();
                        } else {
                            ids[i] = ((SysTool) list.get(i)).getId();
                        }
                    }
                    if (mongo) {
                        deleteAffect = syslogSystemService.deleteSysLogSystemByIds(ids);
                    } else {
                        deleteAffect = sysToolService.deleteSysToolByIds(ids);
                    }
                } else if (delete) {
                    for (int i = 0; i < num; i++) {
                        if (mongo) {
                            sysLogSystem = (SysLogSystem) list.get(i);
                            deleteAffect += syslogSystemService.deleteSysLogSystemById(sysLogSystem.getId());
                        } else {
                            sysTool = (SysTool) list.get(i);
                            deleteAffect += sysToolService.deleteSysToolById(sysTool.getId());
                        }
                    }
                }
            }

            return ResultBean.success("调用完成-耗时：" + (System.currentTimeMillis() - time) + ",新增数据量：" + insertAffect
                    + "，修改影响量" + updateAffect + "，删除影响量：" + deleteAffect)
                    .setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    /**
     * 数据库操作测试
     *
     * @param num 操作数量
     * @return
     */
    @GetMapping(value = "/data-insert")
    @ApiOperation(value = "数据库造数据", notes = "数据库造数据")
    public ResultBean dateInsert(int num, boolean mongo, int waitTime) {
        try {
            long time = System.currentTimeMillis();

            // 新增数据
            if (!mongo) {
                sysToolService.insertBatch(num, waitTime);
            } else {
                syslogSystemService.insertSysLogBatch(num, waitTime);
            }

            return ResultBean.success("调用完成-耗时：" + (System.currentTimeMillis() - time) + ",数据量：" + num)
                    .setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    /**
     * 缓存操作效率
     *
     * @param redisKey      缓存key
     * @param num           操作数量
     * @param batchPutCache 是否批量操作缓存
     * @param putCache      是否进行放入缓存操作
     * @param db            是否从数据库查询数据
     * @param mongo         是否从mongodb查询数据
     * @param cacheTime     缓存时间
     * @param deleteCache   是否进行缓存删除操作
     * @return
     */
    @GetMapping(value = "/test-db-redis")
    @ApiOperation(value = "缓存操作测试", notes = "数据库操作测试")
    public ResultBean testDBRedis(String redisKey, int num, boolean batchPutCache, boolean putCache, boolean db, boolean mongo, int cacheTime, boolean deleteCache) {
        try {
            long time = System.currentTimeMillis();
            List list = null;

            // 是否放入缓存
            if (putCache) {
                // 是否需要从数据库中查询
                if (db) {
                    Pager page = new Pager();
                    page.setCurrentPage(1);
                    page.setPageSize(num);

                    //是否对mongodb操作
                    if (mongo) {
                        list = sysToolService.findSysToolByTop(num);
                    } else {
                        list = syslogSystemService.querySysLogSystemByPager(null, page).getObjectList();
                    }
                } else {
                    // 缓存测试
                    list = new ArrayList();
                    SysTool sysTool;
                    for (int i = 0; i < num; i++) {
                        sysTool = new SysTool();
                        sysTool.setName("缓存对象");
                        sysTool.setToolTypeId(1073141149285355520L);
                        sysTool.setToolIp("192.168.1.1");
                        sysTool.setToolPort(8080);
                        sysTool.setToolStatus(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue());
                        sysTool.setToolConnType(ImppEnumUtil.TOOL_CONN_TYPE.USB.getValue());
                        sysTool.setToolDataType(ImppEnumUtil.TOOL_DATA_TYPE.STRING.getValue());
                        sysTool.setToolDescription("描述");

                        list.add(sysTool);
                    }
                }

                // 批量或是逐次放入缓存
                if (batchPutCache) {
                    redisRes.putList(redisKey, list, cacheTime);
                } else {
                    for (int i = 0; i < list.size(); i++) {
                        redisRes.putObject(redisKey + i, list.get(i), cacheTime);
                    }
                }
            }

            if (deleteCache && batchPutCache) {
                redisRes.deleteKey(redisKey);
            } else if (deleteCache) {
                for (int i = 0; i < num; i++) {
                    redisRes.deleteKey(redisKey + i);
                }
            }

            return ResultBean.success("调用完成-耗时：" + (System.currentTimeMillis() - time) + ",数据量：" + num)
                    .setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    /**
     * 数据库查询测试
     *
     * @param num       操作数据量
     * @param mongo     是否使用mongodb
     * @param needCache 是否使用缓存
     * @param cacheTime 缓存时间
     * @return
     */
    @GetMapping(value = "/test-db-query")
    @ApiOperation(value = "数据库查询测试", notes = "数据库查询测试")
    public ResultBean testDBQuery(int num, boolean mongo, boolean needCache, int cacheTime) {
        try {
            long time = System.currentTimeMillis();
            Pager page = new Pager();
            page.setCurrentPage(1);
            page.setPageSize(num);
            List list;

            // 是否放入缓存
            if (needCache) {
                // 是否使用mongodb
                if (mongo) {
                    list = redisRes.getList(SysLogSystem.class.getSimpleName() + num, 0, num);
                    if (list == null || list.size() == 0) {
                        list = syslogSystemService.querySysLogSystemByPager(null, page).getObjectList();
                        redisRes.putList(SysLogSystem.class.getSimpleName() + num, list, cacheTime);
                    }
                } else {
                    list = redisRes.getList(SysTool.class.getSimpleName() + num, 0, num);
                    if (list == null || list.size() == 0) {
                        list = sysToolService.findSysToolByTop(num);
                        redisRes.putList(SysTool.class.getSimpleName() + num, list, cacheTime);
                    }
                }
            } else {
                // 是否使用mongodb
                if (mongo) {
                    list = syslogSystemService.querySysLogSystemByPager(null, page).getObjectList();
                } else {
                    list = sysToolService.findSysToolByTop(num);
                }
            }

            return ResultBean.success("调用完成 耗时：" + (System.currentTimeMillis() - time) + ",数据量：" + list.size())
                    .setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    /**
     * 吞吐量测试
     *
     * @param num         对象数量
     * @param objectLevel 对象等级 1.单对象，2.大对象，3.复杂对象
     * @return
     */
    @GetMapping(value = "/test-throughput")
    @ApiOperation(value = "吞吐量测试", notes = "吞吐量测试")
    public ResultBean testThroughput(int num, int objectLevel) {
        try {
            long time = System.currentTimeMillis();
            List list = new ArrayList();

            SysTool sysTool;
            SessionUser sessionUser;
            SysUser sysUser;
            SysUserInfo sysUserInfo;
            SysDepartment sysDept;
            List<SysDepartment> deptList;

            for (int i = 0; i < num; i++) {
                switch (objectLevel) {
                    // 单对象
                    case 1:
                        sysTool = new SysTool();
                        sysTool.setName("单对象测试");
                        sysTool.setToolTypeId(1073141149285355520L);
                        sysTool.setToolIp("192.168.1.1");
                        sysTool.setToolPort(8080);
                        sysTool.setToolStatus(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue());
                        sysTool.setToolConnType(ImppEnumUtil.TOOL_CONN_TYPE.USB.getValue());
                        sysTool.setToolDataType(ImppEnumUtil.TOOL_DATA_TYPE.STRING.getValue());
                        sysTool.setToolDescription("描述");

                        list.add(sysTool);
                        break;
                    // 大对象
                    case 2:
                        deptList = new ArrayList<>();

                        for (int j = 0; j < 20; j++) {
                            sysDept = new SysDepartment();
                            sysDept.setName("部门名称");
                            sysDept.setDepartmentCode("部门code");
                            sysDept.setParentNameRdd("上级部门名称");

                            deptList.add(sysDept);
                        }

                        sysUser = new SysUser();
                        sysUser.setUserName("用户名");
                        sysUser.setUserStatus(CommonEnumUtil.USER_STATUS.ENABLE.getValue());
                        sysUser.setUserLoginPassword("123456");
                        sysUser.setDepartmentId(1L);
                        sysUser.setOrganizeId(1L);
                        sysUser.setDepartmentNameRdd("部门名称");
                        sysUser.setOrganizeNameRdd("组织名称");
                        sysUser.setUserLoginNum(1);
                        sysUser.setDepartmentList(deptList);

                        list.add(sysUser);
                        break;
                    // 复杂对象
                    case 3:
                        deptList = new ArrayList<>();
                        for (int j = 0; j < 20; j++) {
                            sysDept = new SysDepartment();
                            sysDept.setName("部门名称集合" + j);
                            sysDept.setDepartmentCode("部门集合code" + j);
                            sysDept.setParentNameRdd("集合" + j);
                            deptList.add(sysDept);

                        }
                        sysDept = new SysDepartment();
                        sysDept.setName("部门名称");
                        sysDept.setDepartmentCode("部门code");
                        sysDept.setParentNameRdd("上级部门名称");

                        sysDept.setChildList(deptList);

                        sysUser = new SysUser();
                        sysUser.setUserName("用户名");
                        sysUser.setUserStatus(CommonEnumUtil.USER_STATUS.ENABLE.getValue());
                        sysUser.setUserLoginPassword("123456");
                        sysUser.setDepartmentId(1L);
                        sysUser.setOrganizeId(1L);
                        sysUser.setDepartmentNameRdd("部门名称");
                        sysUser.setOrganizeNameRdd("组织名称");
                        sysUser.setUserLoginNum(1);
                        sysUser.setDepartment(sysDept);
                        sysUser.setDepartmentList(deptList);

                        sysUserInfo = new SysUserInfo();
                        sysUserInfo.setName("yonghuming");
                        sysUserInfo.setOrganizeId(1L);
                        sysUserInfo.setPositionId(1L);
                        sysUserInfo.setDepartmentNameRdd("部门名称");
                        sysUserInfo.setOrganizeNameRdd("组织名称");

                        sessionUser = new SessionUser();
                        sessionUser.setUserName("用户名");
                        sessionUser.setLanguageCode("zh/CN");
                        sessionUser.setUserCode("10086");
                        sessionUser.setUserType("测试用户");
                        sessionUser.setUserId(1L);
                        sessionUser.setUser(sysUser);
                        sessionUser.setUserInfo(sysUserInfo);

                        list.add(sessionUser);
                        break;
                }
            }

            return ResultBean.success("调用完成-耗时：" + (System.currentTimeMillis() - time) + ",数量：" + list.size())
                    .setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultList(list);
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }


    /**
     * 可靠性测试
     *
     * @param needChangeHealth 是否需要修改健康状态
     * @param serverHealth     设置微服务健康状态
     * @param needSleep        是否需要线程睡眠
     * @param sleepTime        睡眠时间ms
     * @return
     */
    @GetMapping(value = "/test-network")
    @ApiOperation(value = "网络测试", notes = "网络测试")
    public ResultBean testNetwork(boolean needChangeHealth, boolean serverHealth, boolean needSleep, int sleepTime) {
        try {
            long time = System.currentTimeMillis();

            if (needChangeHealth) {
                healthCheck.setHealth(serverHealth);
            }

            if (needSleep) {
                Thread.sleep(sleepTime);
            }

            return ResultBean.success("调用完成-耗时：" + (System.currentTimeMillis() - time))
                    .setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    /**
     * 多表查询
     *
     * @param num       查询数量
     * @param needCache 是否使用缓存
     * @param cacheTime 缓存时间
     * @return
     */
    @GetMapping(value = "/test-complex-query")
    @ApiOperation(value = "多表查询", notes = "多表查询")
    public ResultBean testComplexQuery(int num, boolean needCache, int cacheTime) {
        try {
            long time = System.currentTimeMillis();
            Pager page = new Pager();
            page.setCurrentPage(1);
            page.setPageSize(num);
            List list;

            if (needCache) {
                list = redisRes.getList(Object.class.getSimpleName() + num, 0, num);
                if (list == null || list.size() == 0) {
                    list = testService.queryToolAndToolType(page);
                    redisRes.putList(SysTool.class.getSimpleName() + num, list, cacheTime);
                }
            } else {
                list = testService.queryToolAndToolType(page);
            }

            return ResultBean.success("调用完成-耗时：" + (System.currentTimeMillis() - time) + ",数量：" + list.size())
                    .setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/test-gc")
    @ApiOperation(value = "垃圾回收", notes = "垃圾回收")
    public ResultBean gc() {
        try {
            System.gc();
            return ResultBean.success("调用完成").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/test-user-detail-model")
    @ApiOperation(value = "用户数据", notes = "用户数据")
    public void testUserDetailModel() {
        List<SysRole> roleList = roleService.findSysRoleAll();
        List<SysPosition> positionList = positionService.listSysPosition();
        List<SysDepartment> departmentList = departmentService.listSysDepartment();
        for (int l = 0; l < 100; l++) {

            UserDetailModel model = new UserDetailModel();
            List<String> roleIds = new ArrayList<>();
            List<String> positionIds = new ArrayList<>();
            List<String> departmentIds = new ArrayList<>();

            for (int i = 0; i < new Random().nextInt(10); i++) {
                SysRole role = roleList.get(new Random().nextInt(roleList.size() - 1));
                roleIds.add(role.getId().toString());
            }

            for (int i = 0; i < new Random().nextInt(10); i++) {
                SysPosition position = positionList.get(new Random().nextInt(positionList.size() - 1));
                positionIds.add(position.getId().toString());
            }

            for (int i = 0; i < new Random().nextInt(10); i++) {
                SysDepartment department = departmentList.get(new Random().nextInt(departmentList.size() - 1));
                departmentIds.add(department.getId().toString());
            }


            model.setUserInfoId(System.currentTimeMillis() + snowflakeIdMaker.nextId() + "");
            model.setUserId(System.currentTimeMillis() + snowflakeIdMaker.nextId() + "");
            model.setInfoName(RandomStringUtils.random(5, TEXT));
            model.setUserPhone(RandomStringUtils.random(11, false, true));
            model.setUserEmail(RandomStringUtils.random(15, true, true));
            model.setInfoEmpNo(RandomStringUtils.random(10, true, true));
            model.setUserLoginName(RandomStringUtils.random(20, true, true));
            model.setUserLoginPassword("123456");
            model.setInfoPositionId(positionList.get(0).getId().toString());
            model.setInfoDepartmentId(departmentList.get(0).getId().toString());
            model.setUserDepartmentId(departmentList.get(0).getId().toString());
            model.setUserRoleIdList(roleIds);
            model.setUserDepartmentIdList(departmentIds);
            model.setInfoPositionIdList(positionIds);
            model.setInfoDepartmentIdList(departmentIds);


            try {
                SysUser user = model.getSysUser();
                SysUserInfo info = model.getSysUserInfo();

                init(user);
                init(info);

                if (StringUtils.isBlank(info.getUserJoinDate())) {
                    info.setUserJoinDate(TimeTool.getToday());
                }

                info.setUserInfoStatus(CommonEnumUtil.USER_INFO_STATUS.INCUMBENT.getValue());
                info.setUserLoginNum(0);
                info.setIsValid(CommonEnumUtil.IS_VAILD.VAILD.getValue());

                user.setUserType(CommonEnumUtil.USER_TYPE.USER.getValue());
                user.setUserStatus(CommonEnumUtil.USER_STATUS.ENABLE.getValue());
                user.setIsValid(CommonEnumUtil.IS_VAILD.VAILD.getValue());
                user.setUserLoginNum(0);

                SysDepartment infoDepartment = personnelService.getSysDepartmentById(Long.parseLong(model.getInfoDepartmentId()));
                if (infoDepartment == null) {
                    ValidatorBean.checkNotNull(infoDepartment, "用户主部门不存在");
                }
                SysOrganize infoOrganize = personnelService.getSysOrganizeById(infoDepartment.getOrganizeId());
                SysPosition position = personnelService.getSysPositionById(Long.parseLong(model.getInfoPositionId()));
                if (infoDepartment == null) {
                    ValidatorBean.checkNotNull(position, "用户主岗位存在");
                }

                SysDepartment userDepartment = personnelService.getSysDepartmentById(Long.parseLong(model.getUserDepartmentId()));
                if (userDepartment == null) {
                    ValidatorBean.checkNotNull(userDepartment, "账号主部门不存在");
                }
                SysOrganize userOrganize = personnelService.getSysOrganizeById(userDepartment.getOrganizeId());

                info.setDepartmentId(infoDepartment.getId());
                info.setDepartmentNameRdd(infoDepartment.getName());
                info.setOrganizeId(infoOrganize.getId());
                info.setOrganizeNameRdd(infoOrganize.getName());
                info.setOrganizeCode(infoOrganize.getOrganizeCode());
                info.setPositionId(position.getId());
                info.setPositionNameRdd(position.getName());
                personnelService.saveSysUserInfo(info);

                user.setDepartmentId(userDepartment.getId());
                user.setDepartmentNameRdd(userDepartment.getName());
                user.setOrganizeId(userOrganize.getId());
                user.setOrganizeNameRdd(userOrganize.getName());
                user.setOrganizeCode(userOrganize.getOrganizeCode());
                user.setUserInfoId(info.getId());
                personnelController.refreshSysUserPassword(user);
                personnelService.saveSysUser(user);

                info.setUserId(user.getId());
                personnelService.saveSysUserInfo(info);

                // 关系 刷新
                personnelController.refreshRef(user, info, model);

            } catch (ImppBusiException busExcep) {
            } catch (Exception e) {
            }
        }
    }

    @GetMapping(value = "/test-user-detail")
    @ApiOperation(value = "用户数据", notes = "用户数据")
    public void testUserInfo() throws Exception {
        String PATH = new String(File.separator + "C:\\test\\user");
        List<SysRole> roleList = roleService.findSysRoleAll();
        List<SysPosition> positionList = positionService.listSysPosition();
        List<SysDepartment> departmentList = departmentService.listSysDepartment();

        List<SysUser> userList = new ArrayList<>();
        List<SysUserInfo> userInfoList = new ArrayList<>();
        List<SysRefUserRole> refUserRoleList = new ArrayList<>();
        List<SysRefUserDepartment> refUserDepartmentList = new ArrayList<>();
        List<SysRefUserInfoDepartment> refUserInfoDepartmentList = new ArrayList<>();
        List<SysRefUserPosition> refUserPositionList = new ArrayList<>();

        List<String> refUserRoleNameList ;
        List<String> refUserPositionNameList ;
        List<String> refUserDepartmentNameList ;

        SysUser user;
        SysUserInfo userInfo;
        SysRefUserRole refUserRole;
        SysRefUserDepartment refUserDepartment;
        SysRefUserInfoDepartment refUserInfoDepartment;
        SysRefUserPosition refUserPosition;
        SysDepartment department = null;
        SysPosition position = null;

        for (int i = 0; i < 1000000; i++) {
            System.out.println("造数据 ->" + i);
            user = new SysUser();
            userInfo = new SysUserInfo();
            refUserRoleNameList = new ArrayList<>();
            refUserPositionNameList = new ArrayList<>();
            refUserDepartmentNameList = new ArrayList<>();

            init(user);
            init(userInfo);

            for (int j = 0; j < 2; j++) {
                SysRole role = roleList.get(new Random().nextInt(roleList.size() - 1));
                if(role != null){
                    refUserRole = new SysRefUserRole();
                    init(refUserRole);

                    refUserRole.setRoleId(role.getId());
                    refUserRole.setRoleNameRdd(role.getName());
                    refUserRole.setUserId(user.getId());
                    refUserRole.setUserNameRdd(user.getUserName());

                    refUserRoleNameList.add(role.getName());
                    refUserRoleList.add(refUserRole);
                }
            }

            for (int j = 0; j < 3; j++) {
                position = positionList.get(new Random().nextInt(positionList.size() - 1));
                if(position != null){
                    refUserPosition = new SysRefUserPosition();
                    init(refUserPosition);

                    refUserPosition.setUserId(userInfo.getId());
                    refUserPosition.setUserNameRdd(userInfo.getName());
                    refUserPosition.setPositionId(position.getId());
                    refUserPosition.setPositionNameRdd(position.getName());

                    refUserPositionNameList.add(position.getName());

                    refUserPositionList.add(refUserPosition);
                }
            }

            for (int j = 0; j < 3; j++) {
                department = departmentList.get(new Random().nextInt(departmentList.size() - 1));

                if(department != null){
                    refUserDepartment= new SysRefUserDepartment();
                    refUserInfoDepartment = new SysRefUserInfoDepartment();

                    init(refUserDepartment);
                    init(refUserInfoDepartment);

                    refUserDepartment.setDepartmentId(department.getId());
                    refUserDepartment.setDepartmentNameRdd(department.getName());
                    refUserDepartment.setOrganizeNameRdd(department.getOrganizeNameRdd());
                    refUserDepartment.setOrganizeId(department.getOrganizeId());
                    refUserDepartment.setOrganizeCode(department.getOrganizeCode());
                    refUserDepartment.setUserId(user.getId());
                    refUserDepartment.setUserNameRdd(user.getUserName());

                    refUserInfoDepartment.setDepartmentId(department.getId());
                    refUserInfoDepartment.setDepartmentNameRdd(department.getName());
                    refUserInfoDepartment.setOrganizeNameRdd(department.getOrganizeNameRdd());
                    refUserInfoDepartment.setOrganizeId(department.getOrganizeId());
                    refUserInfoDepartment.setOrganizeCode(department.getOrganizeCode());
                    refUserInfoDepartment.setUserId(user.getId());
                    refUserInfoDepartment.setUserNameRdd(user.getUserName());

                    refUserDepartmentNameList.add(department.getName());

                    refUserDepartmentList.add(refUserDepartment);
                    refUserInfoDepartmentList.add(refUserInfoDepartment);
                }
            }

            userInfo.setDepartmentNamesRdd(StringUtils.join(refUserDepartmentNameList));
            userInfo.setDepartmentId(department.getId());
            userInfo.setDepartmentNameRdd(department.getName());
            userInfo.setOrganizeId(department.getOrganizeId());
            userInfo.setOrganizeNameRdd(department.getOrganizeNameRdd());
            userInfo.setOrganizeCode(department.getOrganizeCode());
            userInfo.setPositionId(position.getId());
            userInfo.setPositionNameRdd(position.getName());
            userInfo.setPositionNamesRdd(StringUtils.join(refUserPositionNameList,","));
            userInfo.setName(RandomStringUtils.random(5, TEXT));
            userInfo.setUserEmpNo(RandomStringUtils.random(10, true, true));
            userInfo.setUserInfoStatus(CommonEnumUtil.USER_INFO_STATUS.INCUMBENT.getValue());
            userInfo.setUserLoginNum(0);
            userInfo.setIsValid(CommonEnumUtil.IS_VAILD.VAILD.getValue());
            userInfo.setUserId(user.getId());

            user.setUserType(CommonEnumUtil.USER_TYPE.USER.getValue());
            user.setUserStatus(CommonEnumUtil.USER_STATUS.ENABLE.getValue());
            user.setIsValid(CommonEnumUtil.IS_VAILD.VAILD.getValue());
            user.setUserLoginNum(0);
            user.setDepartmentNamesRdd(StringUtils.join(refUserDepartmentNameList,","));
            user.setDepartmentId(department.getId());
            user.setDepartmentNameRdd(department.getName());
            user.setUserPhone(RandomStringUtils.random(11, false, true));
            user.setUserEmail(RandomStringUtils.random(15, true, true));
            user.setUserLoginName(RandomStringUtils.random(20, true, true));
            user.setUserLoginPassword("123456");
            user.setUserEmpNo(userInfo.getUserEmpNo());

            userList.add(user);
            userInfoList.add(userInfo);
        }

        System.out.println("写文件  sys_ref_user_position->" );
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    FileWriter writer = new FileWriter(PATH+"/SysRefUserPosition.sql", true);
                    for (SysRefUserPosition ref : refUserPositionList) {
                        String txt = new String("INSERT INTO sys_ref_user_position (id, create_date, create_user, is_deleted," +
                                " is_valid, modify_date, modify_user, position_id, position_name_rdd, user_id, user_name_rdd) VALUES (" +
                                "  "+ref.getId()+", '"+ref.getCreateDatetime()+"', '"+ref.getCreateUser()+"', "+ref.getIsDeleted()+"," +
                                " "+ref.getIsValid()+", '"+ref.getModifyUser()+"', '"+ref.getModifyDatetime()+"', "+ref.getPositionId()+"," +
                                " '"+ref.getPositionNameRdd()+"', "+ref.getUserId()+", '"+ref.getUserNameRdd()+"');");
                        fileWriter(writer,txt);
                    }
                    writer.close();
                }catch (Exception e){
                }
            }
        }).start();

        System.out.println("写文件  sys_ref_user_role->" );
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    FileWriter writer = new FileWriter(PATH+"/SysRefUserRole.sql", true);
                    for (SysRefUserRole ref : refUserRoleList) {
                        String txt = new String("INSERT INTO sys_ref_user_role (id, create_date, create_user, is_deleted," +
                                " is_valid, modify_date, modify_user, role_id, role_name_rdd, user_id, user_name_rdd) VALUES (" +
                                " "+ref.getId()+", '"+ref.getCreateDatetime()+"', '"+ref.getCreateUser()+"', "+ref.getIsDeleted()+"," +
                                " "+ref.getIsValid()+", '"+ref.getModifyDatetime()+"', '"+ref.getModifyUser()+"', "+ref.getRoleId()+"," +
                                " '"+ref.getRoleNameRdd()+"', "+ref.getUserId()+", '"+ref.getUserNameRdd()+"');");
                        fileWriter(writer,txt);
                    }
                    writer.close();
                }catch (Exception e){
                }
            }
        }).start();

        System.out.println("写文件  sys_ref_user_department->" );
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    FileWriter writer = new FileWriter(PATH+"/SysRefUserDepartment.sql", true);
                    for (SysRefUserDepartment ref : refUserDepartmentList) {
                        String txt = new String("INSERT INTO sys_ref_user_department (id, create_date, create_user, is_deleted," +
                                " is_valid, modify_date, modify_user, department_id, department_name_rdd, organize_id, organize_name_rdd, user_id, user_name) VALUES (" +
                                " "+ref.getId()+", '"+ref.getCreateDatetime()+"', '"+ref.getCreateUser()+"', "+ref.getIsDeleted()+"," +
                                " "+ref.getIsValid()+", '"+ref.getModifyDatetime()+"', '"+ref.getModifyUser()+"', "+ref.getDepartmentId()+"," +
                                " '"+ref.getDepartmentNameRdd()+"', "+ref.getOrganizeId()+", '"+ref.getOrganizeNameRdd()+"'," +
                                " "+ref.getUserId()+", '"+ref.getUserNameRdd()+"');");
                        fileWriter(writer,txt);
                    }
                    writer.close();
                }catch (Exception e){
                }
            }
        }).start();

        System.out.println("写文件  sys_ref_user_info_department->" );
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    FileWriter writer = new FileWriter(PATH+"/SysRefUserInfoDepartment.sql", true);
                    for (SysRefUserInfoDepartment ref : refUserInfoDepartmentList) {
                        String txt = new String("INSERT INTO sys_ref_user_info_department (id, create_date, create_user, is_deleted," +
                                " is_valid, modify_date, modify_user, department_id, department_name_rdd, organize_id, organize_name_rdd, user_id, user_name) VALUES (" +
                                " "+ref.getId()+", '"+ref.getCreateDatetime()+"', '"+ref.getCreateUser()+"', "+ref.getIsDeleted()+"," +
                                " "+ref.getIsValid()+", '"+ref.getModifyDatetime()+"', '"+ref.getModifyUser()+"', "+ref.getDepartmentId()+"," +
                                " '"+ref.getDepartmentNameRdd()+"', "+ref.getOrganizeId()+", '"+ref.getOrganizeNameRdd()+"'," +
                                " "+ref.getUserId()+", '"+ref.getUserNameRdd()+"');");
                        fileWriter(writer,txt);
                    }
                    writer.close();
                }catch (Exception e){
                }
            }
        }).start();

        System.out.println("写文件  sys_user->" );
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    FileWriter writer = new FileWriter(PATH+"/SysUser.sql", true);
                    for (SysUser su : userList) {
                        String txt = new String("INSERT INTO sys_user (id, create_date, create_user, is_deleted, is_valid," +
                                " modify_date, modify_user, organize_code, department_id, department_name_rdd, department_names_rdd, language_code," +
                                " organize_id, organize_name_rdd, organize_names_rdd, role_names_rdd, user_email, user_emp_no, user_info_id," +
                                " user_login_last_date_time, user_login_name, user_login_num, user_login_password, user_name_rdd," +
                                " user_phone, user_status, user_type) VALUES (" +
                                " "+su.getId()+", '"+su.getCreateDatetime()+"', '"+su.getCreateUser()+"', "+su.getIsDeleted()+", "+su.getIsValid()+"," +
                                " '"+su.getModifyDatetime()+"', '"+su.getModifyUser()+"', '"+su.getOrganizeCode()+"', " +
                                " "+su.getDepartmentId()+", '"+su.getDepartmentNameRdd()+"', '"+su.getDepartmentNamesRdd()+"', ''," +
                                " "+su.getOrganizeId()+", '"+su.getOrganizeNameRdd()+"', null, '"+su.getRoleNamesRdd()+"', '"+su.getUserEmail()+"'," +
                                " '"+su.getUserEmpNo()+"', "+su.getUserInfoId()+", null, '"+su.getUserLoginName()+"', 0, '2637a5c30af69a7bad877fdb65fbd78b'," +
                                " '"+su.getUserName()+"', '"+su.getUserPhone()+"', 1, 1);");
                        fileWriter(writer,txt);
                    }
                    writer.close();
                }catch (Exception e){
                }
            }
        }).start();

        System.out.println("写文件  sys_user_info->" );
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    FileWriter writer = new FileWriter(PATH+"/SysUserInfo.sql", true);
                    for (SysUserInfo ui : userInfoList) {
                        String txt = new String("INSERT INTO sys_user_info (id, create_date, create_user, is_deleted, is_valid," +
                                " modify_date, modify_user, organize_code, department_id, department_name_rdd, department_names_rdd, name," +
                                " organize_id, organize_name_rdd, position_id, position_name_rdd, position_names_rdd, user_emp_no, user_id," +
                                " user_info_status, user_join_date, user_login_last_date_time, user_login_num) VALUES (" +
                                " "+ui.getId()+", '"+ui.getCreateDatetime()+"', '"+ui.getCreateUser()+"', "+ui.getIsDeleted()+", "+ui.getIsValid()+"," +
                                " '"+ui.getModifyDatetime()+"', '"+ui.getModifyUser()+"', '"+ui.getOrganizeCode()+"'," +
                                " "+ui.getDepartmentId()+", '"+ui.getDepartmentNameRdd()+"', '"+ui.getDepartmentNamesRdd()+"'," +
                                " '"+ui.getName()+"', "+ui.getOrganizeId()+", '"+ui.getOrganizeNameRdd()+"'," +
                                " "+ui.getPositionId()+", '"+ui.getPositionNameRdd()+"', '"+ui.getPositionNamesRdd()+"'," +
                                " '"+ui.getUserEmpNo()+"', "+ui.getUserId()+", 1, '2019-02-26', null , 0);");
                        fileWriter(writer,txt);
                    }
                    writer.close();
                }catch (Exception e){
                }
            }
        }).start();
    }

    public void init(BaseBean bean)throws Exception{
        bean.setId(System.currentTimeMillis() + snowflakeIdMaker.nextId() + UUID.randomUUID().hashCode() + new Random().nextInt(10000000));
        bean.setIsValid(CommonEnumUtil.IS_VAILD.VAILD.getValue());
        bean.setIsDeleted(CommonEnumUtil.IS_DEAL.NO.getValue());
        bean.setCreateUser("系统管理员-测试");
        bean.setModifyUser("系统管理员-测试");
        bean.setCreateDatetime(DateFormatUtils.format(System.currentTimeMillis(),"yyyy-MM-dd HH:mm:ss"));
        bean.setModifyDatetime(DateFormatUtils.format(System.currentTimeMillis(),"yyyy-MM-dd HH:mm:ss"));
    }

    public static void fileWriter(FileWriter writer, String content) {
        try {
            writer.write(content+"\r\n");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping(value = "/make-sql")
    @ApiOperation(value = "生成sql脚本", notes = "生成sql脚本")
    public void MakeSql(String path,int page,int pageSize){
        try {
            for (int i = 0; i < page; i++) {
                printSql(path,pageSize, i);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static final String DATA_TEXT = "党的十八大提出，倡导富强、民主、文明、和谐，倡导自由、平等、公正、法治，倡导爱国、敬业、诚信、友善，积极培育和践行社会主义核心价值观。富强、民主、文明、和谐是国家层面的价值目标，自由、平等、公正、法治是社会层面的价值取向，爱国、敬业、诚信、友善是公民个人层面的价值准则，这24个字是社会主义核心价值观的基本内容。";

    /**
     *
     * @param path
     * @param num
     * @param index
     * @throws IOException
     */
    public static void printSql(String path, int num, int index) throws IOException {

        File dir = new File(path+File.separator+"tool"+File.separator+"temp" + (index / 10));
        if (!dir.exists()) {
            System.out.println(dir.mkdirs());
        }
        File f = new File(path+File.separator+"tool"+File.separator+"temp" + (index / 10) + File.separator+"insert" + index + ".sql");
        FileWriter fw = new FileWriter(f);
        BufferedWriter out = new BufferedWriter(fw);
        try {

            SysTool sysTool;
            StringBuffer sb;
            SnowflakeIdMaker snf = new SnowflakeIdMaker();
            for (int i = 0; i < num; i++) {
                sb = new StringBuffer();
                sb.append("insert into sys_tool (id,name,tool_type_name_rdd,tool_type_id,tool_ip,tool_port,tool_description) values ");
                sysTool = new SysTool();
                sysTool.setId(snf.nextId() + System.currentTimeMillis());
                sysTool.setName(RandomStringUtils.random(10, DATA_TEXT));
                sysTool.setToolTypeNameRdd(RandomStringUtils.random(10, DATA_TEXT));
                sysTool.setToolTypeId(System.currentTimeMillis());
                sysTool.setToolIp(RandomStringUtils.random(10, DATA_TEXT));
                sysTool.setToolPort((int) (Math.random() * i));
                sysTool.setToolDescription(RandomStringUtils.random(10, DATA_TEXT));
                sysTool.setCreateDatetime(TimeTool.getNowTime(true));
                sysTool.setModifyDatetime(TimeTool.getNowTime(true));

                sb.append("(" + sysTool.getId() + ",'" + sysTool.getName() + "','" + sysTool.getToolTypeNameRdd() + "'," + sysTool.getToolTypeId() + ",'"
                        + sysTool.getToolIp() + "'," + sysTool.getToolPort() + ",'" + sysTool.getToolDescription() + "');");
                out.write(sb.toString());
            }

        } finally {
            out.close();
        }
    }
}
class TestThread implements Runnable {

    private Thread t;
    private int piLength = 0;

    public TestThread (int piLength){
        this.piLength = piLength;
    }

    @Override
    public void run() {
        ComputePi.computePi(piLength);
    }

    public void start () {
        if (t == null) {
            t = new Thread (this);
            t.start ();
        }
    }
}