package com.aircraft.modules.route.controller;

import com.aircraft.modules.route.domain.CpRoute;
import com.aircraft.modules.route.domain.dto.CpRouteDTO;
import com.aircraft.modules.route.domain.dto.CpRouteVo;
import com.aircraft.modules.route.mapper.CpRouteMapper;
import com.aircraft.modules.system.mapper.UserMapper;
import com.aircraft.modules.route.service.CpRouteService;
import com.aircraft.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.net.URI;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.aircraft.utils.SecurityUtils.getCurrentUserId;

/**
 * <p>
 * 路线表 前端控制器
 * </p>
 *
 * @author cli
 * @since 2025-07-11
 */
@Api(tags = "系统：路线管理")
@RestController
@RequestMapping("/cpRoute")
public class CpRouteController {
    private static final Logger LOG = LoggerFactory.getLogger(CpRouteController.class);

    @Autowired
    private CpRouteService entityService;
    @Autowired
    private CpRouteMapper cpRouteMapper;

    @ApiOperation(value = "分页查询路线（name模糊查询）", notes = "分页查询路线，可根据路线名称进行模糊搜索")
    @RequestMapping(method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "size", value = "分页大小", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面：从1开始", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "路线名称关键词，用于模糊查询", paramType = "query"),
            @ApiImplicitParam(name = "areaId", value = "通过区域id查询路线", paramType = "query"),
            @ApiImplicitParam(name = "scenicId", value = "通过景区id查询路线", paramType = "query")
    })
    public ResponseEntity<IPage<CpRouteVo>> findByPage(
            final Page<CpRouteVo> page, CpRouteDTO cpRouteDTO) {
        try {
            IPage<CpRouteVo> records = entityService.findByPage(page, cpRouteDTO);
            return new ResponseEntity<>(records, HttpStatus.OK);
        } catch (Exception e) {
            LOG.error("分页查询路线时出错", e);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @ApiOperation(value = "删除路线")
    @RequestMapping(value = "{id}", method = {RequestMethod.DELETE})
    @ApiImplicitParam(name = "id", value = "路线ID", required = true, paramType = "path")
    public ResponseEntity<Void> delete(@PathVariable final Long id) {
        try {
            CpRoute cpRoute = entityService.getById(id);
            if (cpRoute == null) {
                return ResponseEntity.notFound().build();
            }
            cpRoute.setDelFlag(1);
            entityService.updateDelFlagById(id, cpRoute.getDelFlag());
            return ResponseEntity.noContent().build();
        } catch (DataIntegrityViolationException e) {
            LOG.error("删除路线失败: 数据完整性冲突", e);
            return ResponseEntity.status(HttpStatus.CONFLICT).build();
        } catch (Exception e) {
            LOG.error("删除路线失败: 未知错误", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @ApiOperation(value = "查询单个路线")
    @RequestMapping(value = "{id}", method = {RequestMethod.GET})
    @ApiImplicitParam(name = "id", value = "路线ID", required = true, paramType = "path") // 调整参数描述
    public ResponseEntity<CpRoute> one(@PathVariable final Long id) {
        try {
            CpRoute entity = cpRouteMapper.getRouteById(id);
            if (entity == null || entity.getDelFlag() == 1) {
                return ResponseEntity.notFound().build();
            }
            return ResponseEntity.ok(entity);
        } catch (Exception e) {
            LOG.error("查询单个路线失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @ApiOperation(value = "添加路线")
    @RequestMapping(method = {RequestMethod.POST})
    public ResponseEntity<?> add(@Valid @RequestBody final CpRouteDTO cpRouteDTO, final BindingResult result) {
        try {
            // 处理参数校验错误
            if (result.hasErrors()) {
                String errorMsg = null;
                for (FieldError error : result.getFieldErrors()) {
                    errorMsg = error.getField() + "：" + error.getDefaultMessage();
                    break;
                }
                if (errorMsg == null) {
                    errorMsg = "参数验证失败";
                }
                Map<String, Object> error = new HashMap<>();
                error.put("code", 400);
                error.put("msg", errorMsg);
                return ResponseEntity.badRequest().body(error);
            }
            CpRoute cpRoute = new CpRoute();
            BeanUtils.copyProperties(cpRouteDTO, cpRoute);
            // 设置路线基础信息
            cpRoute.setCreateTime(LocalDateTime.now());
            cpRoute.setUpdateTime(LocalDateTime.now());
            cpRoute.setDelFlag(0);

            // 保存路线主信息
            entityService.save(cpRoute);

            // 返回创建成功的响应
            Map<String, Object> success = new HashMap<>();
            success.put("code", 201);
            success.put("msg", "路线创建成功"); // 调整响应描述
            success.put("data", cpRoute);
            return ResponseEntity
                    .created(URI.create("/cpRoute/" + cpRoute.getId())) // 调整路径
                    .body(success);
        } catch (Exception e) {
            LOG.error("添加路线失败", e); // 调整日志描述
            Map<String, Object> error = new HashMap<>();
            error.put("code", 500);
            error.put("msg", "添加路线失败：" + e.getMessage()); // 调整响应描述
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }

    @ApiOperation(value = "修改路线") // 调整接口描述
    @RequestMapping(method = {RequestMethod.PUT})
    public ResponseEntity<?> update(@Valid @RequestBody final CpRoute entity, final BindingResult result) {
        try {
            if (result.hasErrors()) {
                Map<String, Object> error = new HashMap<>();
                error.put("code", 400);
                FieldError firstError = result.getFieldErrors().get(0);
                error.put("msg", firstError.getField() + "：" + firstError.getDefaultMessage());
                return ResponseEntity.badRequest().body(error);
            }

            // 校验ID是否存在
            if (entity.getId() == null) {
                Map<String, Object> error = new HashMap<>();
                error.put("code", 400);
                error.put("msg", "id不能为空");
                return ResponseEntity.badRequest().body(error);
            }

            // 校验路线是否存在
            CpRoute existingRoute = entityService.getById(entity.getId()); // 调整实体类
            if (existingRoute == null) {
                Map<String, Object> error = new HashMap<>();
                error.put("code", 404);
                error.put("msg", "路线不存在"); // 调整响应描述
                return ResponseEntity.status(404).body(error);
            }
            entity.setUpdateTime(LocalDateTime.now());
            entityService.updateById(entity);
            Map<String, Object> success = new HashMap<>();
            success.put("code", 200);
            success.put("msg", "删除成功");
            return ResponseEntity.ok(success);

        } catch (Exception e) {
            LOG.error("修改路线失败", e); // 调整日志描述
            Map<String, Object> error = new HashMap<>();
            error.put("code", 500);
            error.put("msg", "修改路线失败：" + e.getMessage()); // 调整响应描述
            return ResponseEntity.status(500).body(error);
        }
    }

    @ApiOperation(value = "全部路线") // 调整接口描述
    @RequestMapping(value = "all", method = RequestMethod.GET)
    public ResponseEntity<List<CpRoute>> all(CpRoute example) { // 调整实体类
        QueryWrapper<CpRoute> queryWrapper = new QueryWrapper<>(example);
        List<CpRoute> entitys = entityService.list(queryWrapper);
        if (null != entitys) {
            return ResponseEntity.ok(entitys);
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }

    @ApiOperation(value = "根据区域id获取景区下的所有路线")
    @RequestMapping(value = "getByAreaId", method = RequestMethod.GET)
    public ResponseEntity<List<CpRoute>> getRouteByEmAreaId(
            @ApiParam(value = "区域ID", required = true)
            @RequestParam("areaId") Long areaId) {

        try {
            // 1. 参数校验
            if (areaId == null) {
                LOG.warn("查询区域路线失败：区域ID为空");
                return ResponseEntity.badRequest().build();
            }

            // 2. 构建查询条件
            QueryWrapper<CpRoute> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("area_id", areaId)
                    .eq("del_flag", 0);

            // 3. 查询景区下的所有路线
            List<CpRoute> routes = entityService.list(queryWrapper);

            // 4. 返回结果
            if (CollectionUtils.isEmpty(routes)) {
                LOG.info("区域ID={}下未找到路线数据", areaId);
                return ResponseEntity.ok(Collections.emptyList());
            }

            LOG.info("查询区域ID={}下的路线成功，共找到{}条路线", areaId, routes.size());
            return ResponseEntity.ok(routes);

        } catch (Exception e) {
            LOG.error("查询区域路线失败，景区ID={}", areaId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @ApiOperation(value = "根据景区名称模糊查询路线")
    @RequestMapping(value = "searchRoutesByName", method = RequestMethod.GET)
    public ResponseEntity<List<CpRoute>> searchRoutesByName(
            @ApiParam(value = "景区名称（支持模糊匹配）", required = true)
            @RequestParam("areaName") String areaName) {

        try {
            // 1. 参数校验
            if (StringUtils.isBlank(areaName)) {
                LOG.warn("景区名称模糊查询失败：景区名称为空");
                return ResponseEntity.badRequest().build();
            }

            // 2. 构建查询条件（仅针对景区名称进行模糊匹配）
            QueryWrapper<CpRoute> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("area_name", areaName)
                    .eq("del_flag", 0);

            // 3. 查询匹配的路线
            List<CpRoute> routes = entityService.list(queryWrapper);

            // 4. 返回结果
            if (CollectionUtils.isEmpty(routes)) {
                LOG.info("未找到景区名称包含'{}'的路线数据", areaName);
                return ResponseEntity.ok(Collections.emptyList());
            }

            LOG.info("景区名称模糊查询成功，关键词='{}'，共找到{}条路线", areaName, routes.size());
            return ResponseEntity.ok(routes);

        } catch (Exception e) {
            LOG.error("景区名称模糊查询失败，关键词={}", areaName, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}