package org.dromara.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.system.domain.bo.TblDzbcSiteBo;
import org.dromara.system.domain.TblDzbcSitePrice;
import org.dromara.system.domain.vo.*;
import org.dromara.system.mapper.TblDzbcSitePriceMapper;
import org.dromara.system.service.ITblDzbcAreaService;
import org.dromara.system.service.ITblDzbcPathService;
import org.dromara.system.service.ITblDzbcPathSiteService;
import org.dromara.system.service.ITblDzbcSiteService;
import org.dromara.util.DistanceCalculator;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.system.domain.vo.TblDzbcPathSchedulingVo;
import org.dromara.system.domain.bo.TblDzbcPathSchedulingBo;
import org.dromara.system.service.ITblDzbcPathSchedulingService;
import org.dromara.common.mybatis.core.page.TableDataInfo;

/**
 * 定制班车-路线排班
 *
 * @author Lion Li
 * @date 2025-02-12
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/dzbcPathScheduling")
public class TblDzbcPathSchedulingController extends BaseController {

    private final ITblDzbcPathSchedulingService tblDzbcPathSchedulingService;
    private final ITblDzbcPathService tblDzbcPathService;
    private final ITblDzbcPathSiteService tblDzbcPathSiteService;
    private final ITblDzbcSiteService tblDzbcSiteService;
    private final ITblDzbcAreaService tblDzbcAreaService;
    private final TblDzbcSitePriceMapper sitePriceMapper;

    /**
     * 查询定制班车-路线排班列表
     */
    //@SaCheckPermission("system:dzbcPathScheduling:list")
    @GetMapping("/list")
    public TableDataInfo<TblDzbcPathSchedulingVo> list(TblDzbcPathSchedulingBo bo, PageQuery pageQuery) {
        return tblDzbcPathSchedulingService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出定制班车-路线排班列表
     */
    //@SaCheckPermission("system:dzbcPathScheduling:export")
    @Log(title = "定制班车-路线排班", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TblDzbcPathSchedulingBo bo, HttpServletResponse response) {
        List<TblDzbcPathSchedulingVo> list = tblDzbcPathSchedulingService.queryList(bo);
        ExcelUtil.exportExcel(list, "定制班车-路线排班", TblDzbcPathSchedulingVo.class, response);
    }

    /**
     * 获取定制班车-路线排班详细信息
     *
     * @param id 主键
     */
    //@SaCheckPermission("system:dzbcPathScheduling:query")
    @GetMapping("/{id}")
    public R<TblDzbcPathSchedulingVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        TblDzbcPathSchedulingVo  vo = tblDzbcPathSchedulingService.queryById(id);
        if(vo==null){
            return R.fail("未找到该排班");
        }
        return R.ok(vo);
    }

    /**
     * 新增定制班车-路线排班
     */
    //@SaCheckPermission("system:dzbcPathScheduling:add")
    @Log(title = "定制班车-路线排班", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody TblDzbcPathSchedulingBo bo) {
        return toAjax(tblDzbcPathSchedulingService.insertByBo(bo));
    }

    /**
     * 修改定制班车-路线排班
     */
    //@SaCheckPermission("system:dzbcPathScheduling:edit")
    @Log(title = "定制班车-路线排班", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody TblDzbcPathSchedulingBo bo) {
        return toAjax(tblDzbcPathSchedulingService.updateByBo(bo));
    }

    /**
     * 删除定制班车-路线排班
     *
     * @param ids 主键串
     */
    //@SaCheckPermission("system:dzbcPathScheduling:remove")
    @Log(title = "定制班车-路线排班", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(tblDzbcPathSchedulingService.deleteWithValidByIds(List.of(ids), true));
    }


    /**
     * 获取定制班车-余票
     * @param searchDate
     * @param fromareaId
     * @param toareaId
     * @return
     */
    @Log(title = "定制班车-路线排班余票", businessType = BusinessType.FORCE)
    @GetMapping("/getCarTickets")
    public R<Object> getCarTickets(@RequestParam(required = true) String searchDate,
                                   @RequestParam(required = true) Long fromareaId,
                                   @RequestParam(required = true) Long toareaId,
                                   @RequestParam(required = false) Integer type) {
        Date date;
        try{
            date =  DateUtil.parseDate(searchDate);
        }catch (Exception e){
            return R.fail("日期格式不正确 eg:2025-02-01");
        }

        // 优化：直接根据日期构建Redis Key，避免 keys * 扫描和加载所有日期数据
        String redisKey = StrUtil.format("dzbc_path_scheduling|{}", DateUtil.formatDate(date));
        Map<String, TblDzbcPathSchedulingVo> dataMap = RedisUtils.getCacheMap(redisKey);

        // 如果缓存为空，则查询数据库加载当天数据
        if (dataMap == null || dataMap.isEmpty()) {
            TblDzbcPathSchedulingBo bo = new TblDzbcPathSchedulingBo();
            // 精确匹配日期
            bo.setMdate(date);
            List<TblDzbcPathSchedulingVo> schedulingList = tblDzbcPathSchedulingService.queryList(bo);

            if (schedulingList != null && !schedulingList.isEmpty()) {
                dataMap = new HashMap<>();
                for (TblDzbcPathSchedulingVo vo : schedulingList) {
                    dataMap.put(vo.getId().toString(), vo);
                }
                // 存入 Redis，设置过期时间
                RedisUtils.setCacheMap(redisKey, dataMap);
                // 默认过期时间设置为 24 小时后，或者当天的 24 小时后
                long expireTime = DateUtil.offset(date, DateField.HOUR_OF_DAY, 24).getTime() - DateUtil.current();
                if (expireTime > 0) {
                    RedisUtils.expire(redisKey, Duration.ofMillis(expireTime));
                } else {
                    RedisUtils.expire(redisKey, Duration.ofHours(2));
                }
            }
        }

        if(dataMap == null || dataMap.isEmpty()){
            return R.fail("没有排班信息");
        }

        Date finalDate = date;
        // 过滤符合条件的排班
        List<TblDzbcPathSchedulingVo> carTickets = dataMap.values().stream().filter(item -> {
            if (type != null) {
                if (!Objects.equals(item.getType(), type)) {
                    return false;
                }
            } else {
                if (item.getType() != null && item.getType() == 2) {
                    return false;
                }
            }

            if(item.getExt1()!=null){
                try {
                    JSONObject dataObject = JSONUtil.parseObj(item.getExt1()).getJSONObject("pathInfo");
                    if(dataObject != null &&
                       Objects.equals(dataObject.getLong("startArea"), fromareaId) &&
                       Objects.equals(dataObject.getLong("endArea"), toareaId)){

                        // 简单的过期校验
                        if(item.getMdate().getTime() - finalDate.getTime() > 3600*1000){
                             return false;
                        }
                        return true;
                    }
                } catch (Exception e) {
                    // ignore parse error
                }
            }
            return false;
        }).collect(Collectors.toList());

        if(carTickets.isEmpty()){return R.fail("没有排班信息");}

        // 批量查询 Path 信息，解决 N+1 问题
        Set<Long> pathIds = carTickets.stream()
            .map(TblDzbcPathSchedulingVo::getPathId)
            .filter(Objects::nonNull)
            .collect(Collectors.toSet());

        Map<Long, TblDzbcPathVo> pathMap = new HashMap<>();
        if (!pathIds.isEmpty()) {
            List<TblDzbcPathVo> paths = tblDzbcPathService.queryByIds(pathIds);
            pathMap = paths.stream().collect(Collectors.toMap(TblDzbcPathVo::getId, java.util.function.Function.identity(), (k1, k2) -> k1));
        }

        // 计算余票
        for (TblDzbcPathSchedulingVo carTicket : carTickets) {
            //先计算车辆座位数
            if(carTicket.getExt1() != null){
                try {
                    JSONObject data = JSONUtil.parseObj(carTicket.getExt1());
                    JSONObject carInfo = data.getJSONObject("carInfo");
                    Integer zw =  carInfo.getInt("carZw");
                    carTicket.setTicket(zw);
                }
                catch (Exception e){
                    carTicket.setTicket(0);
                    carTicket.setCarStatus("已售罄");
                }
            }else{
                carTicket.setTicket(0);
                carTicket.setCarStatus("已售罄");
            }

            if(carTicket.getExt2() != null){
                try {
                    AtomicInteger salszw = new AtomicInteger();
                    JSONObject data = JSONUtil.parseObj(carTicket.getExt2());
                    data.keySet().stream().forEach( orderid -> {
                        if ("type".equals(orderid)) {
                            return;
                        }
                        JSONObject order = data.getJSONObject(orderid);
                        if (order != null && order.containsKey("zw")) {
                            salszw.addAndGet(order.getInt("zw"));
                        }
                    } );
                    carTicket.setTicket(carTicket.getTicket() - salszw.get());
                    if(carTicket.getTicket()<1){
                        carTicket.setCarStatus("已售罄");
                    }else{
                        if(carTicket.getTicket()<4){
                            carTicket.setCarStatus("余票紧张");
                        }else{
                            carTicket.setCarStatus("余票充足");
                        }
                    }
                }
                catch (Exception e){
                    carTicket.setTicket(0);
                    carTicket.setCarStatus("已售罄");
                }

            }
            try {
                //如果超出时间余票为0
                if(carTicket.getMtime()==null||carTicket.getMtime().equals("")){
                    // 使用批量查询的 Map 获取 PathVo
                    TblDzbcPathVo pathVo = pathMap.get(carTicket.getPathId());
                    if(pathVo != null){
                        carTicket.setMtime(pathVo.getCostTime());
                    }
                }
                if(carTicket.getMtime()!=null && !carTicket.getMtime().equals("")){
                    Date datec =  DateUtil.parse(DateUtil.formatDate(carTicket.getMdate())+" "+carTicket.getMtime(), DatePattern.NORM_DATETIME_FORMAT);
                    if(datec.getTime() < DateUtil.current()){
                        carTicket.setTicket(0);
                        carTicket.setCarStatus("已发车");
                    }
                }
            } catch (Exception e) {

            }
        }

        return R.ok(carTickets);
    }

    @Log(title = "定制班车-多站点路线排班余票", businessType = BusinessType.FORCE)
    @GetMapping("/getMultiSiteCarTickets")
    public R<Object> getMultiSiteCarTickets(@RequestParam(required = true) String searchDate,
                                            @RequestParam(required = true) Long pathId,
                                            @RequestParam(required = true) Long fromsiteId,
                                            @RequestParam(required = true) Long tositeId) {
        Date date = new Date();
        try{
            date =  DateUtil.parseDate(searchDate);
        }catch (Exception e){
            return R.fail("日期格式不正确 eg:2025-02-01");
        }
        if (Objects.equals(fromsiteId, tositeId)) {
            return R.fail("起点和终点不能相同");
        }
        List<TblDzbcPathSiteVo> pathSites = tblDzbcPathSiteService.queryByPathId(pathId);
        if (pathSites == null || pathSites.isEmpty()) {
            return R.fail("未查询到路线站点");
        }
        Map<Long, Integer> siteOrderMap = pathSites.stream()
            .filter(site -> site.getSiteId() != null && site.getSiteOrder() != null)
            .collect(Collectors.toMap(TblDzbcPathSiteVo::getSiteId, TblDzbcPathSiteVo::getSiteOrder, (a, b) -> a));
        Integer fromOrder = siteOrderMap.get(fromsiteId);
        Integer toOrder = siteOrderMap.get(tositeId);
        if (fromOrder == null || toOrder == null) {
            return R.fail("站点不在该路线内");
        }
        if (fromOrder >= toOrder) {
            return R.fail("站点顺序不正确");
        }

        Collection ret = RedisUtils.keys("dzbc_path_scheduling");
        if (ret == null||ret.size()<1) {
            TblDzbcPathSchedulingBo bo = new TblDzbcPathSchedulingBo();
            bo.getParams().put("mdate", DateUtil.today());
            List<TblDzbcPathSchedulingVo> allTblDzbcPathScheduling = tblDzbcPathSchedulingService.queryList(bo);
            for (TblDzbcPathSchedulingVo tblDzbcPathSchedulingVo : allTblDzbcPathScheduling) {
                Map<String, TblDzbcPathSchedulingVo> dataMap =  RedisUtils.getCacheMap(StrUtil.format("dzbc_path_scheduling|{}", DateUtil.formatDate(tblDzbcPathSchedulingVo.getMdate())));
                if(dataMap == null||dataMap.size()<1) dataMap =new HashMap<>();
                dataMap.put(tblDzbcPathSchedulingVo.getId().toString(), tblDzbcPathSchedulingVo);
                RedisUtils.setCacheMap(StrUtil.format("dzbc_path_scheduling|{}", DateUtil.formatDate(tblDzbcPathSchedulingVo.getMdate())), dataMap);
                RedisUtils.expire(StrUtil.format("dzbc_path_scheduling|{}", DateUtil.formatDate(tblDzbcPathSchedulingVo.getMdate())), DateUtil.offset(tblDzbcPathSchedulingVo.getMdate(), DateField.HOUR_OF_DAY, 24).getTime() - DateUtil.current());
            }
        }
        Map<String, TblDzbcPathSchedulingVo> dataMap = RedisUtils.getCacheMap(StrUtil.format("dzbc_path_scheduling|{}", DateUtil.formatDate(date)));
        if(dataMap == null||dataMap.size()<1){
            return  R.fail("没有排班信息");
        }else{
            Date finalDate = date;
            List<TblDzbcPathSchedulingVo> carTickets = dataMap.values().stream().filter(item -> {
                if (item.getType() == null || item.getType() != 2) {
                    return false;
                }
                if (!Objects.equals(item.getPathId(), pathId)) {
                    return false;
                }
                if(item.getMdate().getTime()- finalDate.getTime()> 3600*1000){
                    dataMap.remove(item.getId());
                    RedisUtils.setCacheMap(StrUtil.format("dzbc_path_scheduling|{}", DateUtil.formatDate(finalDate)), dataMap);
                    return false;
                }
                return true;
            }).collect(Collectors.toList());

            if(carTickets.size()<1){return  R.fail("没有排班信息");}

            for (TblDzbcPathSchedulingVo carTicket : carTickets) {
                if(carTicket.getExt1() != null){
                    try {
                        JSONObject data = JSONUtil.parseObj(carTicket.getExt1());
                        JSONObject carInfo = data.getJSONObject("carInfo");
                        Integer zw =  carInfo.getInt("carZw");
                        carTicket.setTicket(zw);
                    }
                    catch (Exception e){
                        carTicket.setTicket(0);
                        carTicket.setCarStatus("已售罄");
                    }
                }else{
                    carTicket.setTicket(0);
                    carTicket.setCarStatus("已售罄");
                }

                if (carTicket.getTicket() != null && carTicket.getTicket() > 0) {
                    int sold = 0;
                    if (StrUtil.isNotBlank(carTicket.getStartSites())) {
                        try {
                            JSONObject startSites = JSONUtil.parseObj(carTicket.getStartSites());
                            for (String siteKey : startSites.keySet()) {
                                JSONObject siteOrders = startSites.getJSONObject(siteKey);
                                if (siteOrders == null) {
                                    continue;
                                }
                                for (String orderKey : siteOrders.keySet()) {
                                    if ("siteInfo".equals(orderKey)) {
                                        continue;
                                    }
                                    Object orderData = siteOrders.get(orderKey);
                                    if (orderData == null) {
                                        continue;
                                    }
                                    JSONObject orderJson = JSONUtil.parseObj(orderData);
                                    Integer zw = orderJson.getInt("zw");
                                    Long orderStartId = orderJson.getLong("startSiteId");
                                    Long orderEndId = orderJson.getLong("endSiteId");
                                    if (zw == null || orderStartId == null || orderEndId == null) {
                                        continue;
                                    }
                                    Integer orderStart = siteOrderMap.get(orderStartId);
                                    Integer orderEnd = siteOrderMap.get(orderEndId);
                                    if (orderStart == null || orderEnd == null) {
                                        continue;
                                    }
                                    if (orderStart < toOrder && orderEnd > fromOrder) {
                                        sold += zw;
                                    }
                                }
                            }
                        } catch (Exception e) {
                        }
                    }
                    carTicket.setTicket(carTicket.getTicket() - sold);
                    if(carTicket.getTicket()<1){
                        carTicket.setTicket(0);
                        carTicket.setCarStatus("已售罄");
                    }else{
                        if(carTicket.getTicket()<4){
                            carTicket.setCarStatus("余票紧张");
                        }else{
                            carTicket.setCarStatus("余票充足");
                        }
                    }
                }

                try {
                    if(carTicket.getMtime()!=null && !carTicket.getMtime().equals("")){
                        Date datec =  DateUtil.parse(DateUtil.formatDate(carTicket.getMdate())+" "+carTicket.getMtime(), DatePattern.NORM_DATETIME_FORMAT);
                        if(datec.getTime() < DateUtil.current()){
                            carTicket.setTicket(0);
                            carTicket.setCarStatus("已发车");
                        }
                    }
                } catch (Exception e) {

                }
            }

            return R.ok(carTickets);
        }
    }

    @Log(title = "定制班车-多站点路线排班票价", businessType = BusinessType.FORCE)
    @GetMapping("/getMultiSitePrice")
    public R<Object> getMultiSitePrice(@RequestParam(required = true) Long schedulingId,
                                       @RequestParam(required = true) Long fromsiteId,
                                       @RequestParam(required = true) Long tositeId) {
        TblDzbcPathSchedulingVo scheduling = tblDzbcPathSchedulingService.queryById(schedulingId);
        if(scheduling==null) return R.fail("排班信息不存在");
        if (scheduling.getType() == null || scheduling.getType() != 2) {
            return R.fail("不是多站点路线排班");
        }
        TblDzbcSitePriceVo priceVo = sitePriceMapper.selectVoOne(
            new LambdaQueryWrapper<TblDzbcSitePrice>()
                .eq(TblDzbcSitePrice::getPathId, scheduling.getPathId())
                .eq(TblDzbcSitePrice::getFromSiteId, fromsiteId)
                .eq(TblDzbcSitePrice::getToSiteId, tositeId)
        );
        if (priceVo == null) {
            return R.fail("未查询到该行程的票价信息");
        }
        int finalResult = Math.round(((int)Math.round(priceVo.getPrice() + scheduling.getPprice()) + 5) / 100) * 100;
        scheduling.setPrice(finalResult);
        return R.ok(scheduling);
    }

    /**
     * 获取定制班车-票价
     * @param schedulingId
     * @param fromsiteId
     * @param tositeId
     * @return
     */
    @GetMapping("/getPrice")
    @Log(title = "定制班车-路线排班票价", businessType = BusinessType.FORCE)
    public R<Object> getCarTickets(@RequestParam(required = true) Long schedulingId,@RequestParam(required = false) Long fromsiteId,@RequestParam(required = false) Long tositeId){
        TblDzbcPathSchedulingVo tblDzbcPathSchedulingVo = tblDzbcPathSchedulingService.queryById(schedulingId);
        if(tblDzbcPathSchedulingVo==null) return R.fail("排班信息不存在");
        JSONObject dataObject = JSONUtil.parseObj(tblDzbcPathSchedulingVo.getExt1()).getJSONObject("pathInfo");
        Long fromareaId = dataObject.getLong("startArea");
        Long toareaId = dataObject.getLong("endArea");

        //计算票价
        if(fromsiteId!=null && tositeId!=null){
            try {
                //查询起点  //查询终点
                TblDzbcSiteVo startSite = tblDzbcSiteService.queryById(fromsiteId);
                TblDzbcSiteVo endSite = tblDzbcSiteService.queryById(tositeId);
                TblDzbcAreaVo startArea = tblDzbcAreaService.queryById(fromareaId);
                TblDzbcAreaVo toArea = tblDzbcAreaService.queryById(toareaId);

                // === 多站点路线价格计算逻辑 ===
                if (tblDzbcPathSchedulingVo.getType() != null && tblDzbcPathSchedulingVo.getType() == 2) {
                     TblDzbcSitePriceVo priceVo = sitePriceMapper.selectVoOne(
                        new LambdaQueryWrapper<TblDzbcSitePrice>()
                            .eq(TblDzbcSitePrice::getPathId, tblDzbcPathSchedulingVo.getPathId())
                            .eq(TblDzbcSitePrice::getFromSiteId, fromsiteId)
                            .eq(TblDzbcSitePrice::getToSiteId, tositeId)
                     );
                     if (priceVo != null) {
                         // 基础票价 + 排班加价
                         int finalResult = Math.round(((int)Math.round(priceVo.getPrice() + tblDzbcPathSchedulingVo.getPprice()) + 5) / 100) * 100;
                         tblDzbcPathSchedulingVo.setPrice(finalResult);
                     } else {
                         return R.fail("未查询到该行程的票价信息");
                     }
                     return R.ok(tblDzbcPathSchedulingVo);
                }

                if(!startSite.getAreaId().equals(fromareaId) || !endSite.getAreaId().equals(toareaId) ){
                    return  R.fail("站点未与区域对应");
                }
                if(fromareaId.equals(toareaId)){
                    return  R.fail("不能是同一区域");
                }
                double distanceArea = DistanceCalculator.calculateDistance(startArea.getLocation(),toArea.getLocation());
                double distanceSite = DistanceCalculator.calculateDistance(startSite.getLocation(),endSite.getLocation());

                try{
                    TblDzbcPathVo pathVo = tblDzbcPathService.queryById(tblDzbcPathSchedulingVo.getPathId());
                    JSONObject ext1 = dataObject.getJSONObject("ext1");
                    if(pathVo!=null && pathVo.getExt1()!=null){
                        ext1 = JSONUtil.parseObj(pathVo.getExt1()) ;
                    }
                    if(ext1!=null){
                        //获取区域价格
                        JSONArray prices = ext1.getJSONArray("jgqj");
                        //获取距离
                        Double distance = ext1.getDouble("jl");
                        //获取价格系数
                        Double jgxs = ext1.getDouble("jgxs");

                        if(jgxs==null) jgxs = 0.0;
                        if(distance==null) distance = distanceArea;
                        double distanceSite1 = distanceSite*distance/distanceArea;
                        if(prices!=null && prices.size()>0){
                            for (int i = 0; i < prices.size(); i++) {
                                JSONObject price = prices.getJSONObject(i);
                                Double min = price.getDouble("min");
                                Double max = price.getDouble("max");
                                Double xs = price.getDouble("xs");
                                Double p = price.getDouble("price");
                                if(min==null) min = 0.0;
                                if(max==null) max = Double.MAX_VALUE;
                                if(xs==null) xs = 0.0;
                                if(distanceSite1>=min && distanceSite1<=max){
                                    double jg = (p*100)+(((distanceSite1-min)/1000.0)*xs)*100;
                                    int finalResult = Math.round(((int) Math.round(jg) + 5) / 100) * 100;
                                    tblDzbcPathSchedulingVo.setPrice(finalResult);
                                    break;
                                }
                            }

                        }



                    }

                }catch (Exception e){
                    return R.fail("路线价格错误");
                }
                if(tblDzbcPathSchedulingVo.getPrice()==null){
                    Integer price1 = dataObject.getInt("price");
                    if(price1==null) return R.fail("路线价格未设置");
                    //单价 根据区域-区域 单价及站点-站点 计算价格
                    double price = price1*(distanceSite/distanceArea);
                    int finalResult = Math.round(((int)Math.round(price+tblDzbcPathSchedulingVo.getPprice()) + 5) / 100) * 100;
                    //计算加价
                    tblDzbcPathSchedulingVo.setPrice(finalResult);
                }
            } catch (Exception e) {
                return  R.fail("站点信息错误");
            }
        }
        return R.ok(tblDzbcPathSchedulingVo);
    }
}
