package com.gxwebsoft.app.controller;

import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.app.service.AppUserService;
import com.gxwebsoft.app.entity.AppUser;
import com.gxwebsoft.app.param.AppUserParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.system.entity.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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

/**
 * 应用成员控制器
 *
 * @author 科技小王子
 * @since 2026-03-28 21:29:44
 */
@Slf4j
@Tag(name = "应用成员管理")
@RestController
@RequestMapping("/api/app/app-user")
public class AppUserController extends BaseController {

    @Resource
    private AppUserService appUserService;

    @Operation(summary = "分页查询应用成员")
    @GetMapping("/page")
    public ApiResult<PageResult<AppUser>> page(AppUserParam param) {
        return success(appUserService.pageRel(param));
    }

    @Operation(summary = "查询全部应用成员")
    @GetMapping()
    public ApiResult<List<AppUser>> list(AppUserParam param) {
        return success(appUserService.listRel(param));
    }

    @Operation(summary = "根据id查询应用成员")
    @GetMapping("/{id}")
    public ApiResult<AppUser> get(@PathVariable("id") Integer id) {
        return success(appUserService.getByIdRel(id));
    }

    @PreAuthorize("hasAuthority('app:appUser:save')")
    @OperationLog
    @Operation(summary = "添加应用成员（手动添加）")
    @PostMapping()
    public ApiResult<?> save(@RequestBody AppUser appUser) {
        User loginUser = getLoginUser();
        if (loginUser != null) {
            appUser.setUserId(loginUser.getUserId());
            appUser.setTenantId(loginUser.getTenantId());
        }
        if (appUserService.save(appUser)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @Operation(summary = "邀请用户成为应用成员（支持用户ID或手机号）")
    @PostMapping("/invite")
    public ApiResult<?> invite(@RequestBody AppUser appUser) {
        User loginUser = getLoginUser();
        if (loginUser == null) {
            return fail("请先登录");
        }
        // 支持手机号邀请：若 userId 为空但传了 phone，则先按手机号查出用户
        if (appUser.getUserId() == null && appUser.getPhone() != null && !appUser.getPhone().isEmpty()) {
            User targetUser = appUserService.findUserByPhone(appUser.getPhone());
            if (targetUser == null) {
                return fail("手机号未注册，请确认后再试");
            }
            appUser.setUserId(targetUser.getUserId());
        }
        if (appUser.getUserId() == null) {
            return fail("请输入用户ID或手机号");
        }
        try {
            AppUser result = appUserService.inviteUser(
                    appUser.getWebsiteId(),
                    appUser.getUserId(),
                    appUser.getRole(),
                    loginUser.getUserId()
            );
            return success("邀请成功", result);
        } catch (RuntimeException e) {
            return fail(e.getMessage());
        }
    }

    @PreAuthorize("hasAuthority('app:appUser:update')")
    @OperationLog
    @Operation(summary = "修改应用成员信息")
    @PutMapping()
    public ApiResult<?> update(@RequestBody AppUser appUser) {
        if (appUserService.updateById(appUser)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('app:appUser:update')")
    @OperationLog
    @Operation(summary = "修改成员角色")
    @PutMapping("/role/{id}/{role}")
    public ApiResult<?> updateRole(@PathVariable("id") Long id, @PathVariable("role") String role) {
        if (appUserService.updateRole(id, role)) {
            return success("角色修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('app:appUser:remove')")
    @OperationLog
    @Operation(summary = "移除应用成员")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (appUserService.removeById(id)) {
            return success("已移除");
        }
        return fail("移除失败");
    }

    @PreAuthorize("hasAuthority('app:appUser:save')")
    @OperationLog
    @Operation(summary = "批量添加应用成员")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<AppUser> list) {
        if (appUserService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('app:appUser:update')")
    @OperationLog
    @Operation(summary = "批量修改应用成员")
    @PutMapping("/batch")
    public ApiResult<?> updateBatch(@RequestBody BatchParam<AppUser> batchParam) {
        if (batchParam.update(appUserService, "id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('app:appUser:remove')")
    @OperationLog
    @Operation(summary = "批量移除应用成员")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (appUserService.removeByIds(ids)) {
            return success("移除成功");
        }
        return fail("移除失败");
    }

}
