package com.aircraft.modules.system.controller;


import com.aircraft.annotation.Log;
import com.aircraft.modules.system.domain.EmEmployees;
import com.aircraft.modules.system.domain.EmScenic;
import com.aircraft.modules.system.domain.User;
import com.aircraft.modules.system.service.EmEmployeesService;
import com.aircraft.modules.system.service.EmScenicService;
import com.aircraft.modules.system.service.UserService;
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;

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

    private static final Logger LOG = LoggerFactory.getLogger(EmScenicController.class);
    @Autowired
    private EmScenicService entityService;
    @Autowired
    private UserService userService;

    @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<EmScenic>> findByPage(final EmScenic example, final Page page) {
        PageResult<EmScenic> 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 {
            EmScenic scenic = entityService.getById(id);
            if (null == scenic) {
                throw new RuntimeException("没有找到id对应对象");
            }
            List<User> fdBaseUsers = userService.findByScenicId(id);
            if (null != fdBaseUsers && !fdBaseUsers.isEmpty()) {
                throw new RuntimeException("部门里面还存在用户，无法删除");
            }
            entityService.removeById(scenic.getId());
            return new ResponseEntity<>(HttpStatus.OK);
        } catch (DataIntegrityViolationException e) {
            LOG.error("删除景区失败", e);
            throw new RuntimeException("删除景区失败,该景区不能删除，存在其他关联数据");
        } catch (Exception e) {
            LOG.error("删除景区失败", e);
            throw new RuntimeException("删除景区失败");
        }
    }

    @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 {
            EmScenic entity = entityService.getById(id);
            return new ResponseEntity<>(entity,HttpStatus.OK);
        } catch (Exception e) {
            LOG.error("查询单个景区失败", e);
            throw new RuntimeException("查询单个景区失败");
        }
    }

    @Log("添加景区")
    @ApiOperation(value = "添加景区")
    @RequestMapping(method = {RequestMethod.POST})
    public ResponseEntity<Object> add(@Valid @RequestBody final EmScenic entity, final BindingResult result) {
        try {
            if (null != entity.getId()) {
                throw new RuntimeException("添加接口不能添加id参数");
            }
            if (null == entity.getAreaId()) {
                throw new RuntimeException("景区必须指定所在区域");
            }
            EmScenic oldDepartment = entityService.findByAreaIdAndName(entity.getAreaId(), entity.getName());
            if (null != oldDepartment) {
                throw new RuntimeException(String.format("区域下已经存在相同名称的景区：%s", entity.getName()));
            }
            entity.setDelFlag(0);
            entity.setPeopleNum(0);
            entityService.save(entity);
            return new ResponseEntity<>(entity,HttpStatus.OK);
        } catch (Exception e) {
            LOG.error("添加景区失败", e);
            throw new RuntimeException("保存景区失败");
        }
    }

    @Log("修改景区")
    @ApiOperation(value = "修改景区")
    @RequestMapping(method = {RequestMethod.PUT})
    public ResponseEntity<Object> update(@Valid @RequestBody final EmScenic 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(EmScenic example) {
        List<EmScenic> entitys = entityService.list(example);
        if (null != entitys) {
            return new ResponseEntity<>(entitys,HttpStatus.OK);
        }
        return new ResponseEntity<>(Collections.emptyList(),HttpStatus.OK);
    }

    @ApiOperation(value = "设置区域景区数量")
    @PostMapping("setAreaScenicNum")
    public ResponseEntity<Object> setAreaScenicNum() {
        entityService.countByAreaIdToUpdate();
        return new ResponseEntity<>("设置区域景区数量成功",HttpStatus.OK);
    }
}

