package org.jeecg.modules.deviceAsset.controller;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
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.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.modules.deviceAsset.dto.TrackBedManagementDTO;
import org.jeecg.modules.deviceAsset.entity.TrackBedManagement;
import org.jeecg.modules.deviceAsset.service.ITrackBedManagementService;
import org.jeecg.modules.deviceAsset.vo.TrackBedManagementVO;
import org.jeecg.modules.subwayNetwork.entity.LightRail;
import org.jeecg.modules.subwayNetwork.entity.LineAlias;
import org.jeecg.modules.subwayNetwork.service.ILightRailService;
import org.jeecg.modules.subwayNetwork.service.ILineAliasService;
import org.jeecg.modules.utils.UnitCodeUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 资产管理-道床管理 前端控制器
 * </p>
 *
 * @author hkl
 * @since 2023-07-06
 */
@RestController
@RequestMapping("/deviceAsset/trackBedManagement")
@Api(tags = "资产管理-道床管理")
public class TrackBedManagementController extends JeecgController<TrackBedManagement, ITrackBedManagementService> {
    @Resource
    private ILightRailService lightRailService;

    @Resource
    private ILineAliasService lineAliasService;

    @AutoLog(value = "资产管理-道床管理-分页列表查询")
    @ApiOperation(value = "资产管理-道床管理-分页列表查询", notes = "资产管理-道床管理-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<TrackBedManagementVO>> queryPageList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                             TrackBedManagementDTO dto) {
        Page<TrackBedManagementVO> pageData = new Page<>(pageNo, pageSize);
        pageData = this.service.queryPageList(pageData, dto);
        return Result.OK(pageData);
    }


    @AutoLog(value = "资产管理-道床管理-编辑")
    @ApiOperation(value = "资产管理-道床管理-编辑", notes = "资产管理-道床管理-编辑")
    @PostMapping(value = "/edit")
    public Result<String> edit(@RequestBody TrackBedManagement trackBedManagement) {
        // 1.验证参数
        verifyEditParams(trackBedManagement);


        // 2.执行保存
        if (ObjectUtil.isEmpty(trackBedManagement.getId())) {
            trackBedManagement.setId(UUIDGenerator.generate());
            trackBedManagement.setTrackBedCode(UnitCodeUtil.trackBedManagementUtil(trackBedManagement.getLineAliasId()));
            this.service.save(trackBedManagement);
        } else {
            this.service.updateById(trackBedManagement);
        }

        return Result.OK("编辑成功!");
    }

    /**
     * 验证参数
     *
     * @param trackBedManagement
     */
    private void verifyEditParams(TrackBedManagement trackBedManagement) {
        LightRail lightRail = lightRailService.getById(trackBedManagement.getLightRailId());
        LineAlias lineAlias = lineAliasService.getById(trackBedManagement.getLineAliasId());
        BigDecimal lightRailEndMileage = lightRail.getUpLineMileage();
        if (lineAlias.getLineAliasName().contains("下行")) {
            lightRailEndMileage = lightRail.getDownLineMileage();
        }
        if (trackBedManagement.getEndMileage().compareTo(lightRailEndMileage) > 0) {
            throw JeecgBootException.error("新增道床结束里程超过:" + lightRail.getRailLineName() + "的" + lineAlias.getLineAliasName() + "的结束里程【" + lightRailEndMileage + "】");
        }

        List<TrackBedManagement> listRecord = this.service.lambdaQuery()
                .eq(TrackBedManagement::getSectionId, trackBedManagement.getSectionId())
                .eq(TrackBedManagement::getLineAliasId, trackBedManagement.getLineAliasId())
                .orderByDesc(TrackBedManagement::getStartingMileage)
                .list();

        for (TrackBedManagement record : listRecord) {

            // 如果是更新，排除自己
            if (record.getId().equals(trackBedManagement.getId())) {
                continue;
            }
            BigDecimal currentStartMileage = record.getStartingMileage();
            BigDecimal currentEndMileage = record.getEndMileage();
            String deviceCode = record.getTrackBedCode();

            BigDecimal startMileage = trackBedManagement.getStartingMileage();
            BigDecimal endMileage = trackBedManagement.getEndMileage();


            // 判断区间是否重叠
            if (currentStartMileage.compareTo(startMileage) >= 0 && currentEndMileage.compareTo(endMileage) <= 0) {
                throw JeecgBootException.error("和【道床编号:" + deviceCode + "】里程冲突");
            }

            // 判断开始里程是否是否冲突
            if (currentStartMileage.compareTo(startMileage) < 0 && currentEndMileage.compareTo(startMileage) > 0) {
                throw JeecgBootException.error("和【道床编号:" + deviceCode + "】里程冲突");
            }

            // 判断结束里程是否是否冲突
            if (currentStartMileage.compareTo(endMileage) < 0 && currentEndMileage.compareTo(endMileage) > 0) {
                throw JeecgBootException.error("和【道床编号:" + deviceCode + "】里程冲突");
            }
        }
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "资产管理-道床管理-通过id删除")
    @ApiOperation(value = "资产管理-道床管理-通过id删除", notes = "资产管理-道床管理-通过id删除")
    @GetMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        this.service.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "资产管理-道床管理-批量删除")
    @ApiOperation(value = "资产管理-道床管理-批量删除", notes = "资产管理-道床管理-批量删除")
    @GetMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.service.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    @AutoLog(value = "资产管理-道床管理-查询列表")
    @ApiOperation(value = "资产管理-道床管理-查询列表", notes = "资产管理-道床管理-查询列表")
    @GetMapping(value = "/queryList")
    public Result<List<TrackBedManagement>> queryList(@ApiParam(name = "区间id") String sectionId,
                                                      @ApiParam(name = "线别id") String lineAliasId) {
        List<TrackBedManagement> listResult = this.service.lambdaQuery()
                .eq(ObjectUtil.isNotEmpty(sectionId), TrackBedManagement::getSectionId, sectionId)
                .eq(ObjectUtil.isNotEmpty(lineAliasId), TrackBedManagement::getLineAliasId, lineAliasId)
                .list();
        return Result.OK(listResult);
    }


    @AutoLog(value = "资产管理-道床管理-校验道床编码重复")
    @ApiOperation(value = "资产管理-道床管理-校验道床编码重复", notes = "资产管理-道床管理-校验道床编码重复")
    @GetMapping(value = "/checkTrackBedCodeRepeat")
    public Result<String> checkTrackBedCodeRepeat(String id, String lightRailId, String trackBedCode) {
        Long count = 0L;
        if (ObjectUtil.isNotEmpty(lightRailId)) {
            count = this.service.checkTrackBedCodeRepeat(id, lightRailId, trackBedCode);
        }
        if (count > 0) {
            throw JeecgBootException.error("");
        }
        return Result.OK("未重复");
    }

}
