package com.ruoyi.xq.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.xq.domain.AreaCode;
import com.ruoyi.xq.dto.admin.areacode.AreaCodeAdminTree;
import com.ruoyi.xq.service.AreaCodeService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;

/**
 * 行政区划
 *
 * @author 77
 * @date 2024-03-19
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/xq/areaCode")
public class AreaCodeController extends BaseController {

    private final AreaCodeService areaCodeService;

    /**
     * 查询行政区划列表
     */
    @SaCheckPermission("xq:areaCode:list")
    @GetMapping("/list")
    public R<List<AreaCode>> list(AreaCode bo) {
        List<AreaCode> list = areaCodeService.list(Wrappers.lambdaQuery(bo)
                .in(AreaCode::getLevel,"province","city")
                .select(AreaCode::getCode, AreaCode::getName,AreaCode::getPcode,AreaCode::getEnableStatus, AreaCode::getLevel));
        return R.ok(list);
    }

    /**
     * 获取行政区划详细信息
     *
     * @param code 主键
     */
    @SaCheckPermission("xq:areaCode:query")
    @GetMapping("/{code}")
    public R<AreaCode> getInfo(@NotNull(message = "主键不能为空") @PathVariable Integer code) {
        return R.ok(areaCodeService.getById(code));
    }

    @GetMapping("/tree")
    public R<List<AreaCodeAdminTree>> areaCodeTree(){
        List<AreaCodeAdminTree> node = areaCodeService.treeAdmin();
        return R.ok(node);
    }

    /**
     * 修改行政区划
     */
    @SaCheckPermission("xq:areaCode:edit")
    @Log(title = "行政区划", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody AreaCode bo) {
        return toAjax(areaCodeService.updateById(bo));
    }

    /**
     * 删除行政区划
     *
     * @param codes 主键串
     */
    @SaCheckPermission("xq:areaCode:remove")
    @Log(title = "行政区划", businessType = BusinessType.DELETE)
    @DeleteMapping("/{codes}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Integer[] codes) {
        return toAjax(areaCodeService.removeBatchByIds(Arrays.asList(codes)));
    }
}
