package com.gxwebsoft.cms.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.gxwebsoft.cms.entity.Design;
import com.gxwebsoft.cms.entity.Navigation;
import com.gxwebsoft.cms.mapper.NavigationMapper;
import com.gxwebsoft.cms.param.NavigationParam;
import com.gxwebsoft.cms.service.DesignService;
import com.gxwebsoft.cms.service.NavigationService;
import com.gxwebsoft.common.core.utils.CommonUtil;
import com.gxwebsoft.common.core.web.*;
import com.gxwebsoft.common.system.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;


/**
 * 导航控制器
 *
 * @author 科技小王子
 * @since 2024-03-04 21:27:55
 */
@Slf4j
@Api(tags = "网站栏目导航")
@RestController
@RequestMapping("/api/cms/navigation")
public class NavigationController extends BaseController {
    @Resource
    private NavigationService navigationService;
    @Resource
    private NavigationMapper navigationMapper;
    @Resource
    private DesignService designService;

    @ApiOperation("分页查询导航")
    @GetMapping("/page")
    public ApiResult<PageResult<Navigation>> page(NavigationParam param) {
        // 使用关联查询
        return success(navigationService.pageRel(param));
    }

    @ApiOperation("查询全部导航")
    @GetMapping()
    public ApiResult<List<Navigation>> list(NavigationParam param) {
        // 使用关联查询
        return success(navigationService.listRel(param));
    }

    @ApiOperation("根据id查询导航")
    @GetMapping("/{id}")
    public ApiResult<Navigation> get(@PathVariable("id") Integer id) {
      final Navigation navigation = navigationService.getById(id);
      // 页面布局
      final Design one = designService.getOne(new LambdaUpdateWrapper<Design>().eq(Design::getCategoryId, id).last("limit 1"));
      if (ObjectUtil.isNotEmpty(one)) {
        navigation.setLayout(one.getLayout());
        navigation.setDesign(one);
      }
      return success(navigation);
    }

    @Transactional(rollbackFor = {Exception.class})
    @PreAuthorize("hasAuthority('cms:navigation:save')")
    @ApiOperation("添加导航")
    @PostMapping()
    public ApiResult<?> save(@RequestBody Navigation navigation) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        if (loginUser != null) {
          navigation.setUserId(loginUser.getUserId());
          navigation.setTenantId(loginUser.getTenantId());
        }
        if (navigationService.save(navigation)) {
            // 添加成功事务处理
            navigationService.saveAsync(navigation);
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @Transactional(rollbackFor = {Exception.class})
    @PreAuthorize("hasAuthority('cms:navigation:update')")
    @ApiOperation("修改导航")
    @PutMapping()
    public ApiResult<?> update(@RequestBody Navigation navigation) {
        if (navigationService.updateById(navigation)) {
            // 修改成功事务处理
            navigationService.saveAsync(navigation);
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('cms:navigation:remove')")
    @ApiOperation("删除导航")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (navigationService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('cms:navigation:save')")
    @ApiOperation("批量添加导航")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<Navigation> list) {
        if (navigationService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('cms:navigation:update')")
    @ApiOperation("批量修改导航")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<Navigation> batchParam) {
        if (batchParam.update(navigationService, "navigation_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('cms:navigation:remove')")
    @ApiOperation("批量删除导航")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (navigationService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @ApiOperation("检查分类是否存在")
    @GetMapping("/existence")
    public ApiResult<?> existence(ExistenceParam<Navigation> param) {
      if (ObjectUtil.isEmpty(param.getId())) {
        return fail(param.getValue() + "不存在");
      }
      if (navigationService.count(new LambdaQueryWrapper<Navigation>()
        .eq(Navigation::getPath, param.getValue())
        .ne(Navigation::getNavigationId,param.getId())
        .ne(Navigation::getType,9)
      )> 0) {
        return success(param.getValue() + "已存在");
      }
      return fail(param.getValue() + "不存在");
    }

    @ApiOperation("获取树形结构的网站导航数据")
    @GetMapping("/tree")
    public ApiResult<List<Navigation>> tree(NavigationParam param) {
      Integer parentId = 0;
      if (ObjectUtil.isEmpty(param.getHide())) {
        param.setHide(0);
      }

      final List<Navigation> navigations = navigationService.listRel(param);
      return success(CommonUtil.toTreeData(navigations, parentId, Navigation::getParentId, Navigation::getNavigationId, Navigation::setChildren));
    }

    @ApiOperation("根据path获取导航")
    @GetMapping("/getNavigationByPath")
    public ApiResult<Navigation> getNavigationByPath(NavigationParam param) {
      if(StrUtil.isBlank(param.getPath())){
        return fail("path不能为空",null);
      }
      final Navigation one = navigationService.getOne(new LambdaUpdateWrapper<Navigation>().eq(Navigation::getPath, param.getPath()).last("limit 1"));

      final Navigation navigation = navigationMapper.getByPathRel(param);
      // 页面元素
      final Design design = designService.getOne(new LambdaUpdateWrapper<Design>().eq(Design::getCategoryId,one.getNavigationId()).last("limit 1"));

      // 上级导航
      if (!navigation.getParentId().equals(0)) {
        final Navigation parent = navigationService.getById(navigation.getParentId());
        navigation.setParentPath(parent.getPath());
        navigation.setParentName(parent.getTitle());
      }
      // 页面信息
      navigation.setDesign(design);
      // 页面布局
      if (ObjectUtil.isNotEmpty(design)) {
        navigation.setLayout(design.getLayout());
      }
      return success(navigation);
    }
}
