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


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.modules.checkData.equipmentCheckData.dto.MovementRecordsMasterDTO;
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.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.LineAlias;
import org.jeecg.modules.subwayNetwork.entity.SubwaySection;
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.jeecg.common.system.base.controller.JeecgController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
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;

    /**
     * 动静态几何尺寸数据-分页列表查询
     *
     * @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 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::getCreateTime)
                .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<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")
                .orderByDesc(MovementCourseInfo::getTrackCode)
                .list();
        //初始化最终返回的集合
        List<MovementCourseInfoOneVO> resultList = new ArrayList<>();
        if (listResult != null && listResult.size() > 0) {
            //获取去重后的项目名称的集合
            Set<String> trackCodeList = listResult.stream().map(MovementCourseInfo::getTrackCode).collect(Collectors.toSet());
            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);
    }

    /**
     * 动静态几何尺寸数据新增时初始化回显数据
     *
     * @param subwaySectionId 区间id
     * @param lightRailId     线路id
     * @param lineAliasId     线别id
     * @return
     */
    @AutoLog(value = "动静态几何尺寸数据新增时初始化回显数据")
    @ApiOperation(value = "动静态几何尺寸数据新增时初始化回显数据", notes = "动静态几何尺寸数据新增时初始化回显数据")
    @GetMapping(value = "/getMovementQuery")
    public Result<MovementSavaQueryVO> getMovementQuery(@ApiParam(name = "区间id", required = true) String subwaySectionId, @ApiParam(name = "线路id", required = true) String lightRailId, @ApiParam(name = "线别id", required = true) String lineAliasId) {
        MovementSavaQueryVO result = new MovementSavaQueryVO();
        result.setSubwaySectionId(subwaySectionId);
        result.setLightRailId(lightRailId);
        result.setLineAliasId(lineAliasId);
        //查询区间起始终点里程
        LambdaQueryWrapper<SubwaySection> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(SubwaySection::getId, subwaySectionId);
        lambdaQuery.eq(SubwaySection::getLightRailId, lightRailId);
        lambdaQuery.eq(SubwaySection::getLineAliasId, lineAliasId);
        SubwaySection bean = subwaySectionService.getOne(lambdaQuery);
        if (bean != null) {
            if (bean.getSectionStartingMileage() != null) {
                result.setStartingMileage(bean.getSectionStartingMileage());
            }
            if (bean.getSectionEndMileage() != null) {
                result.setEndMileage(bean.getSectionEndMileage());
            }
            if(ObjectUtil.isNotEmpty(bean.getSectionName())){
                result.setSubwaySectionName(bean.getSectionName());
            }
            if(ObjectUtil.isNotEmpty(bean.getLightRailName())){
                result.setLightRailName(bean.getLightRailName());
            }
        }
        //查询区间起始终点里程
        result.setLineAliasName(lineAliasService.getById(lineAliasId).getLineAliasName());
        //TODO 后期改造完补充逻辑
        result.setRailNum(25);
        result.setCurveNum(30);
        result.setVerticalCurveNum(58);
        result.setSwitchNum(38);
        return Result.OK(result);
    }

    @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
     * @return
     */
    @AutoLog(value = "删除动静态几何尺寸数据及相关联的数据")
    @ApiOperation(value = "删除动静态几何尺寸数据及相关联的数据", notes = "删除动静态几何尺寸数据及相关联的数据")
    @GetMapping(value = "/delete")
    public Result<String> delete(@ApiParam(name = "动静态几何尺寸数据id", required = true) String id) {
        //删除里程详情
        LambdaUpdateWrapper<MovementCourseInfo> lambdaUpdateWrapper = Wrappers.lambdaUpdate();
        lambdaUpdateWrapper.set(MovementCourseInfo::getDelFlag, "1");
        lambdaUpdateWrapper.eq(MovementCourseInfo::getMovementMasterId, id);
        movementCourseInfoService.update(lambdaUpdateWrapper);
        //删除里程相关
        LambdaUpdateWrapper<MovementCourse> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.set(MovementCourse::getDelFlag, "1");
        updateWrapper.eq(MovementCourse::getMovementMasterId, id);
        movementCourseService.update(updateWrapper);
        //删除动静态几何尺寸数据
        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")
//    @ResponseBody
//    public Result<String> uploadFile(MultipartFile file) throws IOException {
//        byte[] bytes = file.getBytes();
//        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
//        ExcelUtil.getReader(bis);
//        return Result.ok("操作成功");
//    }
    /**
     * 校验参数
     *
     * @param movementRecordsMaster
     */
    private boolean validate(MovementRecordsMaster movementRecordsMaster) {
        if (ObjectUtil.isEmpty(movementRecordsMaster.getType())) {
            return false;
        }
        if (ObjectUtil.isEmpty(movementRecordsMaster.getSubwaySectionName())) {
            return false;
        }
        if (ObjectUtil.isEmpty(movementRecordsMaster.getSubwaySectionId())) {
            return false;
        }
        if (ObjectUtil.isEmpty(movementRecordsMaster.getLightRailName())) {
            return false;
        }
        if (ObjectUtil.isEmpty(movementRecordsMaster.getLightRailId())) {
            return false;
        }
        if (ObjectUtil.isEmpty(movementRecordsMaster.getLineAliasName())) {
            return false;
        }
        if (ObjectUtil.isEmpty(movementRecordsMaster.getLineAliasId())) {
            return false;
        }
        if (ObjectUtil.isEmpty(movementRecordsMaster.getEkCode())) {
            return false;
        }
        return true;
    }

}
