package shop.alien.storeplatform.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import shop.alien.entity.result.R;
import shop.alien.entity.store.vo.SubAccountDetailVo;
import shop.alien.entity.store.vo.SubAccountListVo;
import shop.alien.entity.store.vo.SubAccountVo;
import shop.alien.storeplatform.dto.AssignRolesDto;
import shop.alien.storeplatform.dto.BatchDeleteSubAccountDto;
import shop.alien.storeplatform.dto.CreateAccountDto;
import shop.alien.storeplatform.dto.UpdateAccountDto;
import shop.alien.storeplatform.service.StorePlatformUserRoleService;
import shop.alien.storeplatform.annotation.PlatformOperationLog;


import java.util.List;

/**
 * 用户角色关联表 前端控制器
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Api(tags = {"平台-用户角色关联管理"})
@ApiSort(1)
@CrossOrigin
@RestController
@RequestMapping("/platform/user-role")
@RequiredArgsConstructor
public class StorePlatformUserRoleController {

    private final StorePlatformUserRoleService storePlatformUserRoleService;

    @ApiOperation("根据用户ID查询角色ID列表")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "storeId", value = "店铺ID", dataType = "int", paramType = "query", required = true)
    })
    @GetMapping("/getRoleIdsByUserId")
    public R<List<Long>> getRoleIdsByUserId(@RequestParam("userId") Integer userId, @RequestParam("storeId") Integer storeId) {
        log.info("StorePlatformUserRoleController.getRoleIdsByUserId?userId={}, storeId={}", userId, storeId);
        List<Long> roleIds = storePlatformUserRoleService.getRoleIdsByUserId(userId, storeId);
        return R.data(roleIds);
    }

    @ApiOperation("根据角色ID查询用户ID列表")
    @ApiOperationSupport(order = 2)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色ID", dataType = "Long", paramType = "query", required = true),
            @ApiImplicitParam(name = "storeId", value = "店铺ID", dataType = "int", paramType = "query", required = true)
    })
    @GetMapping("/getUserIdsByRoleId")
    public R<List<Integer>> getUserIdsByRoleId(@RequestParam("roleId") Long roleId, @RequestParam("storeId") Integer storeId) {
        log.info("StorePlatformUserRoleController.getUserIdsByRoleId?roleId={}, storeId={}", roleId, storeId);
        List<Integer> userIds = storePlatformUserRoleService.getUserIdsByRoleId(roleId, storeId);
        return R.data(userIds);
    }

    @ApiOperation("为用户分配角色")
    @ApiOperationSupport(order = 3)
    @PostMapping("/assignRoles")
    public R<String> assignRoles(@RequestBody AssignRolesDto assignRolesDto) {
        log.info("StorePlatformUserRoleController.assignRoles?userId={}, roleIds={}, storeId={}", 
                assignRolesDto.getUserId(), assignRolesDto.getRoleIds(), assignRolesDto.getStoreId());
        boolean result = storePlatformUserRoleService.assignRoles(assignRolesDto.getUserId(), assignRolesDto.getRoleIds(), assignRolesDto.getStoreId());
        if (result) {
            return R.success("分配成功");
        }
        return R.fail("分配失败");
    }

    @ApiOperation("移除用户的所有角色")
    @ApiOperationSupport(order = 4)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "storeId", value = "店铺ID", dataType = "int", paramType = "query", required = true)
    })
    @PlatformOperationLog(
            module = "账号操作记录",
            type = "移除角色",
            content = "移除用户ID=#{#userId}的全部角色（店铺ID=#{#storeId}）"
    )
    @DeleteMapping("/removeAllRoles")
    public R<String> removeAllRoles(@RequestParam("userId") Integer userId, @RequestParam("storeId") Integer storeId) {
        log.info("StorePlatformUserRoleController.removeAllRoles?userId={}, storeId={}", userId, storeId);
        boolean result = storePlatformUserRoleService.removeAllRoles(userId, storeId);
        if (result) {
            return R.success("移除成功");
        }
        return R.fail("移除失败");
    }

    @ApiOperation("移除用户的指定角色")
    @ApiOperationSupport(order = 5)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "roleId", value = "角色ID", dataType = "Long", paramType = "query", required = true),
            @ApiImplicitParam(name = "storeId", value = "店铺ID", dataType = "int", paramType = "query", required = true)
    })
    @PlatformOperationLog(
            module = "账号操作记录",
            type = "移除角色",
            content = "移除用户ID=#{#userId}的角色ID=#{#roleId}（店铺ID=#{#storeId}）"
    )
    @GetMapping("/removeRole")
    public R<String> removeRole(
            @RequestParam("userId") Integer userId,
            @RequestParam("roleId") Long roleId,
            @RequestParam("storeId") Integer storeId
    ) {
        log.info("StorePlatformUserRoleController.removeRole?userId={}, roleId={}, storeId={}", userId, roleId, storeId);
        boolean result = storePlatformUserRoleService.removeRole(userId, roleId, storeId);
        if (result) {
            return R.success("移除成功");
        }
        return R.fail("移除失败");
    }

    @ApiOperation("创建账号并分配角色")
    @ApiOperationSupport(order = 6)
    @PlatformOperationLog(
            module = "账号操作记录",
            type = "新增子账号",
            content = "新增账号手机号：#{#p0.phone}，账号名：#{#p0.accountName}"
    )
    @PostMapping("/createAccountAndAssignRole")
    public R<String> createAccountAndAssignRole(@RequestBody CreateAccountDto createAccountDto) {
        log.info("StorePlatformUserRoleController.createAccountAndAssignRole?phone={}, accountName={}, storeId={}, roleId={}", 
                createAccountDto.getPhone(), createAccountDto.getAccountName(), createAccountDto.getStoreId(), createAccountDto.getRoleId());
        R<String> result = storePlatformUserRoleService.createAccountAndAssignRole(
                createAccountDto.getPhone(), 
                createAccountDto.getAccountName(), 
                createAccountDto.getStoreId(), 
                createAccountDto.getRoleId());
        return result;
    }


    @ApiOperation("查询当前店铺下的子账号列表")
    @ApiOperationSupport(order = 7)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "店铺ID", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "accountName", value = "账号名称（模糊查询）", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "phone", value = "手机号（模糊查询）", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "roleName", value = "角色名称（模糊查询）", dataType = "String", paramType = "query", required = false)
    })
    @GetMapping("/querySubAccounts")
    public R<List<SubAccountVo>> querySubAccounts(
            @RequestParam("storeId") Integer storeId,
            @RequestParam(value = "accountName", required = false) String accountName,
            @RequestParam(value = "phone", required = false) String phone,
            @RequestParam(value = "roleName", required = false) String roleName) {
        log.info("StorePlatformUserRoleController.querySubAccounts?storeId={}, accountName={}, phone={}, roleName={}",
                storeId, accountName, phone, roleName);
        List<SubAccountVo> subAccountList = storePlatformUserRoleService.querySubAccounts(
                storeId, accountName, phone, roleName);
        return R.data(subAccountList);
    }

    @ApiOperation("查询子账号详情")
    @ApiOperationSupport(order = 8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "storeId", value = "店铺ID", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "roleIdNew", value = "角色ID", dataType = "Long", paramType = "query", required = true)
    })
    @GetMapping("/getSubAccountDetail")
    public R<SubAccountDetailVo> getSubAccountDetail(
            @RequestParam("userId") Integer userId,
            @RequestParam("storeId") Integer storeId,
            @RequestParam("roleIdNew") Long roleIdNew
            ) {
        log.info("StorePlatformUserRoleController.getSubAccountDetail?userId={}, storeId={},roleIdNew={}", userId, storeId,roleIdNew);
        SubAccountDetailVo detail = storePlatformUserRoleService.getSubAccountDetail(userId, storeId, roleIdNew);
        if (detail == null) {
            return R.fail("子账号不存在");
        }
        return R.data(detail);
    }

    @ApiOperation("批量删除子账号")
    @ApiOperationSupport(order = 9)
    @PlatformOperationLog(
            module = "账号操作记录",
            type = "批量删除子账号",
            content = "批量删除子账号（店铺ID=#{#p0.storeId}，用户数量=#{#p0.userIds != null ? #p0.userIds.size() : 0}）"
    )
    @PostMapping("/batchDeleteSubAccounts")
    public R<String> batchDeleteSubAccounts(@RequestBody BatchDeleteSubAccountDto batchDeleteDto) {
        log.info("StorePlatformUserRoleController.batchDeleteSubAccounts?storeId={}, userIds={}", 
                batchDeleteDto.getStoreId(), batchDeleteDto.getUserIds());
        
        if (batchDeleteDto.getStoreId() == null) {
            return R.fail("店铺ID不能为空");
        }
        if (batchDeleteDto.getUserIds() == null || batchDeleteDto.getUserIds().isEmpty()) {
            return R.fail("用户ID列表不能为空");
        }
        
        boolean result = storePlatformUserRoleService.batchDeleteSubAccounts(
                batchDeleteDto.getUserIds(), batchDeleteDto.getStoreId());
        if (result) {
            return R.success("批量删除成功");
        }
        return R.fail("批量删除失败");
    }

    @ApiOperation("更新子账号信息")
    @ApiOperationSupport(order = 10)
    @PlatformOperationLog(
            module = "账号操作记录",
            type = "修改子账号",
            content = "修改子账号，用户ID：#{#p0.userId}，手机号：#{#p0.phone}，账号名：#{#p0.accountName}"
    )
    @PostMapping("/updateSubAccount")
    public R<String> updateSubAccount(@RequestBody UpdateAccountDto updateAccountDto) {
        log.info("StorePlatformUserRoleController.updateSubAccount?userId={}, phone={}, accountName={}, storeId={}, roleId={}", 
                updateAccountDto.getUserId(), updateAccountDto.getPhone(), updateAccountDto.getAccountName(), 
                updateAccountDto.getStoreId(), updateAccountDto.getRoleId());
        
        if (updateAccountDto.getUserId() == null) {
            return R.fail("用户ID不能为空");
        }
        if (updateAccountDto.getStoreId() == null) {
            return R.fail("店铺ID不能为空");
        }
        
        boolean result = storePlatformUserRoleService.updateSubAccount(
                updateAccountDto.getUserId(),
                updateAccountDto.getPhone(),
                updateAccountDto.getAccountName(),
                updateAccountDto.getStoreId(),
                updateAccountDto.getRoleId());
        if (result) {
            return R.success("更新子账号信息成功");
        }
        return R.fail("更新子账号信息失败");
    }



    @ApiOperation("更新子账号信息")
    @ApiOperationSupport(order = 10)
    @PlatformOperationLog(
            module = "账号操作记录",
            type = "修改子账号",
            content = "修改子账号，用户ID：#{#p0.userId}，手机号：#{#p0.phone}，账号名：#{#p0.accountName}"
    )
    @PostMapping("/updateSubAccountNew")
    public R<String> updateSubAccountNew(@RequestBody UpdateAccountDto updateAccountDto) {
        log.info("StorePlatformUserRoleController.updateSubAccount?userId={}, phone={}, accountName={}, storeId={}, roleId={}",
                updateAccountDto.getUserId(), updateAccountDto.getPhone(), updateAccountDto.getAccountName(),
                updateAccountDto.getStoreId(), updateAccountDto.getRoleId());

        if (updateAccountDto.getUserId() == null) {
            return R.fail("用户ID不能为空");
        }
        if (updateAccountDto.getStoreId() == null) {
            return R.fail("店铺ID不能为空");
        }

        boolean result = storePlatformUserRoleService.updateSubAccountNew(
                updateAccountDto.getUserId(),
                updateAccountDto.getPhone(),
                updateAccountDto.getAccountName(),
                updateAccountDto.getStoreId(),
                updateAccountDto.getRoleId(),
                updateAccountDto.getId()
        );
        if (result) {
            return R.success("更新子账号信息成功");
        }
        return R.fail("更新子账号信息失败");
    }



    @ApiOperation("查询所有子账号信息（分页）")
    @ApiOperationSupport(order = 11)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", dataType = "int", paramType = "query", required = false, defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页大小", dataType = "int", paramType = "query", required = false, defaultValue = "10"),
            @ApiImplicitParam(name = "mainAccountId", value = "账号ID（主账号ID或子账号用户ID，模糊查询）", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "phone", value = "联系电话（子账号电话，模糊查询）", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "status", value = "状态（0:启用 1:禁用）", dataType = "int", paramType = "query", required = false)
    })
    @GetMapping("/queryAllSubAccounts")
    public R<IPage<SubAccountListVo>> queryAllSubAccounts(
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "mainAccountId", required = false) String mainAccountId,
            @RequestParam(value = "phone", required = false) String phone,
            @RequestParam(value = "status", required = false) Integer status) {
        log.info("StorePlatformUserRoleController.queryAllSubAccounts?pageNum={}, pageSize={}, mainAccountId={}, phone={}, status={}",
                pageNum, pageSize, mainAccountId, phone, status);
        IPage<SubAccountListVo> subAccountPage = storePlatformUserRoleService.queryAllSubAccounts(pageNum, pageSize, mainAccountId, phone, status);
        return R.data(subAccountPage);
    }

    @ApiOperation("禁用子账号")
    @ApiOperationSupport(order = 12)
    @PlatformOperationLog(
            module = "账号操作记录",
            type = "禁用子账号",
            content = "禁用子账号（关联记录ID=#{#id}）"
    )
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "子账号关联记录的主键ID", dataType = "Long", paramType = "query", required = true),
            @ApiImplicitParam(name = "status", value = "状态标志（0启用 1禁用）", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/disableSubAccount")
    public R<String> disableSubAccount(@RequestParam("id") Long id, @RequestParam("status") Integer status) {
        log.info("StorePlatformUserRoleController.disableSubAccount?id={}, status={}", id, status);
        
        if (id == null) {
            return R.fail("子账号关联记录ID不能为空");
        }
        
        if (status == null || (status != 0 && status != 1)) {
            return R.fail("状态参数必须为0（启用）或1（禁用）");
        }
        
        boolean result = storePlatformUserRoleService.disableSubAccount(id, status);
        if (result) {
            String message = status == 0 ? "启用子账号成功" : "禁用子账号成功";
            return R.success(message);
        }
        String message = status == 0 ? "启用子账号失败" : "禁用子账号失败";
        return R.fail(message);
    }

}

