package com.aircraft.modules.article.controller;

import com.aircraft.modules.article.domain.CpModule;
import com.aircraft.modules.article.service.CpModuleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "系统：模块管理")
@RestController
@RequestMapping("/cpModule")
public class CpModuleController {
    private static final Logger LOG = LoggerFactory.getLogger(CpModuleController.class);

    @Autowired
    private CpModuleService entityService;

    @ApiOperation(value = "分页查询模块")
    @GetMapping
    @ApiImplicitParams({
            @ApiImplicitParam(name = "size", value = "分页大小", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面：从1开始", paramType = "query")
    })
    public ResponseEntity<IPage<CpModule>> findByPage(final CpModule example, final Page page) {
        try {
            IPage<CpModule> records = entityService.page(page, new QueryWrapper<>(example));
            return ResponseEntity.ok(records);
        } catch (Exception e) {
            LOG.error("分页查询模块时出错", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @ApiOperation(value = "删除模块")
    @DeleteMapping("{id}")
    @ApiImplicitParam(name = "id", value = "模块ID", required = true, paramType = "path")
    public ResponseEntity<?> delete(@PathVariable final Integer id) {
        try {
            CpModule cpModule = entityService.getById(id);
            if (cpModule == null) {
                return ResponseEntity.notFound().build();
            }
            cpModule.setDelFlag(1); // 逻辑删除
            entityService.updateDelFlagById(id, cpModule.getDelFlag());
            // 3. 删除成功，返回成功信息
            Map<String, Object> success = new HashMap<>();
            success.put("code", 200);
            success.put("msg", "删除成功");
            return ResponseEntity.ok(success);
        } 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 = "查询单个模块")
    @GetMapping("{id}")
    @ApiImplicitParam(name = "id", value = "模块ID", required = true, paramType = "path")
    public ResponseEntity<CpModule> one(@PathVariable final Integer id) {
        try {
            CpModule entity = entityService.getById(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 = "添加模块")
    @PostMapping
    public ResponseEntity<CpModule> add(@Valid @RequestBody final CpModule cpModule, final BindingResult result) {
        try {
            if (result.hasErrors()) {
                String errorMsg = null;
                for (FieldError error : result.getFieldErrors()) {
                    errorMsg = error.getDefaultMessage();
                    break;
                }
                if (errorMsg == null) {
                    errorMsg = "参数验证失败";
                }
                return ResponseEntity.badRequest().body(null);
            }

            // 检查模块名称是否已存在
            boolean exists = entityService.lambdaQuery()
                    .eq(CpModule::getModuleName, cpModule.getModuleName())
                    .eq(CpModule::getDelFlag, 0)
                    .count() > 0;
            if (exists) {
                return ResponseEntity.badRequest().body(null);
            }

            // 设置默认值
            cpModule.setDelFlag(0);

            // 保存模块
            entityService.save(cpModule);

            // 返回201 Created状态和创建的资源
            return ResponseEntity
                    .created(URI.create("/cpModule/" + cpModule.getId()))
                    .body(cpModule);
        } catch (Exception e) {
            LOG.error("添加模块失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    @ApiOperation(value = "修改模块")
    @PutMapping
    public ResponseEntity<?> update(@Valid @RequestBody final CpModule entity, final BindingResult result) {
        try {
            if (result.hasErrors()) {
                Map<String, Object> error = new HashMap<>();
                error.put("code", 400);
                error.put("msg", result.getFieldErrors().get(0).getDefaultMessage());
                return ResponseEntity.badRequest().body(error);
            }

            if (entity.getId() == null) {
                return ResponseEntity.badRequest().body(Map.of("code", 400, "msg", "id不能为空"));
            }

            // 校验模块是否存在
            CpModule existingModule = entityService.getById(entity.getId());
            if (existingModule == null) {
                return ResponseEntity.status(404).body(Map.of("code", 404, "msg", "模块不存在"));
            }

            // 更新模块
            entityService.updateById(entity);

            return ResponseEntity.ok(entity);
        } catch (Exception e) {
            LOG.error("修改模块失败", e);
            return ResponseEntity.status(500).body(Map.of("code", 500, "msg", "修改模块失败：" + e.getMessage()));
        }
    }

    @ApiOperation(value = "全部模块")
    @GetMapping("all")
    public ResponseEntity<List<CpModule>> all(CpModule example) {
        try {
            List<CpModule> entitys = entityService.list(new QueryWrapper<>(example));
            return ResponseEntity.ok(entitys);
        } catch (Exception e) {
            LOG.error("查询全部模块失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}