package com.aircraft.modules.system.controller;


import com.aircraft.annotation.Log;
import com.aircraft.modules.system.domain.EmArea;
import com.aircraft.modules.system.domain.EmScenic;
import com.aircraft.modules.system.domain.vo.AreaTreeVo;
import com.aircraft.modules.system.service.EmAreaService;
import com.aircraft.modules.system.service.EmScenicService;
import com.aircraft.utils.PageResult;
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 kotlin.Result;
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.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cli
 * @since 2025-07-09
 */
@RestController
@RequestMapping("/emArea")
@Api(tags = "区域管理")
public class EmAreaController {

    private static final Logger LOG = LoggerFactory.getLogger(EmAreaController.class);
    @Autowired
    private EmAreaService entityService;
    @Autowired
    private EmScenicService emScenicService;

    @Log("分页查询区域")
    @ApiOperation(value = "分页查询区域", notes = "分页查询区域")
    @RequestMapping(method = RequestMethod.GET)
    @ApiImplicitParams({@ApiImplicitParam(name = "size", value = "分页大小", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面：从1开始", paramType = "query")})
    public ResponseEntity<PageResult<EmArea>> findByPage(final EmArea example, final Page page) {
        PageResult<EmArea> records = entityService.page(example, page);
        return new ResponseEntity<>(records,HttpStatus.OK);
    }

    @Log("删除区域")
    @ApiOperation(value = "删除区域")
    @RequestMapping(value = "{id}", method = {RequestMethod.DELETE})
    @ApiImplicitParam(name = "id", value = "区域ID", required = true, paramType = "path")
    public ResponseEntity<Object> delete(@PathVariable final Long id) {
        try {
            EmArea area = entityService.getById(id);
            List<EmScenic> emScenics = emScenicService.findByAreaId(id);
            if (null != emScenics && !emScenics.isEmpty()) {
                throw new RuntimeException("区域下面还存在景区，无法删除");
            }
            entityService.removeById(area.getId());
            return new ResponseEntity<>(true, HttpStatus.OK);
        } catch (DataIntegrityViolationException e) {
            LOG.error("删除区域失败", e);
            throw new RuntimeException("删除区域失败,该区域不能删除，存在其他关联数据" ,e);
        } catch (Exception e) {
            LOG.error("删除区域失败", e);
            throw new RuntimeException("删除区域失败", e);
        }
    }

    @Log("查询单个区域")
    @ApiOperation(value = "查询单个区域")
    @RequestMapping(value = "{id}", method = {RequestMethod.GET})
    @ApiImplicitParam(name = "id", value = "区域ID", required = true, paramType = "path")
    public ResponseEntity<Object> one(@PathVariable final Integer id) {
        try {
            EmArea entity = entityService.getById(id);
            return new ResponseEntity<>(entity, HttpStatus.OK);
        } catch (Exception e) {
            LOG.error("查询单个区域失败", e);
            throw new RuntimeException("查询单个区域失败", e);
        }
    }

    @Log("添加区域")
    @ApiOperation(value = "添加区域")
    @RequestMapping(method = {RequestMethod.POST})
    public ResponseEntity<Object> add(@Valid @RequestBody final EmArea entity) {
        try {
            if (null != entity.getId()) {
                throw new RuntimeException("添加接口不能添加id参数");
            }
            EmArea area = entityService.findByName(entity.getName());
            if (null != area) {
                throw new RuntimeException(String.format("已经存在名称为：%s的区域", entity.getName()));
            }
            entity.setDelFlag(0);
            entity.setScenicNum(0);
            entityService.save(entity);
            return new ResponseEntity<>(true, HttpStatus.OK);
        } catch (Exception e) {
            LOG.error("添加区域失败", e);
            throw new RuntimeException("保存区域失败", e);
        }
    }

    @Log("修改区域")
    @ApiOperation(value = "修改区域")
    @RequestMapping(method = {RequestMethod.PUT})
    public ResponseEntity<Object> update(@Valid @RequestBody final EmArea entity, final BindingResult result) {
        try {
            if (null == entity.getId()) {
                throw new RuntimeException("id不能为空");
            }
            entityService.updateById(entity);
            return new ResponseEntity<>(true, HttpStatus.OK);
        } catch (Exception e) {
            LOG.error("修改区域失败", e);
            throw new RuntimeException("修改区域失败", e);
        }
    }

    @ApiOperation(value = "全部区域")
    @RequestMapping(value = "all", method = RequestMethod.GET)
    public ResponseEntity<Object> all(EmArea example) {
        List<EmArea> entitys = entityService.list(example);
        if (null != entitys) {
            return new ResponseEntity<>(entitys, HttpStatus.OK);
        }
        return new ResponseEntity<>(Collections.emptyList(), HttpStatus.OK);
    }

    @ApiOperation(value = "区域景区树")
    @GetMapping("areaTree")
    public ResponseEntity<Object> organizationTree() {
        AreaTreeVo tree = new AreaTreeVo("爱尚云");
        List<EmArea> sons = entityService.list(new EmArea());
        List<AreaTreeVo> treeSons = sons.stream().map(e -> {
            AreaTreeVo temp = new AreaTreeVo(e);
            temp.setSons(emScenicService.findByAreaId(e.getId()).stream().map(AreaTreeVo::new).collect(Collectors.toList()));
            return temp;
        }).collect(Collectors.toList());
        tree.setSons(treeSons);
        return new ResponseEntity<>(tree, HttpStatus.OK);
    }
}

