2.27进存销系统2 Controller类

CangkuController

package com.controller;

import java.io.File;
import java.math.BigDecimal;
import java.net.URL;
import java.text.SimpleDateFormat;
import com.alibaba.fastjson.JSONObject;
import java.util.*;
import org.springframework.beans.BeanUtils;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.ContextLoader;
import javax.servlet.ServletContext;
import com.service.TokenService;
import com.utils.*;
import java.lang.reflect.InvocationTargetException;

import com.service.DictionaryService;
import org.apache.commons.lang3.StringUtils;
import com.annotation.IgnoreAuth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.entity.*;
import com.entity.view.*;
import com.service.*;
import com.utils.PageUtils;
import com.utils.R;
import com.alibaba.fastjson.*;

/**
 * 仓库信息
 * 后端接口
 * @author
 * @email
*/
@RestController
@Controller
@RequestMapping("/cangku")
public class CangkuController {
    private static final Logger logger = LoggerFactory.getLogger(CangkuController.class);

    @Autowired
    private CangkuService cangkuService;


    @Autowired
    private TokenService tokenService;
    @Autowired
    private DictionaryService dictionaryService;

    //级联表service

    @Autowired
    private YonghuService yonghuService;


    /**
    * 后端列表
    */
    @RequestMapping("/page")
    public R page(@RequestParam Map<String, Object> params, HttpServletRequest request){
        logger.debug("page方法:,,Controller:{},,params:{}",this.getClass().getName(),JSONObject.toJSONString(params));
        String role = String.valueOf(request.getSession().getAttribute("role"));
        if(StringUtil.isEmpty(role))
            return R.error(511,"权限为空");
        else if("员工".equals(role))
            params.put("yonghuId",request.getSession().getAttribute("userId"));
        if(params.get("orderBy")==null || params.get("orderBy")==""){
            params.put("orderBy","id");
        }
        PageUtils page = cangkuService.queryPage(params);

        //字典表数据转换
        List<CangkuView> list =(List<CangkuView>)page.getList();
        for(CangkuView c:list){
            //修改对应字典表字段
            dictionaryService.dictionaryConvert(c, request);
        }
        return R.ok().put("data", page);
    }

    /**
    * 后端详情
    */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id, HttpServletRequest request){
        logger.debug("info方法:,,Controller:{},,id:{}",this.getClass().getName(),id);
        CangkuEntity cangku = cangkuService.selectById(id);
        if(cangku !=null){
            //entity转view
            CangkuView view = new CangkuView();
            BeanUtils.copyProperties( cangku , view );//把实体数据重构到view中

            //修改对应字典表字段
            dictionaryService.dictionaryConvert(view, request);
            return R.ok().put("data", view);
        }else {
            return R.error(511,"查不到数据");
        }

    }

    /**
    * 后端保存
    */
    @RequestMapping("/save")
    public R save(@RequestBody CangkuEntity cangku, HttpServletRequest request){
        logger.debug("save方法:,,Controller:{},,cangku:{}",this.getClass().getName(),cangku.toString());

        String role = String.valueOf(request.getSession().getAttribute("role"));
        if(StringUtil.isEmpty(role))
            return R.error(511,"权限为空");

        Wrapper<CangkuEntity> queryWrapper = new EntityWrapper<CangkuEntity>()
            .eq("cangku_uuid_unmber", cangku.getCangkuUuidUnmber())
            .eq("cangku_name", cangku.getCangkuName())
            .eq("cangku_types", cangku.getCangkuTypes())
            .eq("cangku_address", cangku.getCangkuAddress())
            ;

        logger.info("sql语句:"+queryWrapper.getSqlSegment());
        CangkuEntity cangkuEntity = cangkuService.selectOne(queryWrapper);
        if(cangkuEntity==null){
            cangku.setCreateTime(new Date());
            cangkuService.insert(cangku);
            return R.ok();
        }else {
            return R.error(511,"表中有相同数据");
        }
    }

    /**
    * 后端修改
    */
    @RequestMapping("/update")
    public R update(@RequestBody CangkuEntity cangku, HttpServletRequest request){
        logger.debug("update方法:,,Controller:{},,cangku:{}",this.getClass().getName(),cangku.toString());

        String role = String.valueOf(request.getSession().getAttribute("role"));
//        if(StringUtil.isEmpty(role))
//            return R.error(511,"权限为空");
        //根据字段查询是否有相同数据
        Wrapper<CangkuEntity> queryWrapper = new EntityWrapper<CangkuEntity>()
            .notIn("id",cangku.getId())
            .andNew()
            .eq("cangku_uuid_unmber", cangku.getCangkuUuidUnmber())
            .eq("cangku_name", cangku.getCangkuName())
            .eq("cangku_types", cangku.getCangkuTypes())
            .eq("cangku_address", cangku.getCangkuAddress())
            ;

        logger.info("sql语句:"+queryWrapper.getSqlSegment());
        CangkuEntity cangkuEntity = cangkuService.selectOne(queryWrapper);
        if(cangkuEntity==null){
            cangkuService.updateById(cangku);//根据id更新
            return R.ok();
        }else {
            return R.error(511,"表中有相同数据");
        }
    }

    /**
    * 删除
    */
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] ids){
        logger.debug("delete:,,Controller:{},,ids:{}",this.getClass().getName(),ids.toString());
        cangkuService.deleteBatchIds(Arrays.asList(ids));
        return R.ok();
    }


    /**
     * 批量上传
     */
    @RequestMapping("/batchInsert")
    public R save( String fileName){
        logger.debug("batchInsert方法:,,Controller:{},,fileName:{}",this.getClass().getName(),fileName);
        try {
            List<CangkuEntity> cangkuList = new ArrayList<>();//上传的东西
            Map<String, List<String>> seachFields= new HashMap<>();//要查询的字段
            Date date = new Date();
            int lastIndexOf = fileName.lastIndexOf(".");
            if(lastIndexOf == -1){
                return R.error(511,"该文件没有后缀");
            }else{
                String suffix = fileName.substring(lastIndexOf);
                if(!".xls".equals(suffix)){
                    return R.error(511,"只支持后缀为xls的excel文件");
                }else{
                    URL resource = this.getClass().getClassLoader().getResource("static/upload/" + fileName);//获取文件路径
                    File file = new File(resource.getFile());
                    if(!file.exists()){
                        return R.error(511,"找不到上传文件,请联系管理员");
                    }else{
                        List<List<String>> dataList = PoiUtil.poiImport(file.getPath());//读取xls文件
                        dataList.remove(0);//删除第一行,因为第一行是提示
                        for(List<String> data:dataList){
                            //循环
                            CangkuEntity cangkuEntity = new CangkuEntity();
//                            cangkuEntity.setCangkuUuidUnmber(data.get(0));                    //仓库编号 要改的
//                            cangkuEntity.setCangkuName(data.get(0));                    //仓库名称 要改的
//                            cangkuEntity.setCangkuTypes(Integer.valueOf(data.get(0)));   //仓库类型 要改的
//                            cangkuEntity.setCangkuAddress(data.get(0));                    //所在区域 要改的
//                            cangkuEntity.setCreateTime(date);//时间
                            cangkuList.add(cangkuEntity);


                            //把要查询是否重复的字段放入map中
                        }

                        //查询是否重复
                        cangkuService.insertBatch(cangkuList);
                        return R.ok();
                    }
                }
            }
        }catch (Exception e){
            return R.error(511,"批量插入数据异常,请联系管理员");
        }
    }






}
View Code

CommonController

package com.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.annotation.IgnoreAuth;
import com.baidu.aip.face.AipFace;
import com.baidu.aip.face.MatchRequest;
import com.baidu.aip.util.Base64Util;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.entity.ConfigEntity;
import com.service.CommonService;
import com.service.ConfigService;
import com.utils.BaiduUtil;
import com.utils.FileUtil;
import com.utils.R;

/**
 * 通用接口
 */
@RestController
public class CommonController{
    private static final Logger logger = LoggerFactory.getLogger(CommonController.class);
    @Autowired
    private CommonService commonService;
    
    @Autowired
    private ConfigService configService;
    
    private static AipFace client = null;
    
    private static String BAIDU_DITU_AK = null;
    
    @RequestMapping("/location")
    public R location(String lng,String lat) {
        if(BAIDU_DITU_AK==null) {
            BAIDU_DITU_AK = configService.selectOne(new EntityWrapper<ConfigEntity>().eq("name", "baidu_ditu_ak")).getValue();
            if(BAIDU_DITU_AK==null) {
                return R.error("请在配置管理中正确配置baidu_ditu_ak");
            }
        }
        Map<String, String> map = BaiduUtil.getCityByLonLat(BAIDU_DITU_AK, lng, lat);
        return R.ok().put("data", map);
    }
    
    /**
     * 人脸比对
     * 
     * @param face1 人脸1
     * @param face2 人脸2
     * @return
     */
    @RequestMapping("/matchFace")
    public R matchFace(String face1, String face2, HttpServletRequest request) {
        if(client==null) {
            /*String AppID = configService.selectOne(new EntityWrapper<ConfigEntity>().eq("name", "AppID")).getValue();*/
            String APIKey = configService.selectOne(new EntityWrapper<ConfigEntity>().eq("name", "APIKey")).getValue();
            String SecretKey = configService.selectOne(new EntityWrapper<ConfigEntity>().eq("name", "SecretKey")).getValue();
            String token = BaiduUtil.getAuth(APIKey, SecretKey);
            if(token==null) {
                return R.error("请在配置管理中正确配置APIKey和SecretKey");
            }
            client = new AipFace(null, APIKey, SecretKey);
            client.setConnectionTimeoutInMillis(2000);
            client.setSocketTimeoutInMillis(60000);
        }
        JSONObject res = null;
        try {
            File file1 = new File(request.getSession().getServletContext().getRealPath("/upload")+"/"+face1);
            File file2 = new File(request.getSession().getServletContext().getRealPath("/upload")+"/"+face2);
            String img1 = Base64Util.encode(FileUtil.FileToByte(file1));
            String img2 = Base64Util.encode(FileUtil.FileToByte(file2));
            MatchRequest req1 = new MatchRequest(img1, "BASE64");
            MatchRequest req2 = new MatchRequest(img2, "BASE64");
            ArrayList<MatchRequest> requests = new ArrayList<MatchRequest>();
            requests.add(req1);
            requests.add(req2);
            res = client.match(requests);
            System.out.println(res.get("result"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return R.error("文件不存在");
        } catch (IOException e) {
            e.printStackTrace();
        } 
        return R.ok().put("data", com.alibaba.fastjson.JSONObject.parse(res.get("result").toString()));
    }
    
    /**
     * 获取table表中的column列表(联动接口)
     * @return
     */
    @RequestMapping("/option/{tableName}/{columnName}")
    @IgnoreAuth
    public R getOption(@PathVariable("tableName") String tableName, @PathVariable("columnName") String columnName,String level,String parent) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("table", tableName);
        params.put("column", columnName);
        if(StringUtils.isNotBlank(level)) {
            params.put("level", level);
        }
        if(StringUtils.isNotBlank(parent)) {
            params.put("parent", parent);
        }
        List<String> data = commonService.getOption(params);
        return R.ok().put("data", data);
    }
    
    /**
     * 根据table中的column获取单条记录
     * @return
     */
    @RequestMapping("/follow/{tableName}/{columnName}")
    @IgnoreAuth
    public R getFollowByOption(@PathVariable("tableName") String tableName, @PathVariable("columnName") String columnName, @RequestParam String columnValue) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("table", tableName);
        params.put("column", columnName);
        params.put("columnValue", columnValue);
        Map<String, Object> result = commonService.getFollowByOption(params);
        return R.ok().put("data", result);
    }
    
    /**
     * 修改table表的sfsh状态
     * @param map
     * @return
     */
    @RequestMapping("/sh/{tableName}")
    public R sh(@PathVariable("tableName") String tableName, @RequestBody Map<String, Object> map) {
        map.put("table", tableName);
        commonService.sh(map);
        return R.ok();
    }
    
    /**
     * 获取需要提醒的记录数
     * @param tableName
     * @param columnName
     * @param type 1:数字 2:日期
     * @param map
     * @return
     */
    @RequestMapping("/remind/{tableName}/{columnName}/{type}")
    @IgnoreAuth
    public R remindCount(@PathVariable("tableName") String tableName, @PathVariable("columnName") String columnName, 
                         @PathVariable("type") String type,@RequestParam Map<String, Object> map) {
        map.put("table", tableName);
        map.put("column", columnName);
        map.put("type", type);
        
        if(type.equals("2")) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar c = Calendar.getInstance();
            Date remindStartDate = null;
            Date remindEndDate = null;
            if(map.get("remindstart")!=null) {
                Integer remindStart = Integer.parseInt(map.get("remindstart").toString());
                c.setTime(new Date()); 
                c.add(Calendar.DAY_OF_MONTH,remindStart);
                remindStartDate = c.getTime();
                map.put("remindstart", sdf.format(remindStartDate));
            }
            if(map.get("remindend")!=null) {
                Integer remindEnd = Integer.parseInt(map.get("remindend").toString());
                c.setTime(new Date());
                c.add(Calendar.DAY_OF_MONTH,remindEnd);
                remindEndDate = c.getTime();
                map.put("remindend", sdf.format(remindEndDate));
            }
        }
        
        int count = commonService.remindCount(map);
        return R.ok().put("count", count);
    }

    /**
     * 圖表统计
     */
    @IgnoreAuth
    @RequestMapping("/group/{tableName}")
    public R group1(@PathVariable("tableName") String tableName, @RequestParam Map<String,Object> params) {
        params.put("table1", tableName);
        List<Map<String, Object>> result = commonService.chartBoth(params);
        return R.ok().put("data", result);
    }

    
    /**
     * 单列求和
     */
    @RequestMapping("/cal/{tableName}/{columnName}")
    @IgnoreAuth
    public R cal(@PathVariable("tableName") String tableName, @PathVariable("columnName") String columnName) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("table", tableName);
        params.put("column", columnName);
        Map<String, Object> result = commonService.selectCal(params);
        return R.ok().put("data", result);
    }
    
    /**
     * 分组统计
     */
    @RequestMapping("/group/{tableName}/{columnName}")
    @IgnoreAuth
    public R group(@PathVariable("tableName") String tableName, @PathVariable("columnName") String columnName) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("table", tableName);
        params.put("column", columnName);
        List<Map<String, Object>> result = commonService.selectGroup(params);
        return R.ok().put("data", result);
    }
    
    /**
     * (按值统计)
     */
    @RequestMapping("/value/{tableName}/{xColumnName}/{yColumnName}")
    @IgnoreAuth
    public R value(@PathVariable("tableName") String tableName, @PathVariable("yColumnName") String yColumnName, @PathVariable("xColumnName") String xColumnName) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("table", tableName);
        params.put("xColumn", xColumnName);
        params.put("yColumn", yColumnName);
        List<Map<String, Object>> result = commonService.selectValue(params);
        return R.ok().put("data", result);
    }


    /**
     * 下面为新加的
     *
     *
     *
     */

    /**
     * 查询字典表的分组求和
     * tableName          表名
     * groupColumn          分组字段
     * sumCloum            统计字段
     * @return
     */
    @RequestMapping("/newSelectGroupSum")
    public R newSelectGroupSum(@RequestParam Map<String,Object> params) {
        logger.debug("newSelectGroupSum:,,Controller:{},,params:{}",this.getClass().getName(),params);
        List<Map<String, Object>> result = commonService.newSelectGroupSum(params);
        return R.ok().put("data", result);
    }

    /**
     * 查询字典表的分组统计总条数
     *  tableName          表名
     *    groupColumn      分组字段
     * @return
     */
    @RequestMapping("/newSelectGroupCount")
    public R newSelectGroupCount(@RequestParam Map<String,Object> params) {
        logger.debug("newSelectGroupCount:,,Controller:{},,params:{}",this.getClass().getName(),params);
        List<Map<String, Object>> result = commonService.newSelectGroupCount(params);
        return R.ok().put("data", result);
    }


    /**
     * 当前表的日期分组求和
     * tableName          表名
     * groupColumn          分组字段
     * sumCloum            统计字段
     * dateFormatType    日期格式化类型   1:年 2:月 3:日
     * @return
     */
    @RequestMapping("/newSelectDateGroupSum")
    public R newSelectDateGroupSum(@RequestParam Map<String,Object> params) {
        logger.debug("newSelectDateGroupSum:,,Controller:{},,params:{}",this.getClass().getName(),params);
        String dateFormatType = String.valueOf(params.get("dateFormatType"));
        if("1".equals(dateFormatType)){
            params.put("dateFormat", "%Y");
        }else if("2".equals(dateFormatType)){
            params.put("dateFormat", "%Y-%m");
        }else if("3".equals(dateFormatType)){
            params.put("dateFormat", "%Y-%m-%d");
        }else{
            R.error("日期格式化不正确");
        }
        List<Map<String, Object>> result = commonService.newSelectDateGroupSum(params);
        return R.ok().put("data", result);
    }

    /**
     *
     * 查询字典表的分组统计总条数
     * tableName          表名
     * groupColumn          分组字段
     * dateFormatType    日期格式化类型   1:年 2:月 3:日
     * @return
     */
    @RequestMapping("/newSelectDateGroupCount")
    public R newSelectDateGroupCount(@RequestParam Map<String,Object> params) {
        logger.debug("newSelectDateGroupCount:,,Controller:{},,params:{}",this.getClass().getName(),params);
        String dateFormatType = String.valueOf(params.get("dateFormatType"));
        if("1".equals(dateFormatType)){
            params.put("dateFormat", "%Y");
        }else if("2".equals(dateFormatType)){
            params.put("dateFormat", "%Y-%m");
        }else if("3".equals(dateFormatType)){
            params.put("dateFormat", "%Y-%m-%d");
        }else{
            R.error("日期格式化类型不正确");
        }
        List<Map<String, Object>> result = commonService.newSelectDateGroupCount(params);
        return R.ok().put("data", result);
    }
/**
 * 饼状图
 * -- 饼状图  查询当前表
 --                 查询字典表【月】
 --                  统计   -- 查询某个月的每个类型的订单销售数量
 --                  求和   -- 查询某个月的每个类型的订单销售额
 --                 查询某个字符串【月】
 --                  统计   -- 查询某个月的每个员工的订单销售数量
 --                  求和   -- 查询某个月的每个员工的订单销售额
 --                 查询时间【年】
 --                  统计     -- 查询每个月的订单销售数量
 --                  求和     -- 查询每个月的订单销售额
 -- 饼状图  查询级联表
 --                 查询字典表
 --                  统计      -- 查询某个月的每个类型的订单销售数量
 --                  求和   -- 查询某个月的每个类型的订单销售额
 --                 查询某个字符串
 --                  统计   -- 查询某个月的每个员工的订单销售数量
 --                  求和   -- 查询某个月的每个员工的订单销售额
 --                 查询时间
 --                  统计     -- 统计每个月的订单销售数量
 --                  求和     -- 查询每个月的订单销售额
 */


/**
 * 柱状图
 -- 柱状图  查询当前表
 --             某个【年,月】
 --              当前表 2 级联表 1
 --                         统计
 --                           【日期,字符串,下拉框】
 --                         求和
 --                           【日期,字符串,下拉框】
 -- 柱状图  查询级联表
 --                     某个【年,月】
 --                         统计
 --                           【日期,字符串,下拉框】
 --                         求和
 --                           【日期,字符串,下拉框】
 */

    /**
     * 柱状图求和
     */
    @RequestMapping("/barSum")
    public R barSum(@RequestParam Map<String,Object> params) {
        logger.debug("barSum方法:,,Controller:{},,params:{}",this.getClass().getName(), com.alibaba.fastjson.JSONObject.toJSONString(params));
        Boolean isJoinTableFlag =  false;//是否有级联表相关
        String one =  "";//第一优先
        String two =  "";//第二优先

        //处理thisTable和joinTable 处理内容是把json字符串转为Map并把带有,的切割为数组
            //当前表
            Map<String,Object> thisTable = JSON.parseObject(String.valueOf(params.get("thisTable")),Map.class);
            params.put("thisTable",thisTable);

            //级联表
            String joinTableString = String.valueOf(params.get("joinTable"));
            if(StringUtil.isNotEmpty(joinTableString)) {
                Map<String, Object> joinTable = JSON.parseObject(joinTableString, Map.class);
                params.put("joinTable", joinTable);
                isJoinTableFlag = true;
            }

        if(StringUtil.isNotEmpty(String.valueOf(thisTable.get("date")))){//当前表日期
            thisTable.put("date",String.valueOf(thisTable.get("date")).split(","));
            one = "thisDate0";
        }
        if(isJoinTableFlag){//级联表日期
            Map<String, Object> joinTable = (Map<String, Object>) params.get("joinTable");
            if(StringUtil.isNotEmpty(String.valueOf(joinTable.get("date")))){
                joinTable.put("date",String.valueOf(joinTable.get("date")).split(","));
                if(StringUtil.isEmpty(one)){
                    one ="joinDate0";
                }else{
                    if(StringUtil.isEmpty(two)){
                        two ="joinDate0";
                    }
                }
            }
        }
        if(StringUtil.isNotEmpty(String.valueOf(thisTable.get("string")))){//当前表字符串
            thisTable.put("string",String.valueOf(thisTable.get("string")).split(","));
            if(StringUtil.isEmpty(one)){
                one ="thisString0";
            }else{
                if(StringUtil.isEmpty(two)){
                    two ="thisString0";
                }
            }
        }
        if(isJoinTableFlag){//级联表字符串
            Map<String, Object> joinTable = (Map<String, Object>) params.get("joinTable");
            if(StringUtil.isNotEmpty(String.valueOf(joinTable.get("string")))){
                joinTable.put("string",String.valueOf(joinTable.get("string")).split(","));
                if(StringUtil.isEmpty(one)){
                    one ="joinString0";
                }else{
                    if(StringUtil.isEmpty(two)){
                        two ="joinString0";
                    }
                }
            }
        }
        if(StringUtil.isNotEmpty(String.valueOf(thisTable.get("types")))){//当前表类型
            thisTable.put("types",String.valueOf(thisTable.get("types")).split(","));
            if(StringUtil.isEmpty(one)){
                one ="thisTypes0";
            }else{
                if(StringUtil.isEmpty(two)){
                    two ="thisTypes0";
                }
            }
        }
        if(isJoinTableFlag){//级联表类型
            Map<String, Object> joinTable = (Map<String, Object>) params.get("joinTable");
            if(StringUtil.isNotEmpty(String.valueOf(joinTable.get("types")))){
                joinTable.put("types",String.valueOf(joinTable.get("types")).split(","));
                if(StringUtil.isEmpty(one)){
                    one ="joinTypes0";
                }else{
                    if(StringUtil.isEmpty(two)){
                        two ="joinTypes0";
                    }
                }

            }
        }

        List<Map<String, Object>> result = commonService.barSum(params);

        List<String> xAxis = new ArrayList<>();//报表x轴
        List<List<String>> yAxis = new ArrayList<>();//y轴
        List<String> legend = new ArrayList<>();//标题

        if(StringUtil.isEmpty(two)){//不包含第二列
            List<String> yAxis0 = new ArrayList<>();
            yAxis.add(yAxis0);
            legend.add("数值");
            for(Map<String, Object> map :result){
                String oneValue = String.valueOf(map.get(one));
                String value = String.valueOf(map.get("value"));
                xAxis.add(oneValue);
                yAxis0.add(value);
            }
        }else{//包含第二列
            Map<String, HashMap<String, String>> dataMap = new LinkedHashMap<>();
            if(StringUtil.isNotEmpty(two)){
                for(Map<String, Object> map :result){
                    String oneValue = String.valueOf(map.get(one));
                    String twoValue = String.valueOf(map.get(two));
                    String value = String.valueOf(map.get("value"));
                    if(!legend.contains(twoValue)){
                        legend.add(twoValue);//添加完成后 就是最全的第二列的类型
                    }
                    if(dataMap.containsKey(oneValue)){
                        dataMap.get(oneValue).put(twoValue,value);
                    }else{
                        HashMap<String, String> oneData = new HashMap<>();
                        oneData.put(twoValue,value);
                        dataMap.put(oneValue,oneData);
                    }

                }
            }

            for(int i =0; i<legend.size(); i++){
                yAxis.add(new ArrayList<String>());
            }

            Set<String> keys = dataMap.keySet();
            for(String key:keys){
                xAxis.add(key);
                HashMap<String, String> map = dataMap.get(key);
                for(int i =0; i<legend.size(); i++){
                    List<String> data = yAxis.get(i);
                    if(StringUtil.isNotEmpty(map.get(legend.get(i)))){
                        data.add(map.get(legend.get(i)));
                    }else{
                        data.add("0");
                    }
                }
            }
            System.out.println();
        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("xAxis",xAxis);
        resultMap.put("yAxis",yAxis);
        resultMap.put("legend",legend);
        return R.ok().put("data", resultMap);
    }
    
    /**
     * 柱状图统计
     */
    @RequestMapping("/barCount")
    public R barCount(@RequestParam Map<String,Object> params) {
        logger.debug("barCount方法:,,Controller:{},,params:{}",this.getClass().getName(), com.alibaba.fastjson.JSONObject.toJSONString(params));
        Boolean isJoinTableFlag =  false;//是否有级联表相关
        String one =  "";//第一优先
        String two =  "";//第二优先

        //处理thisTable和joinTable 处理内容是把json字符串转为Map并把带有,的切割为数组
            //当前表
            Map<String,Object> thisTable = JSON.parseObject(String.valueOf(params.get("thisTable")),Map.class);
            params.put("thisTable",thisTable);

            //级联表
            String joinTableString = String.valueOf(params.get("joinTable"));
            if(StringUtil.isNotEmpty(joinTableString)) {
                Map<String, Object> joinTable = JSON.parseObject(joinTableString, Map.class);
                params.put("joinTable", joinTable);
                isJoinTableFlag = true;
            }

        if(StringUtil.isNotEmpty(String.valueOf(thisTable.get("date")))){//当前表日期
            thisTable.put("date",String.valueOf(thisTable.get("date")).split(","));
            one = "thisDate0";
        }
        if(isJoinTableFlag){//级联表日期
            Map<String, Object> joinTable = (Map<String, Object>) params.get("joinTable");
            if(StringUtil.isNotEmpty(String.valueOf(joinTable.get("date")))){
                joinTable.put("date",String.valueOf(joinTable.get("date")).split(","));
                if(StringUtil.isEmpty(one)){
                    one ="joinDate0";
                }else{
                    if(StringUtil.isEmpty(two)){
                        two ="joinDate0";
                    }
                }
            }
        }
        if(StringUtil.isNotEmpty(String.valueOf(thisTable.get("string")))){//当前表字符串
            thisTable.put("string",String.valueOf(thisTable.get("string")).split(","));
            if(StringUtil.isEmpty(one)){
                one ="thisString0";
            }else{
                if(StringUtil.isEmpty(two)){
                    two ="thisString0";
                }
            }
        }
        if(isJoinTableFlag){//级联表字符串
            Map<String, Object> joinTable = (Map<String, Object>) params.get("joinTable");
            if(StringUtil.isNotEmpty(String.valueOf(joinTable.get("string")))){
                joinTable.put("string",String.valueOf(joinTable.get("string")).split(","));
                if(StringUtil.isEmpty(one)){
                    one ="joinString0";
                }else{
                    if(StringUtil.isEmpty(two)){
                        two ="joinString0";
                    }
                }
            }
        }
        if(StringUtil.isNotEmpty(String.valueOf(thisTable.get("types")))){//当前表类型
            thisTable.put("types",String.valueOf(thisTable.get("types")).split(","));
            if(StringUtil.isEmpty(one)){
                one ="thisTypes0";
            }else{
                if(StringUtil.isEmpty(two)){
                    two ="thisTypes0";
                }
            }
        }
        if(isJoinTableFlag){//级联表类型
            Map<String, Object> joinTable = (Map<String, Object>) params.get("joinTable");
            if(StringUtil.isNotEmpty(String.valueOf(joinTable.get("types")))){
                joinTable.put("types",String.valueOf(joinTable.get("types")).split(","));
                if(StringUtil.isEmpty(one)){
                    one ="joinTypes0";
                }else{
                    if(StringUtil.isEmpty(two)){
                        two ="joinTypes0";
                    }
                }

            }
        }

        List<Map<String, Object>> result = commonService.barCount(params);

        List<String> xAxis = new ArrayList<>();//报表x轴
        List<List<String>> yAxis = new ArrayList<>();//y轴
        List<String> legend = new ArrayList<>();//标题

        if(StringUtil.isEmpty(two)){//不包含第二列
            List<String> yAxis0 = new ArrayList<>();
            yAxis.add(yAxis0);
            legend.add("数值");
            for(Map<String, Object> map :result){
                String oneValue = String.valueOf(map.get(one));
                String value = String.valueOf(map.get("value"));
                xAxis.add(oneValue);
                yAxis0.add(value);
            }
        }else{//包含第二列
            Map<String, HashMap<String, String>> dataMap = new LinkedHashMap<>();
            if(StringUtil.isNotEmpty(two)){
                for(Map<String, Object> map :result){
                    String oneValue = String.valueOf(map.get(one));
                    String twoValue = String.valueOf(map.get(two));
                    String value = String.valueOf(map.get("value"));
                    if(!legend.contains(twoValue)){
                        legend.add(twoValue);//添加完成后 就是最全的第二列的类型
                    }
                    if(dataMap.containsKey(oneValue)){
                        dataMap.get(oneValue).put(twoValue,value);
                    }else{
                        HashMap<String, String> oneData = new HashMap<>();
                        oneData.put(twoValue,value);
                        dataMap.put(oneValue,oneData);
                    }

                }
            }

            for(int i =0; i<legend.size(); i++){
                yAxis.add(new ArrayList<String>());
            }

            Set<String> keys = dataMap.keySet();
            for(String key:keys){
                xAxis.add(key);
                HashMap<String, String> map = dataMap.get(key);
                for(int i =0; i<legend.size(); i++){
                    List<String> data = yAxis.get(i);
                    if(StringUtil.isNotEmpty(map.get(legend.get(i)))){
                        data.add(map.get(legend.get(i)));
                    }else{
                        data.add("0");
                    }
                }
            }
            System.out.println();
        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("xAxis",xAxis);
        resultMap.put("yAxis",yAxis);
        resultMap.put("legend",legend);
        return R.ok().put("data", resultMap);
    }
}
View Code

ConfigController

package com.controller;


import java.util.Arrays;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.annotation.IgnoreAuth;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.entity.ConfigEntity;
import com.service.ConfigService;
import com.utils.PageUtils;
import com.utils.R;
import com.utils.ValidatorUtils;

/**
 * 登录相关
 */
@RequestMapping("config")
@RestController
public class ConfigController{
    
    @Autowired
    private ConfigService configService;

    /**
     * 列表
     */
    @RequestMapping("/page")
    public R page(@RequestParam Map<String, Object> params,ConfigEntity config){
        EntityWrapper<ConfigEntity> ew = new EntityWrapper<ConfigEntity>();
        PageUtils page = configService.queryPage(params);
        return R.ok().put("data", page);
    }
    
    /**
     * 列表
     */
    @IgnoreAuth
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params,ConfigEntity config){
        EntityWrapper<ConfigEntity> ew = new EntityWrapper<ConfigEntity>();
        PageUtils page = configService.queryPage(params);
        return R.ok().put("data", page);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") String id){
        ConfigEntity config = configService.selectById(id);
        return R.ok().put("data", config);
    }
    
    /**
     * 详情
     */
    @IgnoreAuth
    @RequestMapping("/detail/{id}")
    public R detail(@PathVariable("id") String id){
        ConfigEntity config = configService.selectById(id);
        return R.ok().put("data", config);
    }
    
    /**
     * 根据name获取信息
     */
    @RequestMapping("/info")
    public R infoByName(@RequestParam String name){
        ConfigEntity config = configService.selectOne(new EntityWrapper<ConfigEntity>().eq("name", "faceFile"));
        return R.ok().put("data", config);
    }
    
    /**
     * 保存
     */
    @PostMapping("/save")
    public R save(@RequestBody ConfigEntity config){
//        ValidatorUtils.validateEntity(config);
        configService.insert(config);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody ConfigEntity config){
//        ValidatorUtils.validateEntity(config);
        configService.updateById(config);//全部更新
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids){
        configService.deleteBatchIds(Arrays.asList(ids));
        return R.ok();
    }
}
View Code

DictionaryController

package com.controller;

import java.io.File;
import java.math.BigDecimal;
import java.net.URL;
import java.text.SimpleDateFormat;
import com.alibaba.fastjson.JSONObject;
import java.util.*;
import org.springframework.beans.BeanUtils;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.ContextLoader;
import javax.servlet.ServletContext;
import com.service.TokenService;
import com.utils.*;
import java.lang.reflect.InvocationTargetException;

import com.service.DictionaryService;
import org.apache.commons.lang3.StringUtils;
import com.annotation.IgnoreAuth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.entity.*;
import com.entity.view.*;
import com.service.*;
import com.utils.PageUtils;
import com.utils.R;
import com.alibaba.fastjson.*;

/**
 * 字典表
 * 后端接口
 * @author
 * @email
*/
@RestController
@Controller
@RequestMapping("/dictionary")
public class DictionaryController {
    private static final Logger logger = LoggerFactory.getLogger(DictionaryController.class);

    @Autowired
    private DictionaryService dictionaryService;


    @Autowired
    private TokenService tokenService;

    //级联表service

    @Autowired
    private YonghuService yonghuService;


    /**
    * 后端列表
    */
    @RequestMapping("/page")
    @IgnoreAuth
    public R page(@RequestParam Map<String, Object> params, HttpServletRequest request){
        logger.debug("page方法:,,Controller:{},,params:{}",this.getClass().getName(),JSONObject.toJSONString(params));
        if(params.get("orderBy")==null || params.get("orderBy")==""){
            params.put("orderBy","id");
        }
        PageUtils page = dictionaryService.queryPage(params);

        //字典表数据转换
        List<DictionaryView> list =(List<DictionaryView>)page.getList();
        for(DictionaryView c:list){
            //修改对应字典表字段
            dictionaryService.dictionaryConvert(c, request);
        }
        return R.ok().put("data", page);
    }

    /**
    * 后端详情
    */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id, HttpServletRequest request){
        logger.debug("info方法:,,Controller:{},,id:{}",this.getClass().getName(),id);
        DictionaryEntity dictionary = dictionaryService.selectById(id);
        if(dictionary !=null){
            //entity转view
            DictionaryView view = new DictionaryView();
            BeanUtils.copyProperties( dictionary , view );//把实体数据重构到view中

            //修改对应字典表字段
            dictionaryService.dictionaryConvert(view, request);
            return R.ok().put("data", view);
        }else {
            return R.error(511,"查不到数据");
        }

    }

    /**
    * 后端保存
    */
    @RequestMapping("/save")
    public R save(@RequestBody DictionaryEntity dictionary, HttpServletRequest request){
        logger.debug("save方法:,,Controller:{},,dictionary:{}",this.getClass().getName(),dictionary.toString());

        String role = String.valueOf(request.getSession().getAttribute("role"));
        if(StringUtil.isEmpty(role))
            return R.error(511,"权限为空");

        Wrapper<DictionaryEntity> queryWrapper = new EntityWrapper<DictionaryEntity>()
            .eq("dic_code", dictionary.getDicCode())
            .eq("index_name", dictionary.getIndexName())
            ;
        if(dictionary.getDicCode().contains("_erji_types")){
            queryWrapper.eq("super_id",dictionary.getSuperId());
        }

        logger.info("sql语句:"+queryWrapper.getSqlSegment());
        DictionaryEntity dictionaryEntity = dictionaryService.selectOne(queryWrapper);
        if(dictionaryEntity==null){
            dictionary.setCreateTime(new Date());
            dictionaryService.insert(dictionary);
            //字典表新增数据,把数据再重新查出,放入监听器中
            List<DictionaryEntity> dictionaryEntities = dictionaryService.selectList(new EntityWrapper<DictionaryEntity>());
            ServletContext servletContext = request.getServletContext();
            Map<String, Map<Integer,String>> map = new HashMap<>();
            for(DictionaryEntity d :dictionaryEntities){
                Map<Integer, String> m = map.get(d.getDicCode());
                if(m ==null || m.isEmpty()){
                    m = new HashMap<>();
                }
                m.put(d.getCodeIndex(),d.getIndexName());
                map.put(d.getDicCode(),m);
            }
            servletContext.setAttribute("dictionaryMap",map);
            return R.ok();
        }else {
            return R.error(511,"表中有相同数据");
        }
    }

    /**
    * 后端修改
    */
    @RequestMapping("/update")
    public R update(@RequestBody DictionaryEntity dictionary, HttpServletRequest request){
        logger.debug("update方法:,,Controller:{},,dictionary:{}",this.getClass().getName(),dictionary.toString());

        String role = String.valueOf(request.getSession().getAttribute("role"));
//        if(StringUtil.isEmpty(role))
//            return R.error(511,"权限为空");
        //根据字段查询是否有相同数据
        Wrapper<DictionaryEntity> queryWrapper = new EntityWrapper<DictionaryEntity>()
            .notIn("id",dictionary.getId())
            .eq("dic_code", dictionary.getDicCode())
            .eq("index_name", dictionary.getIndexName())
            ;

        if(dictionary.getDicCode().contains("_erji_types")){
            queryWrapper.eq("super_id",dictionary.getSuperId());
        }
        logger.info("sql语句:"+queryWrapper.getSqlSegment());
        DictionaryEntity dictionaryEntity = dictionaryService.selectOne(queryWrapper);
        if(dictionaryEntity==null){
            dictionaryService.updateById(dictionary);//根据id更新
            //如果字典表修改数据的话,把数据再重新查出,放入监听器中
            List<DictionaryEntity> dictionaryEntities = dictionaryService.selectList(new EntityWrapper<DictionaryEntity>());
            ServletContext servletContext = request.getServletContext();
            Map<String, Map<Integer,String>> map = new HashMap<>();
            for(DictionaryEntity d :dictionaryEntities){
                Map<Integer, String> m = map.get(d.getDicCode());
                if(m ==null || m.isEmpty()){
                    m = new HashMap<>();
                }
                m.put(d.getCodeIndex(),d.getIndexName());
                map.put(d.getDicCode(),m);
            }
            servletContext.setAttribute("dictionaryMap",map);
            return R.ok();
        }else {
            return R.error(511,"表中有相同数据");
        }
    }

    /**
    * 删除
    */
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] ids){
        logger.debug("delete:,,Controller:{},,ids:{}",this.getClass().getName(),ids.toString());
        dictionaryService.deleteBatchIds(Arrays.asList(ids));
        return R.ok();
    }

    /**
     * 最大值
     */
    @RequestMapping("/maxCodeIndex")
    public R maxCodeIndex(@RequestBody DictionaryEntity dictionary){
        logger.debug("maxCodeIndex:,,Controller:{},,dictionary:{}",this.getClass().getName(),dictionary.toString());
        List<String> descs = new ArrayList<>();
        descs.add("code_index");
        Wrapper<DictionaryEntity> queryWrapper = new EntityWrapper<DictionaryEntity>()
                .eq("dic_code", dictionary.getDicCode())
                .orderDesc(descs);
        logger.info("sql语句:"+queryWrapper.getSqlSegment());
        List<DictionaryEntity> dictionaryEntityList = dictionaryService.selectList(queryWrapper);
        if(dictionaryEntityList != null ){
            return R.ok().put("maxCodeIndex",dictionaryEntityList.get(0).getCodeIndex()+1);
        }else{
            return R.ok().put("maxCodeIndex",1);
        }
    }

    /**
     * 批量上传
     */
    @RequestMapping("/batchInsert")
    public R save( String fileName){
        logger.debug("batchInsert方法:,,Controller:{},,fileName:{}",this.getClass().getName(),fileName);
        try {
            List<DictionaryEntity> dictionaryList = new ArrayList<>();//上传的东西
            Map<String, List<String>> seachFields= new HashMap<>();//要查询的字段
            Date date = new Date();
            int lastIndexOf = fileName.lastIndexOf(".");
            if(lastIndexOf == -1){
                return R.error(511,"该文件没有后缀");
            }else{
                String suffix = fileName.substring(lastIndexOf);
                if(!".xls".equals(suffix)){
                    return R.error(511,"只支持后缀为xls的excel文件");
                }else{
                    URL resource = this.getClass().getClassLoader().getResource("static/upload/" + fileName);//获取文件路径
                    File file = new File(resource.getFile());
                    if(!file.exists()){
                        return R.error(511,"找不到上传文件,请联系管理员");
                    }else{
                        List<List<String>> dataList = PoiUtil.poiImport(file.getPath());//读取xls文件
                        dataList.remove(0);//删除第一行,因为第一行是提示
                        for(List<String> data:dataList){
                            //循环
                            DictionaryEntity dictionaryEntity = new DictionaryEntity();
//                            dictionaryEntity.setDicCode(data.get(0));                    //字段 要改的
//                            dictionaryEntity.setDicName(data.get(0));                    //字段名 要改的
//                            dictionaryEntity.setCodeIndex(Integer.valueOf(data.get(0)));   //编码 要改的
//                            dictionaryEntity.setIndexName(data.get(0));                    //编码名字 要改的
//                            dictionaryEntity.setSuperId(Integer.valueOf(data.get(0)));   //父字段id 要改的
//                            dictionaryEntity.setBeizhu(data.get(0));                    //备注 要改的
//                            dictionaryEntity.setCreateTime(date);//时间
                            dictionaryList.add(dictionaryEntity);


                            //把要查询是否重复的字段放入map中
                        }

                        //查询是否重复
                        dictionaryService.insertBatch(dictionaryList);
                        return R.ok();
                    }
                }
            }
        }catch (Exception e){
            return R.error(511,"批量插入数据异常,请联系管理员");
        }
    }






}
View Code

FileController

package com.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.annotation.IgnoreAuth;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.entity.ConfigEntity;
import com.entity.EIException;
import com.service.ConfigService;
import com.utils.R;

/**
 * 上传文件映射表
 */
@RestController
@RequestMapping("file")
@SuppressWarnings({"unchecked","rawtypes"})
public class FileController{
    @Autowired
    private ConfigService configService;
    /**
     * 上传文件
     */
    @RequestMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file, String type,HttpServletRequest request) throws Exception {
        if (file.isEmpty()) {
            throw new EIException("上传文件不能为空");
        }
        String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
        String fileName = new Date().getTime()+"."+fileExt;
        File dest = new File(request.getSession().getServletContext().getRealPath("/upload")+"/"+fileName);
        file.transferTo(dest);
        if(StringUtils.isNotBlank(type) && type.equals("1")) {
            ConfigEntity configEntity = configService.selectOne(new EntityWrapper<ConfigEntity>().eq("name", "faceFile"));
            if(configEntity==null) {
                configEntity = new ConfigEntity();
                configEntity.setName("faceFile");
                configEntity.setValue(fileName);
            } else {
                configEntity.setValue(fileName);
            }
            configService.insertOrUpdate(configEntity);
        }
        return R.ok().put("file", fileName);
    }
    
    /**
     * 下载文件
     */
    @IgnoreAuth
    @RequestMapping("/download")
    public void download(@RequestParam String fileName, HttpServletRequest request, HttpServletResponse response) {
        try {
            File file = new File(request.getSession().getServletContext().getRealPath("/upload")+"/"+fileName);
            if (file.exists()) {
                response.reset();
                response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName+"\"");
                response.setHeader("Cache-Control", "no-cache");
                response.setHeader("Access-Control-Allow-Credentials", "true");
                response.setContentType("application/octet-stream; charset=UTF-8");
                IOUtils.write(FileUtils.readFileToByteArray(file), response.getOutputStream());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
}
View Code

UsersController

package com.controller;


import java.util.Arrays;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.annotation.IgnoreAuth;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.entity.UsersEntity;
import com.service.TokenService;
import com.utils.MPUtil;
import com.utils.PageUtils;
import com.utils.R;

/**
 * 登录相关
 */
@RequestMapping("users")
@RestController
public class UsersController {
    
    @Autowired
    private UsersService usersService;
    
    @Autowired
    private TokenService tokenService;

    /**
     * 登录
     */
    @IgnoreAuth
    @PostMapping(value = "/login")
    public R login(String username, String password, String captcha, HttpServletRequest request) {
        UsersEntity user = usersService.selectOne(new EntityWrapper<UsersEntity>().eq("username", username));
        if(user==null || !user.getPassword().equals(password)) {
            return R.error("账号或密码不正确");
        }
        String token = tokenService.generateToken(user.getId(),username, "users", user.getRole());
        R r = R.ok();
        r.put("token", token);
        r.put("role",user.getRole());
        r.put("userId",user.getId());
        return r;
    }
    
    /**
     * 注册
     */
    @IgnoreAuth
    @PostMapping(value = "/register")
    public R register(@RequestBody UsersEntity user){
//        ValidatorUtils.validateEntity(user);
        if(usersService.selectOne(new EntityWrapper<UsersEntity>().eq("username", user.getUsername())) !=null) {
            return R.error("用户已存在");
        }
        usersService.insert(user);
        return R.ok();
    }

    /**
     * 退出
     */
    @GetMapping(value = "logout")
    public R logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return R.ok("退出成功");
    }
    
    /**
     * 密码重置
     */
    @IgnoreAuth
    @RequestMapping(value = "/resetPass")
    public R resetPass(String username, HttpServletRequest request){
        UsersEntity user = usersService.selectOne(new EntityWrapper<UsersEntity>().eq("username", username));
        if(user==null) {
            return R.error("账号不存在");
        }
        user.setPassword("123456");
        usersService.update(user,null);
        return R.ok("密码已重置为:123456");
    }
    
    /**
     * 列表
     */
    @RequestMapping("/page")
    public R page(@RequestParam Map<String, Object> params,UsersEntity user){
        EntityWrapper<UsersEntity> ew = new EntityWrapper<UsersEntity>();
        PageUtils page = usersService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.allLike(ew, user), params), params));
        return R.ok().put("data", page);
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list( UsersEntity user){
           EntityWrapper<UsersEntity> ew = new EntityWrapper<UsersEntity>();
          ew.allEq(MPUtil.allEQMapPre( user, "user")); 
        return R.ok().put("data", usersService.selectListView(ew));
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") String id){
        UsersEntity user = usersService.selectById(id);
        return R.ok().put("data", user);
    }
    
    /**
     * 获取用户的session用户信息
     */
    @RequestMapping("/session")
    public R getCurrUser(HttpServletRequest request){
        Integer id = (Integer)request.getSession().getAttribute("userId");
        UsersEntity user = usersService.selectById(id);
        return R.ok().put("data", user);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    public R save(@RequestBody UsersEntity user){
//        ValidatorUtils.validateEntity(user);
        if(usersService.selectOne(new EntityWrapper<UsersEntity>().eq("username", user.getUsername())) !=null) {
            return R.error("用户已存在");
        }
        user.setPassword("123456");
        usersService.insert(user);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody UsersEntity user){
//        ValidatorUtils.validateEntity(user);
        usersService.updateById(user);//全部更新
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids){
        usersService.deleteBatchIds(Arrays.asList(ids));
        return R.ok();
    }
}
View Code

WuziChuruInoutController

package com.controller;

import java.io.File;
import java.math.BigDecimal;
import java.net.URL;
import java.text.SimpleDateFormat;
import com.alibaba.fastjson.JSONObject;
import java.util.*;
import org.springframework.beans.BeanUtils;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.ContextLoader;
import javax.servlet.ServletContext;
import com.service.TokenService;
import com.utils.*;
import java.lang.reflect.InvocationTargetException;

import com.service.DictionaryService;
import org.apache.commons.lang3.StringUtils;
import com.annotation.IgnoreAuth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.entity.*;
import com.entity.view.*;
import com.service.*;
import com.utils.PageUtils;
import com.utils.R;
import com.alibaba.fastjson.*;

/**
 * 出入库
 * 后端接口
 * @author
 * @email
*/
@RestController
@Controller
@RequestMapping("/wuziChuruInout")
public class WuziChuruInoutController {
    private static final Logger logger = LoggerFactory.getLogger(WuziChuruInoutController.class);

    @Autowired
    private WuziChuruInoutService wuziChuruInoutService;


    @Autowired
    private TokenService tokenService;
    @Autowired
    private DictionaryService dictionaryService;

    //级联表service

    // 列表详情的表级联service
    @Autowired
    private WuziChuruInoutListService wuziChuruInoutListService;
//    @Autowired
//    private YonghuService yonghuService;
    @Autowired
    private WuziService wuziService;
    @Autowired
    private YonghuService yonghuService;


    /**
    * 后端列表
    */
    @RequestMapping("/page")
    public R page(@RequestParam Map<String, Object> params, HttpServletRequest request){
        logger.debug("page方法:,,Controller:{},,params:{}",this.getClass().getName(),JSONObject.toJSONString(params));
        String role = String.valueOf(request.getSession().getAttribute("role"));
        if(StringUtil.isEmpty(role))
            return R.error(511,"权限为空");
        else if("员工".equals(role))
            params.put("yonghuId",request.getSession().getAttribute("userId"));
        if(params.get("orderBy")==null || params.get("orderBy")==""){
            params.put("orderBy","id");
        }
        PageUtils page = wuziChuruInoutService.queryPage(params);

        //字典表数据转换
        List<WuziChuruInoutView> list =(List<WuziChuruInoutView>)page.getList();
        for(WuziChuruInoutView c:list){
            //修改对应字典表字段
            dictionaryService.dictionaryConvert(c, request);
        }
        return R.ok().put("data", page);
    }

    /**
    * 后端详情
    */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id, HttpServletRequest request){
        logger.debug("info方法:,,Controller:{},,id:{}",this.getClass().getName(),id);
        WuziChuruInoutEntity wuziChuruInout = wuziChuruInoutService.selectById(id);
        if(wuziChuruInout !=null){
            //entity转view
            WuziChuruInoutView view = new WuziChuruInoutView();
            BeanUtils.copyProperties( wuziChuruInout , view );//把实体数据重构到view中

            //修改对应字典表字段
            dictionaryService.dictionaryConvert(view, request);
            return R.ok().put("data", view);
        }else {
            return R.error(511,"查不到数据");
        }

    }

    /**
    * 后端保存
    */
    @RequestMapping("/save")
    public R save(@RequestBody WuziChuruInoutEntity wuziChuruInout, HttpServletRequest request){
        logger.debug("save方法:,,Controller:{},,wuziChuruInout:{}",this.getClass().getName(),wuziChuruInout.toString());

        String role = String.valueOf(request.getSession().getAttribute("role"));
        if(StringUtil.isEmpty(role))
            return R.error(511,"权限为空");

        Wrapper<WuziChuruInoutEntity> queryWrapper = new EntityWrapper<WuziChuruInoutEntity>()
            .eq("wuzi_churu_inout_uuid_number", wuziChuruInout.getWuziChuruInoutUuidNumber())
            .eq("wuzi_churu_inout_name", wuziChuruInout.getWuziChuruInoutName())
            .eq("wuzi_churu_inout_types", wuziChuruInout.getWuziChuruInoutTypes())
            ;

        logger.info("sql语句:"+queryWrapper.getSqlSegment());
        WuziChuruInoutEntity wuziChuruInoutEntity = wuziChuruInoutService.selectOne(queryWrapper);
        if(wuziChuruInoutEntity==null){
            wuziChuruInout.setInsertTime(new Date());
            wuziChuruInout.setCreateTime(new Date());
            wuziChuruInoutService.insert(wuziChuruInout);
            return R.ok();
        }else {
            return R.error(511,"表中有相同数据");
        }
    }

    /**
    * 后端修改
    */
    @RequestMapping("/update")
    public R update(@RequestBody WuziChuruInoutEntity wuziChuruInout, HttpServletRequest request){
        logger.debug("update方法:,,Controller:{},,wuziChuruInout:{}",this.getClass().getName(),wuziChuruInout.toString());

        String role = String.valueOf(request.getSession().getAttribute("role"));
//        if(StringUtil.isEmpty(role))
//            return R.error(511,"权限为空");
        //根据字段查询是否有相同数据
        Wrapper<WuziChuruInoutEntity> queryWrapper = new EntityWrapper<WuziChuruInoutEntity>()
            .notIn("id",wuziChuruInout.getId())
            .andNew()
            .eq("wuzi_churu_inout_uuid_number", wuziChuruInout.getWuziChuruInoutUuidNumber())
            .eq("wuzi_churu_inout_name", wuziChuruInout.getWuziChuruInoutName())
            .eq("wuzi_churu_inout_types", wuziChuruInout.getWuziChuruInoutTypes())
            ;

        logger.info("sql语句:"+queryWrapper.getSqlSegment());
        WuziChuruInoutEntity wuziChuruInoutEntity = wuziChuruInoutService.selectOne(queryWrapper);
        if(wuziChuruInoutEntity==null){
            wuziChuruInoutService.updateById(wuziChuruInout);//根据id更新
            return R.ok();
        }else {
            return R.error(511,"表中有相同数据");
        }
    }
    /**
    * 出库
    */
    @RequestMapping("/outWuziChuruInoutList")
    public R outWuziChuruInoutList(@RequestBody  Map<String, Object> params,HttpServletRequest request){
        logger.debug("outWuziChuruInoutList方法:,,Controller:{},,params:{}",this.getClass().getName(),JSONObject.toJSONString(params));

        String role = String.valueOf(request.getSession().getAttribute("role"));
        if(StringUtil.isEmpty(role))
            return R.error(511,"权限为空");

        //取出入库名称并判断是否存在
        String wuziChuruInoutName = String.valueOf(params.get("wuziChuruInoutName"));
        Wrapper<WuziChuruInoutEntity> queryWrapper = new EntityWrapper<WuziChuruInoutEntity>()
            .eq("wuzi_churu_inout_name", wuziChuruInoutName)
            ;
        WuziChuruInoutEntity wuziChuruInoutSelectOne = wuziChuruInoutService.selectOne(queryWrapper);
        if(wuziChuruInoutSelectOne != null)
            return R.error(511,"出入库名称已被使用");


    //取当前表的级联表并判断是否前台传入

        Map<String, Integer> map = (Map<String, Integer>) params.get("map");
        if(map == null || map.size() == 0)
            return R.error(511,"列表内容不能为空");


        Set<String> ids = map.keySet();

        List<WuziEntity> wuziList = wuziService.selectBatchIds(ids);
        if(wuziList == null || wuziList.size() == 0){
            return R.error(511,"查数据库查不到数据");
        }else{
            for(WuziEntity w:wuziList){
                Integer value = w.getWuziKucunNumber()-map.get(String.valueOf(w.getId()));
                if(value <0){
                    return R.error(511,"出库数量大于库存数量");
                }
                w.setWuziKucunNumber(value);
            }
        }

        //当前表
        WuziChuruInoutEntity wuziChuruInoutEntity = new WuziChuruInoutEntity<>();
            wuziChuruInoutEntity.setWuziChuruInoutUuidNumber(String.valueOf(new Date().getTime()));
            wuziChuruInoutEntity.setWuziChuruInoutName(wuziChuruInoutName);
            wuziChuruInoutEntity.setWuziChuruInoutTypes(1);
            wuziChuruInoutEntity.setWuziChuruInoutContent("");
            wuziChuruInoutEntity.setInsertTime(new Date());
            wuziChuruInoutEntity.setCreateTime(new Date());

        boolean insertWuziChuruInout = wuziChuruInoutService.insert(wuziChuruInoutEntity);
        if(insertWuziChuruInout){
            //级联表
            ArrayList<WuziChuruInoutListEntity> wuziChuruInoutLists = new ArrayList<>();
            for(String id:ids){
                WuziChuruInoutListEntity wuziChuruInoutListEntity = new WuziChuruInoutListEntity();
                    wuziChuruInoutListEntity.setWuziChuruInoutId(wuziChuruInoutEntity.getId());
                    wuziChuruInoutListEntity.setWuziId(Integer.valueOf(id));
                    wuziChuruInoutListEntity.setWuziChuruInoutListNumber(map.get(id));
                    wuziChuruInoutListEntity.setInsertTime(new Date());
                    wuziChuruInoutListEntity.setCreateTime(new Date());
                wuziChuruInoutLists.add(wuziChuruInoutListEntity);
                wuziService.updateBatchById(wuziList);
            }
            wuziChuruInoutListService.insertBatch(wuziChuruInoutLists);
        }
        return R.ok();
    }

    /**
    *入库
    */
    @RequestMapping("/inWuziChuruInoutList")
    public R inWuziChuruInoutList(@RequestBody  Map<String, Object> params,HttpServletRequest request){
        logger.debug("inWuziChuruInoutList方法:,,Controller:{},,params:{}",this.getClass().getName(),JSONObject.toJSONString(params));
        //params:{"map":{"1":2,"2":3},"wuziOutinName":"订单1"}

        String role = String.valueOf(request.getSession().getAttribute("role"));
        if(StringUtil.isEmpty(role))
            return R.error(511,"权限为空");

        //取当前表名称并判断
        String wuziChuruInoutName = String.valueOf(params.get("wuziChuruInoutName"));
        Wrapper<WuziChuruInoutEntity> queryWrapper = new EntityWrapper<WuziChuruInoutEntity>()
            .eq("wuzi_churu_inout_name", wuziChuruInoutName)
            ;
        WuziChuruInoutEntity wuziChuruInoutSelectOne = wuziChuruInoutService.selectOne(queryWrapper);
        if(wuziChuruInoutSelectOne != null)
            return R.error(511,"出入库名称已被使用");


        //取当前表的级联表并判断是否前台传入

        Map<String, Integer> map = (Map<String, Integer>) params.get("map");
        if(map == null || map.size() == 0)
            return R.error(511,"列表内容不能为空");

        Set<String> ids = map.keySet();

        List<WuziEntity> wuziList = wuziService.selectBatchIds(ids);
        if(wuziList == null || wuziList.size() == 0){
            return R.error(511,"查数据库查不到数据");
        }else{
            for(WuziEntity w:wuziList){
                w.setWuziKucunNumber(w.getWuziKucunNumber()+map.get(String.valueOf(w.getId())));
            }
        }

        //当前表
        WuziChuruInoutEntity wuziChuruInoutEntity = new WuziChuruInoutEntity<>();
            wuziChuruInoutEntity.setWuziChuruInoutUuidNumber(String.valueOf(new Date().getTime()));
            wuziChuruInoutEntity.setWuziChuruInoutName(wuziChuruInoutName);
            wuziChuruInoutEntity.setWuziChuruInoutTypes(2);
            wuziChuruInoutEntity.setWuziChuruInoutContent("");
            wuziChuruInoutEntity.setInsertTime(new Date());
            wuziChuruInoutEntity.setCreateTime(new Date());


        boolean insertWuziChuruInout = wuziChuruInoutService.insert(wuziChuruInoutEntity);
        if(insertWuziChuruInout){
            //级联表
            ArrayList<WuziChuruInoutListEntity> wuziChuruInoutLists = new ArrayList<>();
            for(String id:ids){
                WuziChuruInoutListEntity wuziChuruInoutListEntity = new WuziChuruInoutListEntity();
                wuziChuruInoutListEntity.setWuziChuruInoutId(wuziChuruInoutEntity.getId());
                wuziChuruInoutListEntity.setWuziId(Integer.valueOf(id));
                wuziChuruInoutListEntity.setWuziChuruInoutListNumber(map.get(id));
                wuziChuruInoutListEntity.setInsertTime(new Date());
                wuziChuruInoutListEntity.setCreateTime(new Date());
                wuziChuruInoutLists.add(wuziChuruInoutListEntity);
                wuziService.updateBatchById(wuziList);
            }
            wuziChuruInoutListService.insertBatch(wuziChuruInoutLists);
        }

        return R.ok();
    }
    /**
    * 删除
    */
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] ids){
        logger.debug("delete:,,Controller:{},,ids:{}",this.getClass().getName(),ids.toString());
        wuziChuruInoutService.deleteBatchIds(Arrays.asList(ids));
        wuziChuruInoutListService.delete(new EntityWrapper<WuziChuruInoutListEntity>().in("wuzi_churu_inout_id",ids));
        return R.ok();
    }


    /**
     * 批量上传
     */
    @RequestMapping("/batchInsert")
    public R save( String fileName){
        logger.debug("batchInsert方法:,,Controller:{},,fileName:{}",this.getClass().getName(),fileName);
        try {
            List<WuziChuruInoutEntity> wuziChuruInoutList = new ArrayList<>();//上传的东西
            Map<String, List<String>> seachFields= new HashMap<>();//要查询的字段
            Date date = new Date();
            int lastIndexOf = fileName.lastIndexOf(".");
            if(lastIndexOf == -1){
                return R.error(511,"该文件没有后缀");
            }else{
                String suffix = fileName.substring(lastIndexOf);
                if(!".xls".equals(suffix)){
                    return R.error(511,"只支持后缀为xls的excel文件");
                }else{
                    URL resource = this.getClass().getClassLoader().getResource("static/upload/" + fileName);//获取文件路径
                    File file = new File(resource.getFile());
                    if(!file.exists()){
                        return R.error(511,"找不到上传文件,请联系管理员");
                    }else{
                        List<List<String>> dataList = PoiUtil.poiImport(file.getPath());//读取xls文件
                        dataList.remove(0);//删除第一行,因为第一行是提示
                        for(List<String> data:dataList){
                            //循环
                            WuziChuruInoutEntity wuziChuruInoutEntity = new WuziChuruInoutEntity();
//                            wuziChuruInoutEntity.setWuziChuruInoutUuidNumber(data.get(0));                    //出入库流水号 要改的
//                            wuziChuruInoutEntity.setWuziChuruInoutName(data.get(0));                    //出入库名称 要改的
//                            wuziChuruInoutEntity.setWuziChuruInoutTypes(Integer.valueOf(data.get(0)));   //出入库类型 要改的
//                            wuziChuruInoutEntity.setWuziChuruInoutContent("");//照片
//                            wuziChuruInoutEntity.setInsertTime(date);//时间
//                            wuziChuruInoutEntity.setCreateTime(date);//时间
                            wuziChuruInoutList.add(wuziChuruInoutEntity);


                            //把要查询是否重复的字段放入map中
                                //出入库流水号
                                if(seachFields.containsKey("wuziChuruInoutUuidNumber")){
                                    List<String> wuziChuruInoutUuidNumber = seachFields.get("wuziChuruInoutUuidNumber");
                                    wuziChuruInoutUuidNumber.add(data.get(0));//要改的
                                }else{
                                    List<String> wuziChuruInoutUuidNumber = new ArrayList<>();
                                    wuziChuruInoutUuidNumber.add(data.get(0));//要改的
                                    seachFields.put("wuziChuruInoutUuidNumber",wuziChuruInoutUuidNumber);
                                }
                        }

                        //查询是否重复
                         //出入库流水号
                        List<WuziChuruInoutEntity> wuziChuruInoutEntities_wuziChuruInoutUuidNumber = wuziChuruInoutService.selectList(new EntityWrapper<WuziChuruInoutEntity>().in("wuzi_churu_inout_uuid_number", seachFields.get("wuziChuruInoutUuidNumber")));
                        if(wuziChuruInoutEntities_wuziChuruInoutUuidNumber.size() >0 ){
                            ArrayList<String> repeatFields = new ArrayList<>();
                            for(WuziChuruInoutEntity s:wuziChuruInoutEntities_wuziChuruInoutUuidNumber){
                                repeatFields.add(s.getWuziChuruInoutUuidNumber());
                            }
                            return R.error(511,"数据库的该表中的 [出入库流水号] 字段已经存在 存在数据为:"+repeatFields.toString());
                        }
                        wuziChuruInoutService.insertBatch(wuziChuruInoutList);
                        return R.ok();
                    }
                }
            }
        }catch (Exception e){
            return R.error(511,"批量插入数据异常,请联系管理员");
        }
    }






}
View Code

WuziChuruInoutListController

package com.controller;

import java.io.File;
import java.math.BigDecimal;
import java.net.URL;
import java.text.SimpleDateFormat;
import com.alibaba.fastjson.JSONObject;
import java.util.*;
import org.springframework.beans.BeanUtils;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.ContextLoader;
import javax.servlet.ServletContext;
import com.service.TokenService;
import com.utils.*;
import java.lang.reflect.InvocationTargetException;

import com.service.DictionaryService;
import org.apache.commons.lang3.StringUtils;
import com.annotation.IgnoreAuth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.entity.*;
import com.entity.view.*;
import com.service.*;
import com.utils.PageUtils;
import com.utils.R;
import com.alibaba.fastjson.*;

/**
 * 出入库详情
 * 后端接口
 * @author
 * @email
*/
@RestController
@Controller
@RequestMapping("/wuziChuruInoutList")
public class WuziChuruInoutListController {
    private static final Logger logger = LoggerFactory.getLogger(WuziChuruInoutListController.class);

    @Autowired
    private WuziChuruInoutListService wuziChuruInoutListService;


    @Autowired
    private TokenService tokenService;
    @Autowired
    private DictionaryService dictionaryService;

    //级联表service
    @Autowired
    private WuziService wuziService;
    @Autowired
    private WuziChuruInoutService wuziChuruInoutService;

    @Autowired
    private YonghuService yonghuService;


    /**
    * 后端列表
    */
    @RequestMapping("/page")
    public R page(@RequestParam Map<String, Object> params, HttpServletRequest request){
        logger.debug("page方法:,,Controller:{},,params:{}",this.getClass().getName(),JSONObject.toJSONString(params));
        String role = String.valueOf(request.getSession().getAttribute("role"));
        if(StringUtil.isEmpty(role))
            return R.error(511,"权限为空");
        else if("员工".equals(role))
            params.put("yonghuId",request.getSession().getAttribute("userId"));
        if(params.get("orderBy")==null || params.get("orderBy")==""){
            params.put("orderBy","id");
        }
        PageUtils page = wuziChuruInoutListService.queryPage(params);

        //字典表数据转换
        List<WuziChuruInoutListView> list =(List<WuziChuruInoutListView>)page.getList();
        for(WuziChuruInoutListView c:list){
            //修改对应字典表字段
            dictionaryService.dictionaryConvert(c, request);
        }
        return R.ok().put("data", page);
    }

    /**
    * 后端详情
    */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id, HttpServletRequest request){
        logger.debug("info方法:,,Controller:{},,id:{}",this.getClass().getName(),id);
        WuziChuruInoutListEntity wuziChuruInoutList = wuziChuruInoutListService.selectById(id);
        if(wuziChuruInoutList !=null){
            //entity转view
            WuziChuruInoutListView view = new WuziChuruInoutListView();
            BeanUtils.copyProperties( wuziChuruInoutList , view );//把实体数据重构到view中

                //级联表
                WuziEntity wuzi = wuziService.selectById(wuziChuruInoutList.getWuziId());
                if(wuzi != null){
                    BeanUtils.copyProperties( wuzi , view ,new String[]{ "id", "createTime", "insertTime", "updateTime"});//把级联的数据添加到view中,并排除id和创建时间字段
                    view.setWuziId(wuzi.getId());
                }
                //级联表
                WuziChuruInoutEntity wuziChuruInout = wuziChuruInoutService.selectById(wuziChuruInoutList.getWuziChuruInoutId());
                if(wuziChuruInout != null){
                    BeanUtils.copyProperties( wuziChuruInout , view ,new String[]{ "id", "createTime", "insertTime", "updateTime"});//把级联的数据添加到view中,并排除id和创建时间字段
                    view.setWuziChuruInoutId(wuziChuruInout.getId());
                }
            //修改对应字典表字段
            dictionaryService.dictionaryConvert(view, request);
            return R.ok().put("data", view);
        }else {
            return R.error(511,"查不到数据");
        }

    }

    /**
    * 后端保存
    */
    @RequestMapping("/save")
    public R save(@RequestBody WuziChuruInoutListEntity wuziChuruInoutList, HttpServletRequest request){
        logger.debug("save方法:,,Controller:{},,wuziChuruInoutList:{}",this.getClass().getName(),wuziChuruInoutList.toString());

        String role = String.valueOf(request.getSession().getAttribute("role"));
        if(StringUtil.isEmpty(role))
            return R.error(511,"权限为空");

        Wrapper<WuziChuruInoutListEntity> queryWrapper = new EntityWrapper<WuziChuruInoutListEntity>()
            .eq("wuzi_churu_inout_id", wuziChuruInoutList.getWuziChuruInoutId())
            .eq("wuzi_id", wuziChuruInoutList.getWuziId())
            .eq("wuzi_churu_inout_list_number", wuziChuruInoutList.getWuziChuruInoutListNumber())
            ;

        logger.info("sql语句:"+queryWrapper.getSqlSegment());
        WuziChuruInoutListEntity wuziChuruInoutListEntity = wuziChuruInoutListService.selectOne(queryWrapper);
        if(wuziChuruInoutListEntity==null){
            wuziChuruInoutList.setInsertTime(new Date());
            wuziChuruInoutList.setCreateTime(new Date());
            wuziChuruInoutListService.insert(wuziChuruInoutList);
            return R.ok();
        }else {
            return R.error(511,"表中有相同数据");
        }
    }

    /**
    * 后端修改
    */
    @RequestMapping("/update")
    public R update(@RequestBody WuziChuruInoutListEntity wuziChuruInoutList, HttpServletRequest request){
        logger.debug("update方法:,,Controller:{},,wuziChuruInoutList:{}",this.getClass().getName(),wuziChuruInoutList.toString());

        String role = String.valueOf(request.getSession().getAttribute("role"));
//        if(StringUtil.isEmpty(role))
//            return R.error(511,"权限为空");
        //根据字段查询是否有相同数据
        Wrapper<WuziChuruInoutListEntity> queryWrapper = new EntityWrapper<WuziChuruInoutListEntity>()
            .notIn("id",wuziChuruInoutList.getId())
            .andNew()
            .eq("wuzi_churu_inout_id", wuziChuruInoutList.getWuziChuruInoutId())
            .eq("wuzi_id", wuziChuruInoutList.getWuziId())
            .eq("wuzi_churu_inout_list_number", wuziChuruInoutList.getWuziChuruInoutListNumber())
            ;

        logger.info("sql语句:"+queryWrapper.getSqlSegment());
        WuziChuruInoutListEntity wuziChuruInoutListEntity = wuziChuruInoutListService.selectOne(queryWrapper);
        if(wuziChuruInoutListEntity==null){
            wuziChuruInoutListService.updateById(wuziChuruInoutList);//根据id更新
            return R.ok();
        }else {
            return R.error(511,"表中有相同数据");
        }
    }

    /**
    * 删除
    */
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] ids){
        logger.debug("delete:,,Controller:{},,ids:{}",this.getClass().getName(),ids.toString());
        wuziChuruInoutListService.deleteBatchIds(Arrays.asList(ids));
        return R.ok();
    }


    /**
     * 批量上传
     */
    @RequestMapping("/batchInsert")
    public R save( String fileName){
        logger.debug("batchInsert方法:,,Controller:{},,fileName:{}",this.getClass().getName(),fileName);
        try {
            List<WuziChuruInoutListEntity> wuziChuruInoutListList = new ArrayList<>();//上传的东西
            Map<String, List<String>> seachFields= new HashMap<>();//要查询的字段
            Date date = new Date();
            int lastIndexOf = fileName.lastIndexOf(".");
            if(lastIndexOf == -1){
                return R.error(511,"该文件没有后缀");
            }else{
                String suffix = fileName.substring(lastIndexOf);
                if(!".xls".equals(suffix)){
                    return R.error(511,"只支持后缀为xls的excel文件");
                }else{
                    URL resource = this.getClass().getClassLoader().getResource("static/upload/" + fileName);//获取文件路径
                    File file = new File(resource.getFile());
                    if(!file.exists()){
                        return R.error(511,"找不到上传文件,请联系管理员");
                    }else{
                        List<List<String>> dataList = PoiUtil.poiImport(file.getPath());//读取xls文件
                        dataList.remove(0);//删除第一行,因为第一行是提示
                        for(List<String> data:dataList){
                            //循环
                            WuziChuruInoutListEntity wuziChuruInoutListEntity = new WuziChuruInoutListEntity();
//                            wuziChuruInoutListEntity.setWuziChuruInoutId(Integer.valueOf(data.get(0)));   //出入库 要改的
//                            wuziChuruInoutListEntity.setWuziId(Integer.valueOf(data.get(0)));   //物资 要改的
//                            wuziChuruInoutListEntity.setWuziChuruInoutListNumber(Integer.valueOf(data.get(0)));   //操作数量 要改的
//                            wuziChuruInoutListEntity.setInsertTime(date);//时间
//                            wuziChuruInoutListEntity.setCreateTime(date);//时间
                            wuziChuruInoutListList.add(wuziChuruInoutListEntity);


                            //把要查询是否重复的字段放入map中
                        }

                        //查询是否重复
                        wuziChuruInoutListService.insertBatch(wuziChuruInoutListList);
                        return R.ok();
                    }
                }
            }
        }catch (Exception e){
            return R.error(511,"批量插入数据异常,请联系管理员");
        }
    }






}
View Code

WuziController

package com.controller;

import java.io.File;
import java.math.BigDecimal;
import java.net.URL;
import java.text.SimpleDateFormat;
import com.alibaba.fastjson.JSONObject;
import java.util.*;
import org.springframework.beans.BeanUtils;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.ContextLoader;
import javax.servlet.ServletContext;
import com.service.TokenService;
import com.utils.*;
import java.lang.reflect.InvocationTargetException;

import com.service.DictionaryService;
import org.apache.commons.lang3.StringUtils;
import com.annotation.IgnoreAuth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.entity.*;
import com.entity.view.*;
import com.service.*;
import com.utils.PageUtils;
import com.utils.R;
import com.alibaba.fastjson.*;

/**
 * 物资信息
 * 后端接口
 * @author
 * @email
*/
@RestController
@Controller
@RequestMapping("/wuzi")
public class WuziController {
    private static final Logger logger = LoggerFactory.getLogger(WuziController.class);

    @Autowired
    private WuziService wuziService;


    @Autowired
    private TokenService tokenService;
    @Autowired
    private DictionaryService dictionaryService;

    //级联表service
    @Autowired
    private CangkuService cangkuService;

    @Autowired
    private YonghuService yonghuService;


    /**
    * 后端列表
    */
    @RequestMapping("/page")
    public R page(@RequestParam Map<String, Object> params, HttpServletRequest request){
        logger.debug("page方法:,,Controller:{},,params:{}",this.getClass().getName(),JSONObject.toJSONString(params));
        String role = String.valueOf(request.getSession().getAttribute("role"));
        if(StringUtil.isEmpty(role))
            return R.error(511,"权限为空");
        else if("员工".equals(role))
            params.put("yonghuId",request.getSession().getAttribute("userId"));
        if(params.get("orderBy")==null || params.get("orderBy")==""){
            params.put("orderBy","id");
        }
        PageUtils page = wuziService.queryPage(params);

        //字典表数据转换
        List<WuziView> list =(List<WuziView>)page.getList();
        for(WuziView c:list){
            //修改对应字典表字段
            dictionaryService.dictionaryConvert(c, request);
        }
        return R.ok().put("data", page);
    }

    /**
    * 后端详情
    */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id, HttpServletRequest request){
        logger.debug("info方法:,,Controller:{},,id:{}",this.getClass().getName(),id);
        WuziEntity wuzi = wuziService.selectById(id);
        if(wuzi !=null){
            //entity转view
            WuziView view = new WuziView();
            BeanUtils.copyProperties( wuzi , view );//把实体数据重构到view中

                //级联表
                CangkuEntity cangku = cangkuService.selectById(wuzi.getCangkuId());
                if(cangku != null){
                    BeanUtils.copyProperties( cangku , view ,new String[]{ "id", "createTime", "insertTime", "updateTime"});//把级联的数据添加到view中,并排除id和创建时间字段
                    view.setCangkuId(cangku.getId());
                }
            //修改对应字典表字段
            dictionaryService.dictionaryConvert(view, request);
            return R.ok().put("data", view);
        }else {
            return R.error(511,"查不到数据");
        }

    }

    /**
    * 后端保存
    */
    @RequestMapping("/save")
    public R save(@RequestBody WuziEntity wuzi, HttpServletRequest request){
        logger.debug("save方法:,,Controller:{},,wuzi:{}",this.getClass().getName(),wuzi.toString());

        String role = String.valueOf(request.getSession().getAttribute("role"));
        if(StringUtil.isEmpty(role))
            return R.error(511,"权限为空");

        Wrapper<WuziEntity> queryWrapper = new EntityWrapper<WuziEntity>()
            .eq("wuzi_uuid_unmber", wuzi.getWuziUuidUnmber())
            .eq("wuzi_name", wuzi.getWuziName())
            .eq("wuzi_types", wuzi.getWuziTypes())
            .eq("Wuzi_kucun_number", wuzi.getWuziKucunNumber())
            .eq("wuzi_min", wuzi.getWuziMin())
            .eq("wuzi_max", wuzi.getWuziMax())
            .eq("wuzi_danwei", wuzi.getWuziDanwei())
            .eq("wuzi_gongyingshang", wuzi.getWuziGongyingshang())
            .eq("cangku_id", wuzi.getCangkuId())
            ;

        logger.info("sql语句:"+queryWrapper.getSqlSegment());
        WuziEntity wuziEntity = wuziService.selectOne(queryWrapper);
        if(wuziEntity==null){
            wuzi.setCreateTime(new Date());
            wuziService.insert(wuzi);
            return R.ok();
        }else {
            return R.error(511,"表中有相同数据");
        }
    }

    /**
    * 后端修改
    */
    @RequestMapping("/update")
    public R update(@RequestBody WuziEntity wuzi, HttpServletRequest request){
        logger.debug("update方法:,,Controller:{},,wuzi:{}",this.getClass().getName(),wuzi.toString());

        String role = String.valueOf(request.getSession().getAttribute("role"));
//        if(StringUtil.isEmpty(role))
//            return R.error(511,"权限为空");
        //根据字段查询是否有相同数据
        Wrapper<WuziEntity> queryWrapper = new EntityWrapper<WuziEntity>()
            .notIn("id",wuzi.getId())
            .andNew()
            .eq("wuzi_uuid_unmber", wuzi.getWuziUuidUnmber())
            .eq("wuzi_name", wuzi.getWuziName())
            .eq("wuzi_types", wuzi.getWuziTypes())
            .eq("Wuzi_kucun_number", wuzi.getWuziKucunNumber())
            .eq("wuzi_min", wuzi.getWuziMin())
            .eq("wuzi_max", wuzi.getWuziMax())
            .eq("wuzi_danwei", wuzi.getWuziDanwei())
            .eq("wuzi_gongyingshang", wuzi.getWuziGongyingshang())
            .eq("cangku_id", wuzi.getCangkuId())
            ;

        logger.info("sql语句:"+queryWrapper.getSqlSegment());
        WuziEntity wuziEntity = wuziService.selectOne(queryWrapper);
        if(wuziEntity==null){
            wuziService.updateById(wuzi);//根据id更新
            return R.ok();
        }else {
            return R.error(511,"表中有相同数据");
        }
    }

    /**
    * 删除
    */
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] ids){
        logger.debug("delete:,,Controller:{},,ids:{}",this.getClass().getName(),ids.toString());
        wuziService.deleteBatchIds(Arrays.asList(ids));
        return R.ok();
    }


    /**
     * 批量上传
     */
    @RequestMapping("/batchInsert")
    public R save( String fileName){
        logger.debug("batchInsert方法:,,Controller:{},,fileName:{}",this.getClass().getName(),fileName);
        try {
            List<WuziEntity> wuziList = new ArrayList<>();//上传的东西
            Map<String, List<String>> seachFields= new HashMap<>();//要查询的字段
            Date date = new Date();
            int lastIndexOf = fileName.lastIndexOf(".");
            if(lastIndexOf == -1){
                return R.error(511,"该文件没有后缀");
            }else{
                String suffix = fileName.substring(lastIndexOf);
                if(!".xls".equals(suffix)){
                    return R.error(511,"只支持后缀为xls的excel文件");
                }else{
                    URL resource = this.getClass().getClassLoader().getResource("static/upload/" + fileName);//获取文件路径
                    File file = new File(resource.getFile());
                    if(!file.exists()){
                        return R.error(511,"找不到上传文件,请联系管理员");
                    }else{
                        List<List<String>> dataList = PoiUtil.poiImport(file.getPath());//读取xls文件
                        dataList.remove(0);//删除第一行,因为第一行是提示
                        for(List<String> data:dataList){
                            //循环
                            WuziEntity wuziEntity = new WuziEntity();
//                            wuziEntity.setWuziUuidUnmber(data.get(0));                    //物资编号 要改的
//                            wuziEntity.setWuziName(data.get(0));                    //物资名称 要改的
//                            wuziEntity.setWuziTypes(Integer.valueOf(data.get(0)));   //物资类型 要改的
//                            wuziEntity.setWuziKucunNumber(Integer.valueOf(data.get(0)));   //物资数量 要改的
//                            wuziEntity.setWuziMin(Integer.valueOf(data.get(0)));   //最低预警值 要改的
//                            wuziEntity.setWuziMax(Integer.valueOf(data.get(0)));   //最高预警值 要改的
//                            wuziEntity.setWuziNewMoney(data.get(0));                    //物资价格 要改的
//                            wuziEntity.setWuziDanwei(data.get(0));                    //物资单位 要改的
//                            wuziEntity.setWuziGongyingshang(data.get(0));                    //供应商 要改的
//                            wuziEntity.setCangkuId(Integer.valueOf(data.get(0)));   //所在仓库 要改的
//                            wuziEntity.setCreateTime(date);//时间
                            wuziList.add(wuziEntity);


                            //把要查询是否重复的字段放入map中
                        }

                        //查询是否重复
                        wuziService.insertBatch(wuziList);
                        return R.ok();
                    }
                }
            }
        }catch (Exception e){
            return R.error(511,"批量插入数据异常,请联系管理员");
        }
    }






}
View Code

YonghuController

package com.controller;

import java.io.File;
import java.math.BigDecimal;
import java.net.URL;
import java.text.SimpleDateFormat;
import com.alibaba.fastjson.JSONObject;
import java.util.*;
import org.springframework.beans.BeanUtils;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.ContextLoader;
import javax.servlet.ServletContext;
import com.service.TokenService;
import com.utils.*;
import java.lang.reflect.InvocationTargetException;

import com.service.DictionaryService;
import org.apache.commons.lang3.StringUtils;
import com.annotation.IgnoreAuth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.entity.*;
import com.entity.view.*;
import com.service.*;
import com.utils.PageUtils;
import com.utils.R;
import com.alibaba.fastjson.*;

/**
 * 员工
 * 后端接口
 * @author
 * @email
*/
@RestController
@Controller
@RequestMapping("/yonghu")
public class YonghuController {
    private static final Logger logger = LoggerFactory.getLogger(YonghuController.class);

    @Autowired
    private YonghuService yonghuService;


    @Autowired
    private TokenService tokenService;
    @Autowired
    private DictionaryService dictionaryService;

    //级联表service



    /**
    * 后端列表
    */
    @RequestMapping("/page")
    public R page(@RequestParam Map<String, Object> params, HttpServletRequest request){
        logger.debug("page方法:,,Controller:{},,params:{}",this.getClass().getName(),JSONObject.toJSONString(params));
        String role = String.valueOf(request.getSession().getAttribute("role"));
        if(StringUtil.isEmpty(role))
            return R.error(511,"权限为空");
        else if("员工".equals(role))
            params.put("yonghuId",request.getSession().getAttribute("userId"));
        params.put("yonghuDeleteStart",1);params.put("yonghuDeleteEnd",1);
        if(params.get("orderBy")==null || params.get("orderBy")==""){
            params.put("orderBy","id");
        }
        PageUtils page = yonghuService.queryPage(params);

        //字典表数据转换
        List<YonghuView> list =(List<YonghuView>)page.getList();
        for(YonghuView c:list){
            //修改对应字典表字段
            dictionaryService.dictionaryConvert(c, request);
        }
        return R.ok().put("data", page);
    }

    /**
    * 后端详情
    */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id, HttpServletRequest request){
        logger.debug("info方法:,,Controller:{},,id:{}",this.getClass().getName(),id);
        YonghuEntity yonghu = yonghuService.selectById(id);
        if(yonghu !=null){
            //entity转view
            YonghuView view = new YonghuView();
            BeanUtils.copyProperties( yonghu , view );//把实体数据重构到view中

            //修改对应字典表字段
            dictionaryService.dictionaryConvert(view, request);
            return R.ok().put("data", view);
        }else {
            return R.error(511,"查不到数据");
        }

    }

    /**
    * 后端保存
    */
    @RequestMapping("/save")
    public R save(@RequestBody YonghuEntity yonghu, HttpServletRequest request){
        logger.debug("save方法:,,Controller:{},,yonghu:{}",this.getClass().getName(),yonghu.toString());

        String role = String.valueOf(request.getSession().getAttribute("role"));
        if(StringUtil.isEmpty(role))
            return R.error(511,"权限为空");

        Wrapper<YonghuEntity> queryWrapper = new EntityWrapper<YonghuEntity>()
            .eq("username", yonghu.getUsername())
            .or()
            .eq("yonghu_phone", yonghu.getYonghuPhone())
            .or()
            .eq("yonghu_id_number", yonghu.getYonghuIdNumber())
            .andNew()
            .eq("yonghu_delete", 1)
            ;

        logger.info("sql语句:"+queryWrapper.getSqlSegment());
        YonghuEntity yonghuEntity = yonghuService.selectOne(queryWrapper);
        if(yonghuEntity==null){
            yonghu.setYonghuDelete(1);
            yonghu.setCreateTime(new Date());
            yonghu.setPassword("123456");
            yonghuService.insert(yonghu);
            return R.ok();
        }else {
            return R.error(511,"账户或者员工手机号或者员工身份证号已经被使用");
        }
    }

    /**
    * 后端修改
    */
    @RequestMapping("/update")
    public R update(@RequestBody YonghuEntity yonghu, HttpServletRequest request){
        logger.debug("update方法:,,Controller:{},,yonghu:{}",this.getClass().getName(),yonghu.toString());

        String role = String.valueOf(request.getSession().getAttribute("role"));
//        if(StringUtil.isEmpty(role))
//            return R.error(511,"权限为空");
        //根据字段查询是否有相同数据
        Wrapper<YonghuEntity> queryWrapper = new EntityWrapper<YonghuEntity>()
            .notIn("id",yonghu.getId())
            .andNew()
            .eq("username", yonghu.getUsername())
            .or()
            .eq("yonghu_phone", yonghu.getYonghuPhone())
            .or()
            .eq("yonghu_id_number", yonghu.getYonghuIdNumber())
            .andNew()
            .eq("yonghu_delete", 1)
            ;

        logger.info("sql语句:"+queryWrapper.getSqlSegment());
        YonghuEntity yonghuEntity = yonghuService.selectOne(queryWrapper);
        if("".equals(yonghu.getYonghuPhoto()) || "null".equals(yonghu.getYonghuPhoto())){
                yonghu.setYonghuPhoto(null);
        }
        if(yonghuEntity==null){
            yonghuService.updateById(yonghu);//根据id更新
            return R.ok();
        }else {
            return R.error(511,"账户或者员工手机号或者员工身份证号已经被使用");
        }
    }

    /**
    * 删除
    */
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] ids){
        logger.debug("delete:,,Controller:{},,ids:{}",this.getClass().getName(),ids.toString());
        ArrayList<YonghuEntity> list = new ArrayList<>();
        for(Integer id:ids){
            YonghuEntity yonghuEntity = new YonghuEntity();
            yonghuEntity.setId(id);
            yonghuEntity.setYonghuDelete(2);
            list.add(yonghuEntity);
        }
        if(list != null && list.size() >0){
            yonghuService.updateBatchById(list);
        }
        return R.ok();
    }


    /**
     * 批量上传
     */
    @RequestMapping("/batchInsert")
    public R save( String fileName){
        logger.debug("batchInsert方法:,,Controller:{},,fileName:{}",this.getClass().getName(),fileName);
        try {
            List<YonghuEntity> yonghuList = new ArrayList<>();//上传的东西
            Map<String, List<String>> seachFields= new HashMap<>();//要查询的字段
            Date date = new Date();
            int lastIndexOf = fileName.lastIndexOf(".");
            if(lastIndexOf == -1){
                return R.error(511,"该文件没有后缀");
            }else{
                String suffix = fileName.substring(lastIndexOf);
                if(!".xls".equals(suffix)){
                    return R.error(511,"只支持后缀为xls的excel文件");
                }else{
                    URL resource = this.getClass().getClassLoader().getResource("static/upload/" + fileName);//获取文件路径
                    File file = new File(resource.getFile());
                    if(!file.exists()){
                        return R.error(511,"找不到上传文件,请联系管理员");
                    }else{
                        List<List<String>> dataList = PoiUtil.poiImport(file.getPath());//读取xls文件
                        dataList.remove(0);//删除第一行,因为第一行是提示
                        for(List<String> data:dataList){
                            //循环
                            YonghuEntity yonghuEntity = new YonghuEntity();
//                            yonghuEntity.setUsername(data.get(0));                    //账户 要改的
//                            //yonghuEntity.setPassword("123456");//密码
//                            yonghuEntity.setYonghuName(data.get(0));                    //员工姓名 要改的
//                            yonghuEntity.setYonghuPhoto("");//照片
//                            yonghuEntity.setYonghuPhone(data.get(0));                    //员工手机号 要改的
//                            yonghuEntity.setYonghuIdNumber(data.get(0));                    //员工身份证号 要改的
//                            yonghuEntity.setYonghuEmail(data.get(0));                    //邮箱 要改的
//                            yonghuEntity.setSexTypes(Integer.valueOf(data.get(0)));   //性别 要改的
//                            yonghuEntity.setYonghuDelete(1);//逻辑删除字段
//                            yonghuEntity.setCreateTime(date);//时间
                            yonghuList.add(yonghuEntity);


                            //把要查询是否重复的字段放入map中
                                //账户
                                if(seachFields.containsKey("username")){
                                    List<String> username = seachFields.get("username");
                                    username.add(data.get(0));//要改的
                                }else{
                                    List<String> username = new ArrayList<>();
                                    username.add(data.get(0));//要改的
                                    seachFields.put("username",username);
                                }
                                //员工手机号
                                if(seachFields.containsKey("yonghuPhone")){
                                    List<String> yonghuPhone = seachFields.get("yonghuPhone");
                                    yonghuPhone.add(data.get(0));//要改的
                                }else{
                                    List<String> yonghuPhone = new ArrayList<>();
                                    yonghuPhone.add(data.get(0));//要改的
                                    seachFields.put("yonghuPhone",yonghuPhone);
                                }
                                //员工身份证号
                                if(seachFields.containsKey("yonghuIdNumber")){
                                    List<String> yonghuIdNumber = seachFields.get("yonghuIdNumber");
                                    yonghuIdNumber.add(data.get(0));//要改的
                                }else{
                                    List<String> yonghuIdNumber = new ArrayList<>();
                                    yonghuIdNumber.add(data.get(0));//要改的
                                    seachFields.put("yonghuIdNumber",yonghuIdNumber);
                                }
                        }

                        //查询是否重复
                         //账户
                        List<YonghuEntity> yonghuEntities_username = yonghuService.selectList(new EntityWrapper<YonghuEntity>().in("username", seachFields.get("username")).eq("yonghu_delete", 1));
                        if(yonghuEntities_username.size() >0 ){
                            ArrayList<String> repeatFields = new ArrayList<>();
                            for(YonghuEntity s:yonghuEntities_username){
                                repeatFields.add(s.getUsername());
                            }
                            return R.error(511,"数据库的该表中的 [账户] 字段已经存在 存在数据为:"+repeatFields.toString());
                        }
                         //员工手机号
                        List<YonghuEntity> yonghuEntities_yonghuPhone = yonghuService.selectList(new EntityWrapper<YonghuEntity>().in("yonghu_phone", seachFields.get("yonghuPhone")).eq("yonghu_delete", 1));
                        if(yonghuEntities_yonghuPhone.size() >0 ){
                            ArrayList<String> repeatFields = new ArrayList<>();
                            for(YonghuEntity s:yonghuEntities_yonghuPhone){
                                repeatFields.add(s.getYonghuPhone());
                            }
                            return R.error(511,"数据库的该表中的 [员工手机号] 字段已经存在 存在数据为:"+repeatFields.toString());
                        }
                         //员工身份证号
                        List<YonghuEntity> yonghuEntities_yonghuIdNumber = yonghuService.selectList(new EntityWrapper<YonghuEntity>().in("yonghu_id_number", seachFields.get("yonghuIdNumber")).eq("yonghu_delete", 1));
                        if(yonghuEntities_yonghuIdNumber.size() >0 ){
                            ArrayList<String> repeatFields = new ArrayList<>();
                            for(YonghuEntity s:yonghuEntities_yonghuIdNumber){
                                repeatFields.add(s.getYonghuIdNumber());
                            }
                            return R.error(511,"数据库的该表中的 [员工身份证号] 字段已经存在 存在数据为:"+repeatFields.toString());
                        }
                        yonghuService.insertBatch(yonghuList);
                        return R.ok();
                    }
                }
            }
        }catch (Exception e){
            return R.error(511,"批量插入数据异常,请联系管理员");
        }
    }


    /**
    * 登录
    */
    @IgnoreAuth
    @RequestMapping(value = "/login")
    public R login(String username, String password, String captcha, HttpServletRequest request) {
        YonghuEntity yonghu = yonghuService.selectOne(new EntityWrapper<YonghuEntity>().eq("username", username));
        if(yonghu==null || !yonghu.getPassword().equals(password))
            return R.error("账号或密码不正确");
        else if(yonghu.getYonghuDelete() != 1)
            return R.error("账户已被删除");
        //  // 获取监听器中的字典表
        // ServletContext servletContext = ContextLoader.getCurrentWebApplicationContext().getServletContext();
        // Map<String, Map<Integer, String>> dictionaryMap= (Map<String, Map<Integer, String>>) servletContext.getAttribute("dictionaryMap");
        // Map<Integer, String> role_types = dictionaryMap.get("role_types");
        // role_types.get(.getRoleTypes());
        String token = tokenService.generateToken(yonghu.getId(),username, "yonghu", "员工");
        R r = R.ok();
        r.put("token", token);
        r.put("role","员工");
        r.put("username",yonghu.getYonghuName());
        r.put("tableName","yonghu");
        r.put("userId",yonghu.getId());
        return r;
    }

    /**
    * 注册
    */
    @IgnoreAuth
    @PostMapping(value = "/register")
    public R register(@RequestBody YonghuEntity yonghu){
//        ValidatorUtils.validateEntity(user);
        Wrapper<YonghuEntity> queryWrapper = new EntityWrapper<YonghuEntity>()
            .eq("username", yonghu.getUsername())
            .or()
            .eq("yonghu_phone", yonghu.getYonghuPhone())
            .or()
            .eq("yonghu_id_number", yonghu.getYonghuIdNumber())
            .andNew()
            .eq("yonghu_delete", 1)
            ;
        YonghuEntity yonghuEntity = yonghuService.selectOne(queryWrapper);
        if(yonghuEntity != null)
            return R.error("账户或者员工手机号或者员工身份证号已经被使用");
        yonghu.setYonghuDelete(1);
        yonghu.setCreateTime(new Date());
        yonghuService.insert(yonghu);
        return R.ok();
    }

    /**
     * 重置密码
     */
    @GetMapping(value = "/resetPassword")
    public R resetPassword(Integer  id){
        YonghuEntity yonghu = new YonghuEntity();
        yonghu.setPassword("123456");
        yonghu.setId(id);
        yonghuService.updateById(yonghu);
        return R.ok();
    }


    /**
     * 忘记密码
     */
    @IgnoreAuth
    @RequestMapping(value = "/resetPass")
    public R resetPass(String username, HttpServletRequest request) {
        YonghuEntity yonghu = yonghuService.selectOne(new EntityWrapper<YonghuEntity>().eq("username", username));
        if(yonghu!=null){
            yonghu.setPassword("123456");
            boolean b = yonghuService.updateById(yonghu);
            if(!b){
               return R.error();
            }
        }else{
           return R.error("账号不存在");
        }
        return R.ok();
    }


    /**
    * 获取用户的session用户信息
    */
    @RequestMapping("/session")
    public R getCurrYonghu(HttpServletRequest request){
        Integer id = (Integer)request.getSession().getAttribute("userId");
        YonghuEntity yonghu = yonghuService.selectById(id);
        if(yonghu !=null){
            //entity转view
            YonghuView view = new YonghuView();
            BeanUtils.copyProperties( yonghu , view );//把实体数据重构到view中

            //修改对应字典表字段
            dictionaryService.dictionaryConvert(view, request);
            return R.ok().put("data", view);
        }else {
            return R.error(511,"查不到数据");
        }
    }


    /**
    * 退出
    */
    @GetMapping(value = "logout")
    public R logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return R.ok("退出成功");
    }





}
View Code

 

posted @ 2025-03-10 09:00    阅读(14)  评论(0)    收藏  举报