package org.jeecg.modules.checkData.equipmentCheckData.controller;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.*;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.modules.checkData.equipmentCheckData.dto.MovementAdditiveInfoDTO;
import org.jeecg.modules.checkData.equipmentCheckData.dto.MovementRecordsMasterDTO;
import org.jeecg.modules.checkData.equipmentCheckData.entity.MovementAdditiveInfo;
import org.jeecg.modules.checkData.equipmentCheckData.entity.MovementCourse;
import org.jeecg.modules.checkData.equipmentCheckData.entity.MovementCourseInfo;
import org.jeecg.modules.checkData.equipmentCheckData.entity.MovementRecordsMaster;
import org.jeecg.modules.checkData.equipmentCheckData.service.IMovementAdditiveInfoService;
import org.jeecg.modules.checkData.equipmentCheckData.service.IMovementCourseInfoService;
import org.jeecg.modules.checkData.equipmentCheckData.service.IMovementCourseService;
import org.jeecg.modules.checkData.equipmentCheckData.service.IMovementRecordsMasterService;
import org.jeecg.modules.checkData.equipmentCheckData.vo.*;
import org.jeecg.modules.subwayNetwork.entity.LightRail;
import org.jeecg.modules.subwayNetwork.entity.LineAlias;
import org.jeecg.modules.subwayNetwork.entity.SubwaySection;
import org.jeecg.modules.subwayNetwork.service.ILightRailService;
import org.jeecg.modules.subwayNetwork.service.ILineAliasService;
import org.jeecg.modules.subwayNetwork.service.ISubwaySectionService;
import org.jeecg.modules.utils.BeanCopyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 * 动静态几何尺寸数据主表	 前端控制器
 * </p>
 *
 * @author hkl
 * @since 2023-07-11
 */
@RestController
@RequestMapping("/movement/master")
@Api(tags = "动静态几何尺寸数据")
public class MovementRecordsMasterController extends JeecgController<MovementRecordsMaster, IMovementRecordsMasterService> {
    @Autowired
    private IMovementCourseService movementCourseService;
    @Autowired
    private IMovementCourseInfoService movementCourseInfoService;
    @Autowired
    private ISubwaySectionService subwaySectionService;
    @Autowired
    private ILineAliasService lineAliasService;
    @Autowired
    private IMovementAdditiveInfoService movementAdditiveInfoService;
    @Autowired
    private ILightRailService lightRailService;


//**********************************人工静态检查******************************

    /**
     * 动静态几何尺寸数据-分页列表查询
     *
     * @param pageNo
     * @param pageSize
     * @param dto
     * @return
     */
    @AutoLog(value = "动静态几何尺寸数据-分页列表查询")
    @ApiOperation(value = "动静态几何尺寸数据-分页列表查询", notes = "动静态几何尺寸数据-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<MovementRecordsMasterVO>> queryPageList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                MovementRecordsMasterDTO dto) {
        if (ObjectUtil.isEmpty(dto.getType())) {
            return Result.error("传递参数不完整");
        }
        Page<MovementRecordsMasterVO> pageData = new Page<>(pageNo, pageSize);
        pageData = this.service.queryPageList(pageData, dto);
        return Result.OK(pageData);
    }

    /**
     * 动静态几何新增时初始化回显数据
     *
     * @param lightRailId
     * @param lineAliasId
     * @param sectionId
     * @param type
     * @return
     */
    @AutoLog(value = "动静态几何新增时初始化回显数据")
    @ApiOperation(value = "动静态几何新增时初始化回显数据", notes = "动静态几何新增时初始化回显数据")
    @GetMapping(value = "/getMovementAdditiveQuery")
    public Result<MovementAdditiveSavaQueryVO> getMovementAdditiveQuery(@ApiParam(name = "线路id", required = true) String lightRailId, @ApiParam(name = "线别id", required = true) String lineAliasId, @ApiParam(name = "区间id", required = false) String sectionId, @ApiParam(name = "查询类型", required = true) String type) {
        MovementAdditiveSavaQueryVO result = new MovementAdditiveSavaQueryVO();
        result.setLightRailId(lightRailId);
        result.setLineAliasId(lineAliasId);
        //查询线路对象
        LightRail lightRail = lightRailService.getById(lightRailId);
        result.setLightRailName(lightRail.getRailLineName());
        //查询线别对象
        LineAlias lineAlias = lineAliasService.getById(lineAliasId);
        result.setLineAliasName(lineAlias.getLineAliasName());
        if ("4".equals(type)) {
            result.setStartingMileage(BigDecimal.ZERO);
            if ("上行线".equals(lineAlias.getLineAliasName())) {
                result.setEndMileage(lightRail.getUpLineMileage());
            }
            if ("下行线".equals(lineAlias.getLineAliasName())) {
                result.setEndMileage(lightRail.getDownLineMileage());
            }
        } else {
            SubwaySection subwaySection = subwaySectionService.getById(sectionId);
            result.setEndMileage(subwaySection.getSectionStartingMileage());
            result.setEndMileage(subwaySection.getSectionEndMileage());
        }
        if (ObjectUtil.isNotEmpty(sectionId)) {
            result.setSubwaySectionId(sectionId);
            result.setSubwaySectionName(subwaySectionService.getById(sectionId).getSectionName());
        }
        //钢轨单元数量
        result.setRailNum(this.service.getRailNums(sectionId, lightRailId, lineAliasId, result.getStartingMileage(), result.getEndMileage()));
        //曲线数量
        result.setCurveNum(this.service.getCurveNums(sectionId, lightRailId, lineAliasId, result.getStartingMileage(), result.getEndMileage()));
        //竖曲线数量
        result.setVerticalCurveNum(this.service.getVerticalCurveNum(sectionId, lightRailId, lineAliasId, result.getStartingMileage(), result.getEndMileage()));
        //道岔数量
        result.setSwitchNum(this.service.getSwitchNum(sectionId, lightRailId, lineAliasId, result.getStartingMileage(), result.getEndMileage()));
        return Result.ok(result);
    }

    /**
     * 根据动静态几何尺寸数据主键查询检查里程相关信息
     *
     * @param id 动静态几何尺寸数据id
     * @return
     */
    @AutoLog(value = "根据动静态几何尺寸数据主键查询检查里程相关信息")
    @ApiOperation(value = "根据动静态几何尺寸数据主键查询检查里程相关信息", notes = "根据动静态几何尺寸数据主键查询检查里程相关信息")
    @GetMapping(value = "/getCourseList")
    public Result<List<MovementCourseVO>> getCourseList(@ApiParam(name = "动静态几何尺寸数据id") String id) {
        List<MovementCourse> listResult = movementCourseService.lambdaQuery()
                .eq(ObjectUtil.isNotEmpty(id), MovementCourse::getMovementMasterId, id)
                .eq(MovementCourse::getDelFlag, "0")
                .orderByAsc(MovementCourse::getSort)
                .list();
        List<MovementCourseVO> resultList = new ArrayList<>();
        if (listResult != null) {
            resultList = BeanCopyUtil.copyListProperties(listResult, MovementCourseVO::new);
        }
        return Result.OK(resultList);
    }

    /**
     * 根据动静态几何尺寸数据id和对应的里程相关信息id查询其详情
     *
     * @param movementMasterId 动静态几何尺寸数据id
     * @param movementCourseId 对应的里程相关信息id
     * @return
     */
//    @AutoLog(value = "根据动静态几何尺寸数据id和对应的里程相关信息id查询其详情")
//    @ApiOperation(value = "根据动静态几何尺寸数据id和对应的里程相关信息id查询其详情", notes = "根据动静态几何尺寸数据id和对应的里程相关信息id查询其详情")
//    @GetMapping(value = "/getInfoById")
//    public Result<List<MovementCourseInfoVO>> getInfoById(@ApiParam(name = "动静态几何尺寸数据id") String movementMasterId, @ApiParam(name = "检查里程相关信息id") String movementCourseId) {
//        List<MovementCourseInfo> listResult = movementCourseInfoService.lambdaQuery()
//                .eq(ObjectUtil.isNotEmpty(movementMasterId), MovementCourseInfo::getMovementMasterId, movementMasterId)
//                .eq(ObjectUtil.isNotEmpty(movementCourseId), MovementCourseInfo::getMovementCourseId, movementCourseId)
//                .eq(MovementCourseInfo::getDelFlag, "0")
//                .orderByAsc(MovementCourseInfo::getInfoSort)
//                .list();
//        List<MovementCourseInfoVO> resultList = new ArrayList<>();
//        if(listResult != null && listResult.size() > 0){
//            resultList = BeanCopyUtil.copyListProperties(listResult, MovementCourseInfoVO::new);
//        }
//        return Result.OK(resultList);
//    }


    @AutoLog(value = "根据动静态几何尺寸数据id和对应的里程相关信息id查询其详情")
    @ApiOperation(value = "根据动静态几何尺寸数据id和对应的里程相关信息id查询其详情", notes = "根据动静态几何尺寸数据id和对应的里程相关信息id查询其详情")
    @GetMapping(value = "/getInfoById")
    public Result<List<MovementCourseInfoOneVO>> getInfoById(@ApiParam(name = "动静态几何尺寸数据id") String movementMasterId, @ApiParam(name = "检查里程相关信息id") String movementCourseId) {
        List<MovementCourseInfo> listResult = movementCourseInfoService.lambdaQuery()
                .eq(ObjectUtil.isNotEmpty(movementMasterId), MovementCourseInfo::getMovementMasterId, movementMasterId)
                .eq(ObjectUtil.isNotEmpty(movementCourseId), MovementCourseInfo::getMovementCourseId, movementCourseId)
                .eq(MovementCourseInfo::getDelFlag, "0")
                .orderByAsc(MovementCourseInfo::getInfoSort)
                .list();

        //初始化最终返回的集合
        List<MovementCourseInfoOneVO> resultList = new ArrayList<>();
        if (listResult != null && listResult.size() > 0) {
            List<String> trackCodeList = listResult.stream().map(MovementCourseInfo::getTrackCode).distinct().collect(Collectors.toList());
            for (String code : trackCodeList) {
                //初始化最终返回的对象
                MovementCourseInfoOneVO resultModel = new MovementCourseInfoOneVO();
                //初始化检查项目对应的详情记录的集合
                List<MovementCourseInfoVO> infoList = new ArrayList<>();
                //循环符合条件的数据项集合
                for (MovementCourseInfo entity : listResult) {
                    //判断项目名称一样
                    if (code.equals(entity.getTrackCode())) {
                        //初始化检查项目对应的详情记录的对象
                        MovementCourseInfoVO infoVo = new MovementCourseInfoVO();
                        BeanCopyUtil.copyProperties(entity, infoVo);
                        infoList.add(infoVo);
                    }
                }
                resultModel.setInfoList(infoList);
                resultModel.setTrackCode(code);
                resultList.add(resultModel);
            }
        }
        return Result.OK(resultList);
    }
    @AutoLog(value = "动静态几何尺寸主数据新增或者编辑")
    @ApiOperation(value = "动静态几何尺寸主数据新增或者编辑", notes = "动静态几何尺寸主数据新增或者编辑")
    @PostMapping(value = "/saveOrUpdate")
    @ResponseBody
    public Result<String> saveOrUpdate(@RequestBody MovementRecordsMaster movementRecordsMaster) {
        boolean state = validate(movementRecordsMaster);
        if (false == state) {
            return Result.error("传递参数不完整");
        }
        movementRecordsMaster.setUpdateTime(new Date());
        movementRecordsMaster.setDelFlag("0");
        if (ObjectUtil.isEmpty(movementRecordsMaster.getId())) {
            this.service.save(movementRecordsMaster);
        } else {
            this.service.updateById(movementRecordsMaster);
        }
        return Result.OK("操作成功!");
    }

    /**
     * 删除动静态几何尺寸数据及相关联的数据
     *
     * @param id
     * @param type
     * @return
     */
    @AutoLog(value = "删除动静态几何尺寸数据及相关联的数据")
    @ApiOperation(value = "删除动静态几何尺寸数据及相关联的数据", notes = "删除动静态几何尺寸数据及相关联的数据")
    @GetMapping(value = "/delete")
    public Result<String> delete(@ApiParam(name = "动静态几何尺寸数据id", required = true) String id, @ApiParam(name = "动静态几何尺寸数据类型", required = true) String type) {
        if ("1".equals(type)) {
            //人工静态检查相关
            //删除里程详情
//            LambdaUpdateWrapper<MovementCourseInfo> lambdaUpdateWrapper = Wrappers.lambdaUpdate();
//            lambdaUpdateWrapper.set(MovementCourseInfo::getDelFlag, "1");
//            lambdaUpdateWrapper.eq(MovementCourseInfo::getMovementMasterId, id);
            movementCourseInfoService.lambdaUpdate().eq(MovementCourseInfo::getMovementMasterId, id).remove();
            //删除里程相关
//            LambdaUpdateWrapper<MovementCourse> updateWrapper = Wrappers.lambdaUpdate();
//            updateWrapper.set(MovementCourse::getDelFlag, "1");
//            updateWrapper.eq(MovementCourse::getMovementMasterId, id);
            movementCourseService.lambdaUpdate().eq(MovementCourse::getMovementMasterId, id).remove();
        } else if ("4".equals(type)) {
            //删除添乘仪详情
            LambdaUpdateWrapper<MovementAdditiveInfo> updateQuery = Wrappers.lambdaUpdate();
            updateQuery.set(MovementAdditiveInfo::getDelFlag, "1");
            updateQuery.eq(MovementAdditiveInfo::getMovementMasterId, id);
            movementAdditiveInfoService.update(updateQuery);
        }
        //删除动静态几何尺寸数据
        LambdaUpdateWrapper<MovementRecordsMaster> update = Wrappers.lambdaUpdate();
        update.set(MovementRecordsMaster::getDelFlag, "1");
        update.eq(MovementRecordsMaster::getId, id);
        this.service.update(update);
        return Result.OK("删除成功!");
    }

    @AutoLog(value = "导入")
    @ApiOperation(value = "导入", notes = "导入 ")
    @PostMapping(value = "/upload")
    @Transactional
    public Result<String> uploadFile(MultipartFile file, @ApiParam(name = "动静态几何尺寸主键id") String id) {
        try {
            //初始化数据模板
            QueryWrapper<MovementCourse> courseRemove = new QueryWrapper<>();
            courseRemove.eq("movement_master_id", id);
            movementCourseService.remove(courseRemove);
            QueryWrapper<MovementCourseInfo> rm = new QueryWrapper<>();
            rm.eq("movement_master_id", id);
            movementCourseInfoService.remove(rm);
            //时间校验
            String pat = "\\d{4}.\\d{2}.\\d{2}";
            Pattern p = Pattern.compile(pat);
            //读取第一个sheet页的数据
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream(), 0);
            //读取Excel中所有的数据，以行保存
            List<List<Object>> rowRecords = reader.read();

            // 获取excel的列数
            int column = rowRecords.get(0).size();
            //初始化列的索引
            int skipColumnNum = 0;
            //int seq = 1; // 第一个
            //初始化起始里程
            String startingAndEndingMileageStr = "";
            //初始化终点里程
            String endingMileageStr = "";
            //初始化曲线半径
            String curveRadius = "";
            //初始化超高
            String superHigh = "";
            //初始化加宽
            String widen = "";
            //初始化顺坡率
            String slopeRatio = "";
            //初始化长度
            String longExtent = "";
            //初始化备注
            String remark = "";
            //初始化起始里程表主键
            String courseId = "";
            //获取当前登录人信息
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            String realname = user.getRealname();
            // 如果做完了一个解析就跳过
            MovementCourse movementCourse = new MovementCourse();
            List<MovementCourseInfo> resultList = new ArrayList<>();
            //初始化里程排序
            int sort = 0;
            //初始化测点
            int measurePoint = 0;
            //初始化轨号排序
            int infoSort = 0;
            for (int i = 0; i < column; i++) {
                skipColumnNum++;
                if (ObjectUtil.isEmpty(startingAndEndingMileageStr)) {
                    // 1.起止里程
                    List<Object> startingAndEndingMileage = rowRecords.get(3);
                    Object mileageObject = startingAndEndingMileage.get(i);
                    String mileage = mileageObject.toString();

                    //超高、加宽、顺坡率、线路全长
                    List<Object> courseList = rowRecords.get(4);
                    Object courseObject = courseList.get(i);
                    String courseStr = courseObject.toString();
                    if (mileage.indexOf("起止里程") != -1) {
                        //开始里程
                        String[] start = mileage.split("-");
                        String s = start[0];
                        String k = s.substring(s.indexOf("K") + 1, s.length()).trim();
                        startingAndEndingMileageStr = k.replace("+","").trim();

                        //结束里程
                        String s1 = start[1];
                        String[] ks1 = s1.split("K");
                        String k1 = ks1[1];
                        String[] n1 = k1.split("\\+");
                        String s2 = n1[1];
                        endingMileageStr = n1[0]+s2.substring(0, s2.indexOf(" ")).trim();

                        //曲线半径
                        String[] n2 = s1.split("半径 ");
                        String s3 = n2[1];
                        curveRadius = s3.substring(0, s3.indexOf(" m")).replace("/", "").trim();

                        //解析超高、加宽、顺坡率、线路全长
                        String[] n3 = courseStr.split("超高");
                        String s4 = n3[1];
                        superHigh = s4.substring(0, s4.indexOf("mm")).replace("/", "").trim();

                        //加宽
                        String[] n4 = courseStr.split("加宽");
                        String s5 = n4[1];
                        widen = s5.substring(0, s5.indexOf("mm")).replace("/", "").trim();
                        //System.out.println(skipColumnNum+"加宽="+widen+";");

                        //顺坡率
                        String[] n5 = courseStr.split("顺坡率");
                        String s6 = n5[1];
                        slopeRatio = s6.substring(0, s6.indexOf("‰")).replace("/", "").trim();
                        //System.out.println(skipColumnNum+"顺坡率="+slopeRatio+";");

                        //线路全长
                        String[] n6 = courseStr.split("线路全长：");
                        String s7 = n6[1];
                        longExtent = s7.substring(0, s7.indexOf("米")).replace("/", "").trim();
                        //System.out.println(skipColumnNum+"线路全长="+longExtent+";");

                        //解析备注
                        remark = rowRecords.get(14).get(i + 3).toString().trim();

                        movementCourse.setMovementMasterId(id);
                        movementCourse.setCourseStartingMileage(new BigDecimal(startingAndEndingMileageStr));
                        movementCourse.setCourseEndMileage(new BigDecimal(endingMileageStr));
                        if (ObjectUtil.isNotEmpty(curveRadius)) {
                            movementCourse.setCurveRadius(new BigDecimal(curveRadius));
                        }
                        if (ObjectUtil.isNotEmpty(superHigh)) {
                            movementCourse.setSuperHigh(new BigDecimal(superHigh));
                        }
                        if (ObjectUtil.isNotEmpty(widen)) {
                            movementCourse.setWiden(new BigDecimal(widen));
                        }
                        if (ObjectUtil.isNotEmpty(slopeRatio)) {
                            movementCourse.setSlopeRatio(new BigDecimal(slopeRatio));
                        }
                        if (ObjectUtil.isNotEmpty(longExtent)) {
                            movementCourse.setLongExtent(new BigDecimal(longExtent));
                        }
                        sort++;
                        courseId = UUIDGenerator.generate();
                        movementCourse.setId(courseId);
                        movementCourse.setDelFlag("0");
                        movementCourse.setCreateTime(new Date());
                        movementCourse.setUpdateTime(new Date());
                        movementCourse.setCreateBy(realname);
                        movementCourse.setUpdateBy(realname);
                        movementCourse.setRemark(remark);
                        movementCourse.setSort(sort);
                        movementCourseService.save(movementCourse);
                    }
                }

                //解析子集
                if ((skipColumnNum - 1) % 28 == 0) {
                    continue;
                }
                if ((skipColumnNum - 2) % 28 == 0) {
                    continue;
                }
                if (ObjectUtil.isNotEmpty(courseId)) {
                    infoSort++;
                    measurePoint++;
                    MovementCourseInfo movementCourseInfo = new MovementCourseInfo();
                    movementCourseInfo.setId(IdWorker.get32UUID());
                    movementCourseInfo.setDelFlag("0");
                    movementCourseInfo.setMovementMasterId(id);
                    movementCourseInfo.setMovementCourseId(courseId);
                    movementCourseInfo.setCreateTime(new Date());
                    movementCourseInfo.setUpdateTime(new Date());
                    movementCourseInfo.setCreateBy(realname);
                    movementCourseInfo.setUpdateBy(realname);
                    movementCourseInfo.setInfoSort(infoSort);
                    movementCourseInfo.setMeasurePoint(measurePoint);
                    //获取轨号
                    List<Object> trackCodeList = rowRecords.get(6);
                    String trackCode = trackCodeList.get(i).toString().trim();
                    if (ObjectUtil.isNotEmpty(trackCode) && !("检查日期").equals(trackCode) && !("轨号").equals(trackCode)) {
                        movementCourseInfo.setTrackCode(trackCode);
                    }
                    //获取轨距
                    List<Object> trackGaugeList = rowRecords.get(7);
                    String trackGauge = trackGaugeList.get(i).toString().trim();
                    if (ObjectUtil.isNotEmpty(trackGauge)
                            && !("轨距").equals(trackGauge) && !p.matcher(trackGauge).matches()) {
                        movementCourseInfo.setTrackGauge(trackGauge);
                    }
                    //获取水平
                    List<Object> levelList = rowRecords.get(8);
                    String level = levelList.get(i).toString().trim();
                    if (ObjectUtil.isNotEmpty(level)
                            && !("水平").equals(level) && !p.matcher(level).matches()) {
                        movementCourseInfo.setLevel(level);
                    }
                    //获取三角坑
                    List<Object> triangularPitList = rowRecords.get(9);
                    String triangularPit = triangularPitList.get(i).toString().trim();

                    if (ObjectUtil.isNotEmpty(triangularPit)
                            && !("三角坑").equals(triangularPit) && !p.matcher(triangularPit).matches()) {
                        movementCourseInfo.setTriangularPit(triangularPit);
                    }
                    //获取方向
                    List<Object> directionList = rowRecords.get(10);
                    String direction = directionList.get(i).toString().trim();

                    if (ObjectUtil.isNotEmpty(direction)
                            && !("方向").equals(direction) && !p.matcher(direction).matches()) {
                        movementCourseInfo.setDirection(direction);
                    }
                    //获取高低
                    List<Object> heightList = rowRecords.get(11);
                    String height = heightList.get(i).toString().trim();

                    if (ObjectUtil.isNotEmpty(height)
                            && !("高低").equals(height) && !p.matcher(height).matches()) {
                        movementCourseInfo.setHeight(height);
                    }
                    //获取结构
                    List<Object> structureList = rowRecords.get(12);
                    String structure = structureList.get(i).toString().trim();

                    if (ObjectUtil.isNotEmpty(structure)
                            && !("结构").equals(structure) && !p.matcher(structure).matches()) {
                        movementCourseInfo.setStructure(structure);
                    }
                    //获取整改
                    List<Object> rectificationList = rowRecords.get(13);
                    String rectification = rectificationList.get(i).toString().trim();

                    if (ObjectUtil.isNotEmpty(rectification)
                            && !("整改").equals(rectification) && !p.matcher(rectification).matches()) {
                        movementCourseInfo.setRectification(rectification);
                    }
                    resultList.add(movementCourseInfo);
                    if (measurePoint % 8 == 0) {
                        measurePoint = 0;
                    }
                }
                if ((skipColumnNum + 2) % 28 == 0) {
                    i = i + 4;
                    skipColumnNum = skipColumnNum + 4;
                    startingAndEndingMileageStr = "";
                    endingMileageStr = "";
                    curveRadius = "";
                    superHigh = "";
                    widen = "";
                    slopeRatio = "";
                    longExtent = "";
                    remark = "";
                    courseId = "";
                    infoSort = 0;
                    movementCourse = new MovementCourse();
                }
            }
            if (resultList != null && resultList.size() > 0) {
                movementCourseInfoService.saveBatch(resultList);
            }

        } catch (Exception e) {
            e.getMessage();
        }
        return Result.ok("操作成功");
    }

    @AutoLog(value = "人工静态检查数据-保存曲线半径信息")
    @ApiOperation(value = "人工静态检查数据-保存曲线半径信息", notes = "人工静态检查数据-保存曲线半径信息")
    @PostMapping(value = "/saveAdditive")
    public Result<String> saveAdditive(@RequestBody MovementCourse record) {
        // 保存人工项目检查表
        record.setId(UUIDGenerator.generate());
        record.setDelFlag("0");
        movementCourseService.save(record);


        // 初始化下面的格子模板
        List<MovementCourseInfo> movementCourseInfos = new ArrayList<>();
        int measurePoint = 1;
        String trackCode = "1";
        for (int i = 0; i < 24; i++) {
            MovementCourseInfo movementCourseInfo = new MovementCourseInfo();
            movementCourseInfo.setMovementMasterId(record.getMovementMasterId());
            movementCourseInfo.setMovementCourseId(record.getId());
            movementCourseInfo.setMeasurePoint(measurePoint);
            movementCourseInfo.setDelFlag("0");
            movementCourseInfo.setTrackCode(trackCode);
            if (measurePoint % 8 == 0) {
                measurePoint = 1;
                trackCode = String.valueOf(Integer.valueOf(trackCode) + 1);
            }
            movementCourseInfos.add(movementCourseInfo);
        }
        movementCourseInfoService.saveBatch(movementCourseInfos);


        return Result.OK("操作成功");
    }

    @AutoLog(value = "人工静态检查数据-更新曲线半径信息")
    @ApiOperation(value = "人工静态检查数据-更新曲线半径信息", notes = "人工静态检查数据-更新曲线半径信息")
    @PostMapping(value = "/updateAdditive")
    public Result<String> updateAdditive(@RequestBody MovementCourse record) {
        // 保存人工项目检查表
        movementCourseService.updateById(record);

        return Result.OK("操作成功");
    }

    @AutoLog(value = "人工静态检查数据-删除曲线半径信息")
    @ApiOperation(value = "人工静态检查数据-删除曲线半径信息", notes = "人工静态检查数据-删除曲线半径信息")
    @GetMapping(value = "/deleteAdditive")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "movementCourseId", required = true, value = "曲线半径信息Id")
    })
    public Result<String> deleteAdditive(String movementCourseId) {
        //删除里程详情
        movementCourseInfoService.lambdaUpdate()
                .eq(MovementCourseInfo::getMovementCourseId, movementCourseId)
                .remove();

        //删除里程相关
        movementCourseService.removeById(movementCourseId);
        return Result.OK("操作成功");
    }


    @AutoLog(value = "人工静态检查数据-更新轨道信息")
    @ApiOperation(value = "人工静态检查数据-更新轨道信息", notes = "人工静态检查数据-更新轨道信息")
    @PostMapping(value = "/updateAdditiveDetail")
    public Result<String> updateAdditiveDetail(@RequestBody MovementCourseInfo record) {
        movementCourseInfoService.updateById(record);

        return Result.OK("操作成功");
    }


    //**********************************添乘仪检查******************************

    /**
     * 查询添乘仪详情
     *
     * @param pageNo
     * @param pageSize
     * @param dto
     * @return
     */
    @AutoLog(value = "查询添乘仪详情")
    @ApiOperation(value = "查询添乘仪详情", notes = "查询添乘仪详情")
    @GetMapping(value = "/getMovementAdditiveInfo")
    public Result<IPage<MovementAdditiveInfoVO>> getMovementAdditiveInfo(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                         MovementAdditiveInfoDTO dto) {
        if (ObjectUtil.isEmpty(dto.getMovementMasterId())) {
            return Result.error("参数不完整");
        }
        Page<MovementAdditiveInfoVO> pageData = new Page<>(pageNo, pageSize);
        pageData = this.service.queryPageAdditiveInfoList(pageData, dto);
        return Result.OK(pageData);
    }

    @AutoLog(value = "添乘仪导入")
    @ApiOperation(value = "添乘仪导入", notes = "添乘仪导入")
    @PostMapping(value = "/uploadAdditive")
    @Transactional
    public Result<String> uploadAdditiveFile(MultipartFile file, @ApiParam(name = "动静态几何尺寸主键id") String id) {
        try {
            //初始化数据模板
            QueryWrapper<MovementAdditiveInfo> rm = new QueryWrapper<>();
            rm.eq("movement_master_id", id);
            movementAdditiveInfoService.remove(rm);

            //读取第一个sheet页的数据
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream(), 0);
            //读取Excel中所有的数据，以行保存
            List<List<Object>> rowRecords = reader.read();
            //获取当前登录人信息
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            String realname = user.getRealname();
            //初始化测点里程
            String pointMileage = "";
            //初始化水平加速度
            String zontalSpeed = "";
            //初始化水平加速度等级
            String zontalSpeedLevel = "";
            //初始化垂直加速度
            String verticalSpeed = "";
            //初始化垂直加速度等级
            String verticalSpeedLevel = "";
            //初始化速度
            String speed = "";
            //初始化手动标记
            String mark = "";
            //初始化添乘仪排序
            int sort = 0;
            //初始化存储结果
            List<MovementAdditiveInfo> result = new ArrayList<>();
            for (int m = 1; m < rowRecords.size(); m++) {
                MovementAdditiveInfo movementAdditiveInfo = new MovementAdditiveInfo();
                sort++;
                for (int i = 0; i < 7; i++) {
                    //获取当前行
                    List<Object> list = rowRecords.get(m);
                    if (ObjectUtil.isNotEmpty(list.get(i))) {
                        //获取测点里程
                        if (i == 0) {
                            pointMileage = list.get(i).toString().trim();
                        }
                        //获取水平加速度
                        if (i == 1) {
                            zontalSpeed = list.get(i).toString().trim();
                        }
                        //获取水平加速度等级
                        if (i == 2) {
                            zontalSpeedLevel = list.get(i).toString().trim();
                        }
                        //垂直加速度
                        if (i == 3) {
                            verticalSpeed = list.get(i).toString().trim();
                        }
                        //垂直加速度等级
                        if (i == 4) {
                            verticalSpeedLevel = list.get(i).toString().trim();
                        }
                        //手工标记
                        if (i == 5) {
                            mark = list.get(i).toString().trim();
                        }
                        //速度
                        if (i == 6) {
                            speed = list.get(i).toString().trim();
                        }
                    }
                }
                movementAdditiveInfo.setId(IdWorker.get32UUID());
                movementAdditiveInfo.setDelFlag("0");
                movementAdditiveInfo.setMovementMasterId(id);
                movementAdditiveInfo.setCreateTime(new Date());
                movementAdditiveInfo.setUpdateTime(new Date());
                movementAdditiveInfo.setCreateBy(realname);
                movementAdditiveInfo.setUpdateBy(realname);
                movementAdditiveInfo.setInfoSort(sort);
                if (ObjectUtil.isNotEmpty(pointMileage)) {
                    movementAdditiveInfo.setPointMileage(new BigDecimal(pointMileage));
                }
                if (ObjectUtil.isNotEmpty(zontalSpeed)) {
                    movementAdditiveInfo.setZontalSpeed(new BigDecimal(zontalSpeed));
                }
                if (ObjectUtil.isNotEmpty(zontalSpeedLevel)) {
                    movementAdditiveInfo.setZontalSpeedLevel(Integer.valueOf(zontalSpeedLevel));
                }
                if (ObjectUtil.isNotEmpty(verticalSpeed)) {
                    movementAdditiveInfo.setVerticalSpeed(new BigDecimal(verticalSpeed));
                }
                if (ObjectUtil.isNotEmpty(verticalSpeedLevel)) {
                    movementAdditiveInfo.setVerticalSpeedLevel(Integer.valueOf(verticalSpeedLevel));
                }
                if (ObjectUtil.isNotEmpty(mark)) {
                    movementAdditiveInfo.setMark(mark);
                }
                if (ObjectUtil.isNotEmpty(verticalSpeed)) {
                    movementAdditiveInfo.setSpeed(new BigDecimal(speed));
                }
                result.add(movementAdditiveInfo);
            }
            if (result != null && result.size() > 0) {
                movementAdditiveInfoService.saveBatch(result);
            }
        } catch (Exception e) {
            e.getMessage();
        }
        return Result.ok("操作成功");
    }

    /**
     * 校验参数
     *
     * @param movementRecordsMaster
     */
    private boolean validate(MovementRecordsMaster movementRecordsMaster) {
        if (ObjectUtil.isEmpty(movementRecordsMaster.getType())) {
            return false;
        }
        if (ObjectUtil.isEmpty(movementRecordsMaster.getEkCode())) {
            return false;
        }
        return true;
    }

}
