package org.dromara.system.controller;

import java.io.IOException;
import java.util.List;

import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.system.domain.vo.VsNavServiceToolbarVo;
import org.dromara.system.domain.bo.VsNavServiceToolbarBo;
import org.dromara.system.service.IVsNavServiceToolbarService;
import org.dromara.common.mybatis.core.page.TableDataInfo;

/**
 * 服务区工具栏管理
 *
 * @author system
 * @date 2025-01-20
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/scenic/navServiceToolbar")
public class VsNavServiceToolbarController extends BaseController {

    private final IVsNavServiceToolbarService vsNavServiceToolbarService;

    /**
     * 查询服务区工具栏列表
     */
    @SaCheckPermission("scenic:navServiceToolbar:list")
    @GetMapping("/list")
    public TableDataInfo<VsNavServiceToolbarVo> list(VsNavServiceToolbarBo bo, PageQuery pageQuery) {
        return vsNavServiceToolbarService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出服务区工具栏列表
     */
    @SaCheckPermission("scenic:navServiceToolbar:export")
    @Log(title = "服务区工具栏", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(VsNavServiceToolbarBo bo, HttpServletResponse response) {
        try {
            List<VsNavServiceToolbarVo> list = vsNavServiceToolbarService.queryList(bo);
            ExcelUtil.exportExcel(list, "服务区工具栏", VsNavServiceToolbarVo.class, response);
        } catch (Exception e) {
            // 如果导出过程中出现异常，重置Content-Type并返回错误信息
            response.reset();
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            try {
                response.getWriter().write("{\"code\":500,\"msg\":\"导出失败：" + e.getMessage() + "\"}");
            } catch (IOException ex) {
                // 忽略写入错误
            }
        }
    }

    /**
     * 获取服务区工具栏详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("scenic:navServiceToolbar:query")
    @GetMapping("/{id}")
    public R<VsNavServiceToolbarVo> getInfo(@NotNull(message = "主键不能为空")
                                            @PathVariable Long id) {
        return R.ok(vsNavServiceToolbarService.queryById(id));
    }

    /**
     * 新增服务区工具栏
     */
    @SaCheckPermission("scenic:navServiceToolbar:add")
    @Log(title = "服务区工具栏", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody VsNavServiceToolbarBo bo) {
        return toAjax(vsNavServiceToolbarService.insertByBo(bo));
    }

    /**
     * 修改服务区工具栏
     */
    @SaCheckPermission("scenic:navServiceToolbar:edit")
    @Log(title = "服务区工具栏", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody VsNavServiceToolbarBo bo) {
        return toAjax(vsNavServiceToolbarService.updateByBo(bo));
    }

    /**
     * 删除服务区工具栏
     *
     * @param ids 主键串
     */
    @SaCheckPermission("scenic:navServiceToolbar:remove")
    @Log(title = "服务区工具栏", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(vsNavServiceToolbarService.deleteWithValidByIds(List.of(ids), true));
    }

    /**
     * 根据分类ID查询工具栏列表
     *
     * @param categoryId 分类ID
     */
    @SaCheckPermission("scenic:navServiceToolbar:list")
    @GetMapping("/byCategory/{categoryId}")
    public R<List<VsNavServiceToolbarVo>> getToolbarListByCategory(@NotNull(message = "分类ID不能为空")
                                                                   @PathVariable Integer categoryId) {
        return R.ok(vsNavServiceToolbarService.queryByCategoryIdOrderBySort(categoryId));
    }

    /**
     * 获取所有分类的工具栏列表
     */
    @SaCheckPermission("scenic:navServiceToolbar:list")
    @GetMapping("/allCategories")
    public R<List<VsNavServiceToolbarVo>> getAllCategoriesToolbar() {
        // 查询所有分类的工具栏，按分类ID和排序号排序
        VsNavServiceToolbarBo bo = new VsNavServiceToolbarBo();
        bo.setStatus(0); // 只查询正常状态
        bo.setShowFlag(0); // 只查询显示状态
        List<VsNavServiceToolbarVo> list = vsNavServiceToolbarService.queryList(bo);

        // 按分类ID和排序号排序
        list.sort((a, b) -> {
            int categoryCompare = Integer.compare(a.getCategoryId(), b.getCategoryId());
            if (categoryCompare != 0) {
                return categoryCompare;
            }
            return Integer.compare(a.getSortNum(), b.getSortNum());
        });

        return R.ok(list);
    }
}
