package com.gxwebsoft.common.system.controller;

import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.Organization;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.entity.UserVerify;
import com.gxwebsoft.common.system.param.UserVerifyParam;
import com.gxwebsoft.common.system.service.OrganizationService;
import com.gxwebsoft.common.system.service.UserService;
import com.gxwebsoft.common.system.service.UserVerifyService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
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 2025-05-29 23:01:04
 */
@Tag(name = "实名认证管理")
@RestController
@RequestMapping("/api/system/user-verify")
public class UserVerifyController extends BaseController {
  @Resource
  private UserVerifyService userVerifyService;
  @Resource
  private UserService userService;
  @Resource
  private OrganizationService organizationService;

  @PreAuthorize("hasAuthority('sys:userVerify:list')")
  @Operation(summary = "分页查询实名认证")
  @GetMapping("/page")
  public ApiResult<PageResult<UserVerify>> page(UserVerifyParam param) {
    // 使用关联查询
    return success(userVerifyService.pageRel(param));
  }

  @PreAuthorize("hasAuthority('sys:userVerify:list')")
  @Operation(summary = "查询全部实名认证")
  @GetMapping()
  public ApiResult<List<UserVerify>> list(UserVerifyParam param) {
    // 使用关联查询
    return success(userVerifyService.listRel(param));
  }

  @Operation(summary = "根据id查询实名认证")
  @GetMapping("/{id}")
  public ApiResult<UserVerify> get(@PathVariable("id") Integer id) {
    // 使用关联查询
    return success(userVerifyService.getByIdRel(id));
  }

  @Operation(summary = "根据userId查询实名认证")
  @GetMapping("/myUserVerify")
  public ApiResult<UserVerify> myUserVerify(UserVerifyParam param) {
    if (getLoginUser() == null) {
      return fail("请先登录", null);
    }
    final LambdaQueryWrapper<UserVerify> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(UserVerify::getUserId, getLoginUserId());
    wrapper.eq(UserVerify::getDeleted, 0);
    if(param.getStatus() != null){
      wrapper.eq(UserVerify::getStatus, param.getStatus());
    }
    wrapper.last("limit 1");
    final UserVerify one = userVerifyService.getOne(wrapper);
    if(ObjUtil.isNotEmpty(one) && one.getOrganizationId() > 0){
      final Organization organization = organizationService.getById(one.getOrganizationId());
      if(organization != null){
        one.setOrganizationName(organization.getOrganizationName());
      }
    }
    return success(one);
  }

  @Operation(summary = "提交实名认证")
  @PostMapping()
  public ApiResult<?> save(@RequestBody UserVerify userVerify) {
    if (getLoginUser() == null) {
      return fail("请先登录");
    }
    userVerify.setUserId(getLoginUserId());
    if (userVerifyService.save(userVerify)) {
      return success("提交成功");
    }
    return fail("提交失败");
  }

  @Transactional(rollbackFor = Exception.class)
  @Operation(summary = "修改实名认证")
  @PutMapping()
  public ApiResult<?> update(@RequestBody UserVerify userVerify) {
    final User loginUser = getLoginUser();
    if (loginUser == null) {
      return fail("请先登录");
    }

    final User byUserId = userService.getById(userVerify.getUserId());
    if (ObjUtil.isEmpty(byUserId)) {
      return fail("用户不存在");
    }
    // 不通过
    byUserId.setCertification(false);
    // 通过认证
    if (userVerify.getStatus().equals(1)) {
      byUserId.setRealName(userVerify.getRealName());
      byUserId.setCertification(true);
      byUserId.setType(userVerify.getType());
      // 企业认证
      if (userVerify.getType().equals(1)) {
        byUserId.setRealName(userVerify.getName());
      }
      // 设置管理员id
      userVerify.setAdminId(loginUser.getUserId());
    }
    userService.updateById(byUserId);

    if (userVerifyService.updateById(userVerify)) {
      return success("提交成功");
    }
    return fail("提交失败");
  }

  @PreAuthorize("hasAuthority('sys:userVerify:remove')")
  @OperationLog
  @Operation(summary = "删除实名认证")
  @DeleteMapping("/{id}")
  public ApiResult<?> remove(@PathVariable("id") Integer id) {
    if (userVerifyService.removeById(id)) {
      return success("删除成功");
    }
    return fail("删除失败");
  }

  @PreAuthorize("hasAuthority('sys:userVerify:save')")
  @OperationLog
  @Operation(summary = "批量添加实名认证")
  @PostMapping("/batch")
  public ApiResult<?> saveBatch(@RequestBody List<UserVerify> list) {
    if (userVerifyService.saveBatch(list)) {
      return success("添加成功");
    }
    return fail("添加失败");
  }

  @PreAuthorize("hasAuthority('sys:userVerify:update')")
  @OperationLog
  @Operation(summary = "批量修改实名认证")
  @PutMapping("/batch")
  public ApiResult<?> removeBatch(@RequestBody BatchParam<UserVerify> batchParam) {
    if (batchParam.update(userVerifyService, "id")) {
      return success("修改成功");
    }
    return fail("修改失败");
  }

  @PreAuthorize("hasAuthority('sys:userVerify:remove')")
  @OperationLog
  @Operation(summary = "批量删除实名认证")
  @DeleteMapping("/batch")
  public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
    if (userVerifyService.removeByIds(ids)) {
      return success("删除成功");
    }
    return fail("删除失败");
  }


}
