kimi
2020-05-27 c007f0ca1785db093d48f4846cda82fe8e955765
src/main/java/com/highdatas/mdm/controller/DispenseController.java
@@ -1,35 +1,43 @@
package com.highdatas.mdm.controller;
import com.highdatas.mdm.entity.TUser;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.highdatas.mdm.entity.*;
import com.highdatas.mdm.entity.Character;
import com.highdatas.mdm.pojo.CodeMsg;
import com.highdatas.mdm.pojo.DispenseField;
import com.highdatas.mdm.pojo.Result;
import com.highdatas.mdm.service.DispenseService;
import com.highdatas.mdm.service.MasterDataService;
import com.highdatas.mdm.pojo.SubscribeEntity;
import com.highdatas.mdm.service.*;
import com.highdatas.mdm.util.Constant;
import com.highdatas.mdm.util.DbUtils;
import com.highdatas.mdm.util.RedisClient;
import com.highdatas.mdm.util.pool.MqEntity;
import com.highdatas.mdm.util.pool.MqMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @description 分发接口
 * @author kimi
 * @since 2019-12-31
 */
@RestController
@RequestMapping("/dispense")
@RequestMapping("/subscribe")
public class DispenseController {
    @Autowired
    DispenseService dispenseService;
@@ -37,28 +45,903 @@
    RedisClient redisClient;
    @Autowired
    MasterDataService masterDataService;
    @Autowired
    IMasterAuthorService masterAuthorService;
    @Autowired
    IMaintainFieldService maintainFieldService;
    @Autowired
    IMaintainService maintainService;
    @Autowired
    IMenuMappingService menuMappingService;
    @Autowired
    IMasterAuthorSubscribeService subscribeService;
    @Autowired
    ISysMenuService menuService;
    @Autowired
    ISysViewService viewService;
    @Autowired
    IMasterAuthorSubscribeService masterAuthorSubscribeService;
    @Autowired
    IMasterAuthorUnactiveService masterAuthorUnactiveService;
    @Autowired
    ISysDispenseLogsService dispenseLogsService;
    @Autowired
    ISysFieldService fieldService;
    /**
     *
     * @description:  页面调用分发接口
     * @param userId 分发用户
     * @param dataId 分发的dataId
     * @param type 分发类型, 视图还是主题
     * @param increment 增量/全量
     * @return: 是否添加到队列
     *
     */
    @RequestMapping(value = "/dispense/surface", method = RequestMethod.GET)
    public Result surface(@RequestParam String userId, @RequestParam String type, @RequestParam String dataId, HttpServletRequest request, HttpServletResponse response) {
        //类型为 主题的时候需要传分发哪个版本的数据
        String versionId = request.getParameter("versionId");
        //添加到分发队列
        return addPassiveMq(userId, type, dataId, versionId, request, "surface");
    }
    /**
     *
     * @description:  获取当前分发任务数据总条数,供外部系统调用
     * @param reqObj 参数对象
     *               token 通过token获取user信息
     *               type 数据类型 视图,主题
     *               dataId 分发的dataId
     *               versionId 主题的版本id
     *               increment 增量/全量
     * @return: 记录数
     *
     */
    @RequestMapping(value = "/api/count", method = RequestMethod.POST)
    public Result count(@RequestBody JSONObject reqObj) {
        String token = reqObj.getString("token");
        String type = reqObj.getString("type");
        String dataId = reqObj.getString("dataId");
        String versionId = reqObj.getString("versionId");
        String incrementStr = reqObj.getString("increment");
        //校验必传字段
        if (StringUtils.isEmpty(token) || StringUtils.isEmpty(type) || StringUtils.isEmpty(dataId)) {
            return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
        }
        //获取用户信息
        String userId = redisClient.getRedisVal(token);
        if (StringUtils.isEmpty(userId)) {
            return Result.error(CodeMsg.ERROR_FIND_TOKEN);
        }
        //转换increment类型
        boolean increment = true;
        if (!StringUtils.isEmpty(incrementStr)) {
            increment = Boolean.valueOf(incrementStr);
        }
        if (type.equalsIgnoreCase(Constant.Master)) {
            //主题 需校验版本字段
            if (StringUtils.isEmpty(versionId)) {
                return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
            }
            //获取主题版本信息
            Maintain maintain = maintainService.selectById(versionId);
            if (maintain == null) {
                return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
            }
            //获取主题信息
            SysMenu sysMenu = menuService.selectById(dataId);
            if (sysMenu == null) {
                return Result.error(CodeMsg.SELECT_ERROR_NOTFOUND);
            }
            //校验是否已经注册
            int subscribeCnt = subscribeService.selectCount(new EntityWrapper<MasterAuthorSubscribe>().eq("menu_id", dataId).eq("user_id", userId));
            if (subscribeCnt < 1) {
                return Result.error(CodeMsg.SUBSCRIBE_UN_ERROR);
            }
            //校验是否激活
            int i = masterAuthorUnactiveService.selectCount(new EntityWrapper<MasterAuthorUnactive>().eq("maintain_id", versionId).eq("user_id", userId));
            if (i > 0) {
                return Result.error(CodeMsg.Active_UN_ERROR);
            }
            //获取权限信息
            MasterAuthor masterAuthor = new MasterAuthor().setTableName(maintain.getTableName());
            TUser user = new TUser().setUserId(userId);
            //获取理论上的页码数,记录信息
            com.highdatas.mdm.pojo.Page initPageInfo = DbUtils.masterAuthorService.getInitPageInfo(masterAuthor, maintain, user, increment);
            if (initPageInfo != null) {
                return Result.success(initPageInfo.getRecordCount());
            }
            return Result.success(0);
        } else if (type.equalsIgnoreCase(Constant.View)) {
            //获取视图信息
            SysView sysView = viewService.selectById(dataId);
            if (sysView == null) {
                return Result.error(CodeMsg.SELECT_ERROR_NOTFOUND);
            }
            //校验是否激活
            Boolean active = sysView.getActive();
            if (!active) {
                return Result.error(CodeMsg.Active_UN_ERROR);
            }
            //获取视图记录数
            long viewCount = viewService.getViewCount(sysView);
            return Result.success(viewCount);
        } else {
            return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
        }
    }
    /**
     *
     * @description:  获取当前分发任务数据数据,供外部系统调用
     * @param reqObj 参数对象
     *               token 通过token获取user信息
     *               beginNo 起始条数
     *               endNo 结束条数
     *               type 数据类型 视图,主题
     *               dataId 分发的dataId
     *               versionId 主题的版本id
     *               increment 增量/全量
     * @return: 数据记录
     *
     */
    @RequestMapping(value = "/api/data", method = RequestMethod.POST)
    public Result data(@RequestBody JSONObject reqObj) {
        //创建分发日志
        SysDispenseLogs logs = new SysDispenseLogs().setId(DbUtils.getUUID()).setCreateTime(new Date());
        //设置日志类型
        logs.setTouchType("rest");
        logs.insert();
        String token = reqObj.getString("token");
        String type = reqObj.getString("type");
        String dataId = reqObj.getString("dataId");
        String versionId = reqObj.getString("versionId");
        String incrementStr = reqObj.getString("increment");
        Integer beginNo = reqObj.getInteger("beginNo");
        Integer endNo = reqObj.getInteger("endNo");
        logs.setTopicId(type).setTagId(dataId).setDataType(type);
        //beginNo endNo字段 是否合理
        if (beginNo == null || endNo == null) {
            logs.setErrorInfo("beginNo or endNo not exists").setStatus("false").updateById();
            return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
        } else if (endNo < beginNo) {
            logs.setErrorInfo("beginNo > endNo ").setStatus("false").updateById();
            return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
        }
        if (beginNo < 0 || endNo < 0) {
            logs.setErrorInfo("beginNo or endNo  < 0").setStatus("false").updateById();
            return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
        }
        //校验必传字段
        if (StringUtils.isEmpty(token) || StringUtils.isEmpty(type) || StringUtils.isEmpty(dataId)) {
            logs.setErrorInfo("token or type or dataId not found").setStatus("false").updateById();
            return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
        }
        //获取用户信息
        String userId = redisClient.getRedisVal(token);
        if (StringUtils.isEmpty(userId)) {
            logs.setErrorInfo(CodeMsg.ERROR_FIND_TOKEN.getMsg()).setStatus("false").updateById();
            return Result.error(CodeMsg.ERROR_FIND_TOKEN);
        }
        TUser userById = DbUtils.getUserById(userId);
        //更新日志信息
        logs.setUserName(userById.getUserName());
        logs.setUserId(userId).updateById();
        boolean increment = true;
        if (!StringUtils.isEmpty(incrementStr)) {
            increment = Boolean.valueOf(incrementStr);
        }
        com.highdatas.mdm.pojo.Page initPageInfo = null;
        if (type.equalsIgnoreCase(Constant.Master)) {
            //校验版本字段
            if (StringUtils.isEmpty(versionId)) {
                logs.setErrorInfo("versionId not exists").setStatus("false").updateById();
                return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
            }
            //获取版本信息
            Maintain maintain = maintainService.selectById(versionId);
            if (maintain == null) {
                return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
            }
            //更新日志信息
            logs.setMaintainId(maintain.getId()).setVersion(maintain.getVersion());
            logs.updateById();
            //获取主题信息
            SysMenu sysMenu = menuService.selectById(dataId);
            if (sysMenu == null) {
                return Result.error(CodeMsg.SELECT_ERROR_NOTFOUND);
            }
            //更新主题信息
            logs.setName(sysMenu.getName());
            logs.updateById();
            //检验是否已注册
            int subscribeCnt = subscribeService.selectCount(new EntityWrapper<MasterAuthorSubscribe>().eq("menu_id", dataId).eq("user_id", userId));
            if (subscribeCnt < 1) {
                logs.setErrorInfo(CodeMsg.SUBSCRIBE_UN_ERROR.getMsg()).updateById();
                return Result.error(CodeMsg.SUBSCRIBE_UN_ERROR);
            }
            //检验是否已激活
            int i = masterAuthorUnactiveService.selectCount(new EntityWrapper<MasterAuthorUnactive>().eq("maintain_id", versionId).eq("user_id", userId));
            if (i > 0) {
                logs.setErrorInfo(CodeMsg.Active_UN_ERROR.getMsg()).updateById();
                return Result.error(CodeMsg.Active_UN_ERROR);
            }
            //获取权限
            MasterAuthor masterAuthor = new MasterAuthor().setTableName(maintain.getTableName());
            TUser user = new TUser().setUserId(userId);
            //获取理论上的页数,记录数
            initPageInfo = masterAuthorService.getInitPageInfo(masterAuthor, maintain, user, increment);
            if (initPageInfo == null) {
                return Result.success(null);
            }
            //通过 beginNo,endNo更新page信息
            boolean b = refreshInitPage(initPageInfo, beginNo, endNo);
            if(!b) {
                return Result.error(CodeMsg.ERROR_SIZE_TOO_LONG);
            }
            if (increment) {
                //获取增量数据
                String maintainTableName = maintain.getTableName();
                //获取记录表
                String tempTableName = maintainTableName + Constant.RECORD;
                //组装字段
                List<SysField> fieldByMaintain = DbUtils.fieldService.getFieldByMaintain(maintain.getId());
                List<String> fieldList = fieldByMaintain.stream().map(sysField -> sysField.getField()).collect(Collectors.toList());
                String fields = fieldByMaintain.stream().map(sysField -> sysField.getField()).collect(Collectors.joining(Constant.COMMA));
                //组装筛选条件
                String filter = DbUtils.masterAuthorService.getFilter(user, maintain.getId());
                if (StringUtils.isEmpty(filter)) {
                    filter = Constant.WHERE_DEFAULT;
                }
                //获取数据
                List<Map<String, Object>> maps = DbUtils.maintainDetailMapper.selectMaintainDetail(fields, tempTableName, maintain.getId(), filter, initPageInfo.getLimitSQL());
                //脱敏规则
                Map<String, AntianaphylaxisResult> helpfulField = DbUtils.antianaphylaxisClient.getHelpfulField(fields, maintainTableName);
                //转换为脱敏后的数据
                DbUtils.antianaphylaxisClient.fixMasterData(maps,helpfulField);
                //组装返回结果
                JSONObject object = new JSONObject();
                object.fluentPut("records", maps);
                List<SysField> sysFields = masterAuthorService.getField(user, versionId);
                List<DispenseField> collect = sysFields.stream().map(sysField -> new DispenseField().setField(sysField.getField()).setAlias(sysField.getAlias())).collect(Collectors.toList());
                object.fluentPut("fields", collect);
                long time = new Date().getTime();
                logs.setSchedule(time - logs.getCreateTime().getTime()).setStatus("true").setTotal(Long.valueOf(initPageInfo.getRecordCount()).intValue()).updateById();
                return Result.success(object);
            } else {
                //获取全量数据
                Result result = masterDataService.selectListByPageByVersion(user, maintain.getTableName(), null, Constant.WHERE_DEFAULT, null, null, maintain.getVersion(), false, null, initPageInfo);
                //组装返回结果
                Object data = result.getData();
                JSONObject masterResult = new JSONObject();
                JSONObject dataResult = (JSONObject) JSONObject.toJSON(data);
                JSONObject grid = dataResult.getJSONObject("grid");
                masterResult.fluentPut("records", grid.getJSONArray("record"));
                JSONArray fields = dataResult.getJSONArray("fields");
                ArrayList<DispenseField> dispenseFields = new ArrayList<>();
                for (Object field : fields) {
                    JSONObject one = (JSONObject) JSONObject.toJSON(field);
                    dispenseFields.add(new DispenseField().setAlias(one.getString("alias")).setField(one.getString("field")));
                }
                grid.remove("record");
                masterResult.fluentPut("fields", dispenseFields);
                //更新执行时间
                long time = new Date().getTime();
                logs.setSchedule(time - logs.getCreateTime().getTime()).setStatus("true").setTotal(Long.valueOf(initPageInfo.getRecordCount()).intValue()).updateById();
                return Result.success(masterResult);
            }
        } else if (type.equalsIgnoreCase(Constant.View)) {
            //获取视图信息
            SysView sysView = viewService.selectById(dataId);
            if (sysView == null) {
                return Result.error(CodeMsg.SELECT_ERROR_NOTFOUND);
            }
            logs.setName(sysView.getName());
            logs.updateById();
            //检验是否激活
            Boolean active = sysView.getActive();
            if (!active) {
                return Result.error(CodeMsg.Active_UN_ERROR);
            }
            //获取理论上的记录数
            initPageInfo = viewService.getInitPageInfo(sysView.getId());
            if (initPageInfo == null) {
                long time = new Date().getTime();
                logs.setSchedule(time - logs.getCreateTime().getTime()).setStatus("true").setTotal(Long.valueOf(initPageInfo.getRecordCount()).intValue()).updateById();
                return Result.success(null);
            }
            //通过beginNo, endNo更新记录
            boolean b = refreshInitPage(initPageInfo, beginNo, endNo);
            if(!b) {
                logs.setErrorInfo(CodeMsg.ERROR_SIZE_TOO_LONG.getMsg()).updateById();
                return Result.error(CodeMsg.ERROR_SIZE_TOO_LONG);
            }
            //获取视图数据
            Result viewData = viewService.getViewData(sysView, null, 0, initPageInfo);
            //更新记录日志
            long time = new Date().getTime();
            logs.setSchedule(time - logs.getCreateTime().getTime()).setStatus("true").setTotal(Long.valueOf(initPageInfo.getRecordCount()).intValue()).updateById();
            return  viewData;
        } else {
            return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
        }
    }
    /**
     *
     * @description:  通过biginNo endNo 更新page
     * @param initPageInfo 页数信息实体
     * @param beginNo 开始条数
     * @param endNo 结束条数
     * @return: 刷新成功/失败
     *
     */
    private boolean refreshInitPage(com.highdatas.mdm.pojo.Page initPageInfo, Integer beginNo, Integer endNo) {
        //每页条数
        int size = endNo - beginNo;
        int pageSize = initPageInfo.getPageSize();
        //每页数据过多 不准继续执行
        if (pageSize < size) {
            return false;
        }
        //更新page信息
        initPageInfo.setBeginNo(beginNo);
        initPageInfo.setEndNo(endNo);
        initPageInfo.setPageSize(size);
        initPageInfo.setRecordCount(size);
        return true;
    }
    /**
     *
     * @description:  页面调用分发接口  多选
     * @param objectList
     *   userId 分发用户
     *   datas
     *                  [
     *                  dataId 分发的dataId
     *                  type 分发类型, 视图还是主题
     *                  increment 增量/全量
     *        ]
     *
     * @return: 是否添加到队列
     *
     */
    @RequestMapping(value = "/dispense/surface/muti", method = RequestMethod.POST)
    public Result surface(@RequestBody JSONObject objectList, HttpServletRequest request, HttpServletResponse response) {
        //获取用户信息
        String userId = objectList.getString("userId");
        //多个任务的数据
        JSONArray datas = objectList.getJSONArray("datas");
        ArrayList<Result> results = new ArrayList<>();
        for (int i = 0; i < datas.size(); i++) {
            JSONObject oneRequest = datas.getJSONObject(i);
            String type = oneRequest.getString("type");
            String dataId = oneRequest.getString("dataId");
            String versionId = oneRequest.getString("versionId");
            //循环加到分发队列里
            Result result = addPassiveMq(userId, type, dataId, versionId, request, "muti");
            results.add(result);
        }
//        返回每条执行的结果
        return Result.success(results);
    }
    /**
     *
     * @description:  页面调用分发接口
     * @param userId 分发用户
     * @param dataId 分发的dataId
     * @param type 分发类型, 视图还是主题
     * @param increment 增量/全量
     * @param touchType 请求来源的类型
     * @return: 是否添加到队列
     *
     */
    private Result addPassiveMq(@RequestParam String userId, @RequestParam String type, @RequestParam String dataId, String versionId, HttpServletRequest request, String touchType) {
        //创建分发日志
        SysDispenseLogs logs = new SysDispenseLogs()
                .setId(DbUtils.getUUID())
                .setTouchType(touchType)
                .setDataType(type)
                .setCreateTime(new Date())
                .setTopicId(type)
                .setTagId(dataId)
                .setMaintainId(versionId);
            logs.insert();
            //获取用户信息
        TUser user = DbUtils.getUserById(userId);
        if (user == null) {
            logs.setResult(CodeMsg.USER_NOT_MATHED.getMsg()).updateById();
            return Result.error(CodeMsg.USER_NOT_MATHED);
        }
        logs.setUserName(user.getUserName());
        logs.updateById();
        //是否增量
        String incrementStr = request.getParameter("increment");
        boolean increment = true;
        if (!StringUtils.isEmpty(incrementStr)) {
            increment = Boolean.valueOf(incrementStr);
        }
        //创建MQ任务
        MqEntity mqEntity = new MqEntity();
        mqEntity.setUserId(userId);
        mqEntity.setIncrement(increment);
        mqEntity.setMsgTopicName(type);
        mqEntity.setType(type);
        mqEntity.setLogId(logs.getId());
        mqEntity.setDataId(dataId);
        if(type.equalsIgnoreCase(Constant.Master)) {
            //主题的需要检验版本信息
            if (StringUtils.isEmpty(versionId)) {
                logs.setResult(CodeMsg.ERROR_PARAMS_NOT_MATHED.getMsg()).updateById();
                return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
            }
            //获取版本信息
            Maintain maintain = maintainService.selectById(versionId);
            if (maintain == null) {
                logs.setResult(CodeMsg.ERROR_PARAMS_NOT_MATHED.getMsg()).updateById();
                return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
            }
            logs.setVersion(maintain.getVersion());
            logs.updateById();
            mqEntity.setMaintainId(versionId);
            //获取主题信息
            SysMenu sysMenu = menuService.selectById(dataId);
            if (sysMenu == null) {
                logs.setResult(CodeMsg.SELECT_ERROR_NOTFOUND.getMsg()).updateById();
                return Result.error(CodeMsg.SELECT_ERROR_NOTFOUND);
            }
            logs.setName(sysMenu.getName());
            logs.updateById();
            //校验是否激活
            int i = masterAuthorUnactiveService.selectCount(new EntityWrapper<MasterAuthorUnactive>().eq("maintain_id", versionId).eq("user_id", userId));
            if (i > 0) {
                logs.setResult(CodeMsg.Active_UN_ERROR.getMsg()).updateById();
                return Result.error(CodeMsg.Active_UN_ERROR);
            }
            mqEntity.setMsgTagName(sysMenu.getId());
        } else if (type.equalsIgnoreCase(Constant.View)) {
            //获取视图信息
            SysView sysView = viewService.selectById(dataId);
            if (sysView == null) {
                logs.setResult(CodeMsg.SELECT_ERROR_NOTFOUND.getMsg()).updateById();
                return Result.error(CodeMsg.SELECT_ERROR_NOTFOUND);
            }
            logs.setName(sysView.getName());
            logs.updateById();
            //校验是否激活
            Boolean active = sysView.getActive();
            if (!active) {
                logs.setResult(CodeMsg.Active_UN_ERROR.getMsg()).updateById();
                return Result.error(CodeMsg.Active_UN_ERROR);
            }
            mqEntity.setMsgTagName(sysView.getId());
        } else {
            logs.setResult(CodeMsg.ERROR_PARAMS_NOT_MATHED.getMsg()).updateById();
            return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
        }
        //创建msgKey
        mqEntity.setMsgKey(DbUtils.getUUID(16));
        MqEntity.MsgBodyBean msgBody = mqEntity.getMsgBody();
        msgBody.setTo(userId);
        msgBody.setVersion(versionId);
        MqMessage mqMessage = new MqMessage(mqEntity);
        //保存日志id 方便后续获取
        mqEntity.setLogId(logs.getId());
        //添加到被动分发队列
        return dispenseService.pushPassiveMq(mqMessage, touchType, logs);//被动返回
//        dispenseService.pushActiveMq(mqMessage);  主动推
    }
    /**
     *
     * @description:  外部系统调用分发接口
     * @param token 分发用户token
     * @param dataId 分发的dataId
     * @param type 分发类型, 视图还是主题
     * @param versionId 版本id
     * @return: 是否添加到队列
     *
     */
    @RequestMapping(value = "/dispense/api", method = RequestMethod.GET)
    public Result api(@RequestParam String token, @RequestParam String type, @RequestParam String dataId, HttpServletRequest request, HttpServletResponse response) {
        //通过token获取用户信息
        String userId = redisClient.getRedisVal(token);
        if (StringUtils.isEmpty(userId)) {
            return Result.error(CodeMsg.ERROR_FIND_TOKEN);
        }
        //获取版本信息
        String versionId = request.getParameter("versionId");
        //添加到分发队列
        return addPassiveMq(userId, type, dataId, versionId, request, "api");
    }
    /**
     *
     * @description:  外部系统调用 注册接口
     * @param token 分发用户
     * @param dataId 分发的dataId
     * @param type 分发类型, 视图还是主题
     * @return: 是否添加成功
     *
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public void getAll(@RequestParam String code,  HttpServletResponse response) {
        dispenseService.pushPassiveMq(new MqMessage( code, response));
    public Result add(@RequestParam String token, @RequestParam String type, @RequestParam String dataId) {
        try{
            //获取用户信息
            String redisVal = redisClient.getRedisVal(token);
            if (StringUtils.isEmpty(redisVal)) {
                return Result.error(CodeMsg.ERROR_FIND_TOKEN);
            }
            if(type.equalsIgnoreCase(Constant.Master)) {
                //获取权限
                MasterAuthor masterAuthor = masterAuthorService.selectById(dataId);
                if (masterAuthor == null) {
                    return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
                }
                //创建注册信息
                boolean updated = new MasterAuthorSubscribe().setId(DbUtils.getUUID()).setMenuId(masterAuthor.getId()).setUserId(redisVal).insert();
                if (updated) {
                    return Result.success(null);
                } else {
                    return Result.error(CodeMsg.SUBSCRIBE_SAVE_ERROR);
                }
            } else if (type.equalsIgnoreCase(Constant.View)) {
                //获取视图信息
                SysView sysView =  viewService.selectById(dataId);
                if (sysView == null) {
                    return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
                }
                //注册视图
                boolean updated = sysView.setSubscribe(true).updateById();
                if (updated) {
                    return Result.success(null);
                } else {
                    return Result.error(CodeMsg.SUBSCRIBE_SAVE_ERROR);
                }
            } else {
                return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            return Result.error(CodeMsg.ERROR_SAVE_TOKEN);
        }
    }
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String test(@RequestParam String tableName,  HttpServletRequest request) {
        TUser user = DbUtils.getUser(request);
        List<String> size = new ArrayList<>();
        String s = masterDataService.selectByVersionSql(user, tableName, size, Constant.WHERE_DEFAULT, "V1.0", false);
        return s;
    /**
     *
     * @description:  外部系统调用批量 注册接口
     * @param token 分发用户
     * @param datalist 分发的dataList
     * @return: 是否添加成功
     *
     */
    @RequestMapping(value = "/refreshList", method = RequestMethod.POST)
    public Result refreshList(@RequestBody JSONObject requestBody) {
        //通过token获取用户信息
        String token = requestBody.getString(Constant.Token);
        if (StringUtils.isEmpty(token)) {
            return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
        }
        try{
            String userId = redisClient.getRedisVal(token);
            if (StringUtils.isEmpty(userId)) {
                return Result.error(CodeMsg.ERROR_FIND_TOKEN);
            }
            //校验datalist
            JSONArray dataList = requestBody.getJSONArray("dataList");
            if (dataList == null) {
                return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
            }
            //un subscribe
            //删除当前用户所有的注册信息
            List<SysView> sysViews = viewService.selectList(new EntityWrapper<SysView>().eq(Constant.USERID, userId));
            for (SysView sysView : sysViews) {
                sysView.setSubscribe(false).updateById();
            }
            masterAuthorSubscribeService.delete(new EntityWrapper<MasterAuthorSubscribe>().eq(Constant.USERID, userId));
            //循环添加新的注册信息
            for (int i = 0; i < dataList.size(); i++) {
                JSONObject oneObj = dataList.getJSONObject(i);
                String dataId = oneObj.getString("dataId");
                String type = oneObj.getString("type");
                if (StringUtils.isEmpty(dataId) || StringUtils.isEmpty(type)) {
                    return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
                }
                if(type.equalsIgnoreCase(Constant.Master)) {
                    //校验是否有权限
                    MasterAuthor masterAuthor = masterAuthorService.selectById(dataId);
                    if (masterAuthor == null) {
                        return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
                    }
                    //注册主题
                    boolean updated = new MasterAuthorSubscribe().setId(DbUtils.getUUID()).setMenuId(masterAuthor.getId()).setUserId(userId).insert();
                    if (updated) {
                        return Result.success(null);
                    } else {
                        return Result.error(CodeMsg.SUBSCRIBE_SAVE_ERROR);
                    }
                } else if (type.equalsIgnoreCase(Constant.View)) {
                    SysView sysView =  viewService.selectById(dataId);
                    if (sysView == null) {
                        return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
                    }
                    //注册视图
                    boolean updated = sysView.setSubscribe(true).updateById();
                    if (updated) {
                        return Result.success(null);
                    } else {
                        return Result.error(CodeMsg.SUBSCRIBE_SAVE_ERROR);
                    }
                } else {
                    return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
                }
            }
            return Result.success(null);
        }
        catch (Exception e) {
            e.printStackTrace();
            return Result.error(CodeMsg.ERROR_SAVE_TOKEN);
        }
    }
    /**
     *
     * @description:  外部系统调用 删除注册接口
     * @param token 分发用户
     * @param dataId 分发的dataId
     * @param type 分发类型, 视图还是主题
     * @return: 是否添加成功
     *
     */
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public Result delete(@RequestParam String token, @RequestParam String type, @RequestParam String dataId) {
        try{
            //获取用户信息通过token
            String redisVal = redisClient.getRedisVal(token);
            if (StringUtils.isEmpty(redisVal)) {
                return Result.error(CodeMsg.ERROR_FIND_TOKEN);
            }
            if(type.equalsIgnoreCase(Constant.Master)) {
                //校验权限
                MasterAuthor masterAuthor = masterAuthorService.selectById(dataId);
                if (masterAuthor == null) {
                    return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
                }
                //删除注册
                boolean updated = masterAuthorSubscribeService.delete(new EntityWrapper<MasterAuthorSubscribe>().eq("master_author_id", masterAuthor.getId()).eq(Constant.USERID, redisVal));
                if (updated) {
                    return Result.success(null);
                } else {
                    return Result.error(CodeMsg.SUBSCRIBE_SAVE_ERROR);
                }
            } else if (type.equalsIgnoreCase(Constant.View)) {
                SysView sysView =  viewService.selectById(dataId);
                if (sysView == null) {
                    return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
                }
                //删除视图
                boolean updated = sysView.setSubscribe(false).updateById();
                if (updated) {
                    return Result.success(null);
                } else {
                    return Result.error(CodeMsg.SUBSCRIBE_SAVE_ERROR);
                }
            } else {
                return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            return Result.error(CodeMsg.ERROR_SAVE_TOKEN);
        }
    }
    /**
     *
     * @description:  外部系统调用 获取可注册数据列表接口
     * @param token 分发用户
     * @return: 是否添加成功
     *
     */
    @RequestMapping(value = "/authors", method = RequestMethod.GET)
    public Result authors(@RequestParam String token) {
        try{
            //通过token获取用户信息
            String userId = redisClient.getRedisVal(token);
            if (StringUtils.isEmpty(userId)) {
                return Result.error(CodeMsg.ERROR_FIND_TOKEN);
            }
            TUser user = DbUtils.getUserById(userId);
            if (user == null) {
                return Result.error(CodeMsg.USER_NOT_MATHED);
            }
            List<SubscribeEntity> result = new ArrayList<>();
            //获取用户权限
            List<MasterAuthor> userAuthor = masterAuthorService.getUserAuthor(userId, null);
            // author 只有拥有最新权限的才能订阅
            userAuthor = userAuthor.stream()
                    .filter(masterAuthor -> !StringUtils.isEmpty(masterAuthor.getMaintainFieldId()))
//                    .filter(masterAuthor -> masterAuthor.getMaintainFieldId().equalsIgnoreCase(Constant.All))
                    .collect(Collectors.toList());
            for (MasterAuthor masterAuthor : userAuthor) {
                SubscribeEntity subscribeEntity = new SubscribeEntity();
                //获取版本list
                List<Maintain> versionList = maintainFieldService.getMaintainByMaintainField(masterAuthor.getMaintainFieldId(), masterAuthor.getTableName());
                if (versionList != null && !versionList.isEmpty()) {
                    //版本排序 倒序
                    Collections.sort(versionList, new Comparator<Maintain>() {
                        @Override
                        public int compare(Maintain o1, Maintain o2) {
                            return o2.getOrderNo().compareTo(o1.getOrderNo());
                        }
                    });
                    ArrayList<JSONObject> jsonObjects = new ArrayList<>();
                    for (Maintain maintain : versionList) {
                        JSONObject object = new JSONObject();
                        object.fluentPut("id", maintain.getId());
                        object.fluentPut("version", maintain.getVersion());
                        jsonObjects.add(object);
                    }
                    //组装返回信息
                   subscribeEntity.setVersionList(jsonObjects);
                }
                //添加当前返回的数据类型为主题
                subscribeEntity.setType(Constant.Master);
                String menuId = masterAuthor.getMenuId();
                SysMenu sysMenu = menuService.selectById(menuId);
                if (sysMenu == null) {
                    continue;
                }
                subscribeEntity.setId(sysMenu.getId());
                subscribeEntity.setName(sysMenu.getName());
                String maintainFieldId = masterAuthor.getMaintainFieldId();
                String tableName = masterAuthor.getTableName();
                //获取当前版本信息通过权限,主题
                Maintain nowVersion = maintainService.getNowVersion(tableName);
                if (nowVersion == null) {
                    continue;
                }
                List<Maintain> maintainByMaintainField = maintainFieldService.getMaintainByMaintainField(maintainFieldId, tableName);
                //校验权限是否包含最新版本
                long count = maintainByMaintainField.stream().filter(maintain -> maintain.getId().equalsIgnoreCase(nowVersion.getId())).count();
                if (count  == 1) {
                    result.add(subscribeEntity);
                }
            }
            //view 可注册的视图信息
            List<SysView> sysViews = viewService.selectList(new EntityWrapper<SysView>().eq(Constant.USERID, userId));
            List<SubscribeEntity> viewList = sysViews.stream()
                    .map(view -> new SubscribeEntity().setId(view.getId()).setName(view.getName()).setType(Constant.View))
                    .collect(Collectors.toList());
            result.addAll(viewList);
            return Result.success(result);
        }
        catch (Exception e) {
            e.printStackTrace();
            return Result.error(CodeMsg.ERROR_SAVE_TOKEN);
        }
    }
    /**
     *
     * @description:  外部系统调用 获取token信息
     * @return: 是否添加成功
     *
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public Result login(HttpServletRequest request) {
        //请求头里获取用户信息
        TUser user = DbUtils.getUser(request);
        String token = DbUtils.getUUID(32);
        boolean b = redisClient.putRedisVal(user.getId(), token);
        //保存redis内,默认 超时时间30Min
        boolean b = redisClient.putRedisVal(token, user.getId());
        if (b) {
            return Result.success(token);
        }else {
            return Result.success(CodeMsg.ERROR_SAVE_TOKEN);
        }
    }
    /**
     *
     * @description: 分页获取日志信息
     * @param pageNo 页数
     * @param touchType 请求类型
     * @param pageSize 每页条数
     * @return: 是否添加成功
     *
     */
    @RequestMapping(value = "/log/all/{pageNo}", method = RequestMethod.GET)
    public Result login( @PathVariable int pageNo, HttpServletRequest request) throws ParseException {
        String pageSizeStr = request.getParameter("pageSize");
        String touchType = request.getParameter("touchType");
        int pageSize = 15;
        if (!StringUtils.isEmpty(pageSizeStr)) {
            pageSize = Integer.valueOf(pageSizeStr);
        }
        Wrapper<SysDispenseLogs> wrapper = new EntityWrapper<SysDispenseLogs>();
        if (!StringUtils.isEmpty(touchType)) {
            if ("sys".equalsIgnoreCase(touchType)) {
                //页面点击+系统主动分发的为分发列表
                ArrayList<String> strings = new ArrayList<>();
                strings.add("muti");
                strings.add("sys");
                strings.add("surface");
                wrapper.in("touch_type", strings);
            } else {
                //外部系统调用为调用列表
                ArrayList<String> strings = new ArrayList<>();
                strings.add("api");
                strings.add("rest");
                wrapper.in("touch_type", strings);
            }
        }
        //筛选--数据类型
        String dataType = request.getParameter("dataType");
        if (!StringUtils.isEmpty(dataType)) {
            wrapper.eq("data_type", dataType);
        }
        //筛选--用户
        String userId = request.getParameter("userId");
        if (!StringUtils.isEmpty(userId)) {
            wrapper.eq("user_id", userId);
        }
//        筛选-- 主题
        String name = request.getParameter("name");
        if (!StringUtils.isEmpty(name)) {
            wrapper.like("name", name);
        }
        //筛选-- 主题id或者视图id
        String tagId = request.getParameter("tagId");
        if (!StringUtils.isEmpty(tagId)) {
            wrapper.eq("tag_id", tagId);
        }
        //筛选-- 主题版本
        String maintainId = request.getParameter("maintainId");
        if (!StringUtils.isEmpty(maintainId)) {
            wrapper.eq("maintain_id", maintainId);
        }
        //筛选--分发状态
        String status = request.getParameter("status");
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("status", status);
        }
        //--BY 时间段筛选
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String startTime = request.getParameter("startTime");
        if (!StringUtils.isEmpty(startTime)) {
            Date start = simpleDateFormat.parse(startTime);
            wrapper.ge("create_time", start);
        }
        String endTime = request.getParameter("endTime");
        if (!StringUtils.isEmpty(endTime)) {
            Date end = simpleDateFormat.parse(endTime);
            wrapper.le("create_time", end);
        }
        Page<SysDispenseLogs> page = new Page<>(pageNo, pageSize);
        //创建时间倒叙
        wrapper.orderBy("create_time desc");
        Page<SysDispenseLogs> sysDispenseLogsPage = dispenseLogsService.selectPage(page, wrapper);
        return Result.success(sysDispenseLogsPage);
    }
}