package com.dbnt.kcscbackend.admin.users;


import com.dbnt.kcscbackend.admin.users.service.AdminUsersService;
import com.dbnt.kcscbackend.auth.entity.LoginVO;
import com.dbnt.kcscbackend.auth.entity.UserInfo;
import com.dbnt.kcscbackend.commonCode.service.CommonCodeService;
import com.dbnt.kcscbackend.config.common.BaseController;
import com.dbnt.kcscbackend.config.common.ResponseCode;
import com.dbnt.kcscbackend.config.common.ResultVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequiredArgsConstructor
@RequestMapping("/admin/users")
@Tag(name="AdminConfigController", description = "사이트관리 사용자관리 메뉴 컨트롤러")
public class AdminUsersController extends BaseController {

  private final AdminUsersService adminUsersService;
  private final CommonCodeService commonCodeService;

  @Operation(
      summary = "사용자 목록 조회",
      description = "사용자 목록 조회",
      tags = {"AdminUsersController"}
  )
  @ApiResponses(value = {
      @ApiResponse(responseCode = "200", description = "조회 성공"),
      @ApiResponse(responseCode = "403", description = "인가된 사용자가 아님")
  })
  @RequestMapping(method = RequestMethod.GET, value = "/list")
  public ResultVO getUserList(UserInfo params) throws Exception{
    ResultVO resultVO = new ResultVO();
    Map<String, Object> resultMap = new HashMap<>();
    params.setQueryInfo();
    resultMap.put("userSeOption", commonCodeService.selectCodeItemList("ACC_TYPE"));
    resultMap.put("userList", adminUsersService.selectUserList(params));
    params.setContentCnt(adminUsersService.selectUserListCnt(params));
    params.setPaginationInfo();
    resultMap.put("paginationInfo", params);
    resultVO.setResult(resultMap);
    return resultVO;
  }

  @Operation(
      summary = "사용자 정보 조회",
      description = "사용자 정보 조회",
      tags = {"AdminUsersController"}
  )
  @ApiResponses(value = {
      @ApiResponse(responseCode = "200", description = "조회 성공"),
      @ApiResponse(responseCode = "403", description = "인가된 사용자가 아님")
  })
  @RequestMapping(method = RequestMethod.GET, value = "/info")
  public ResultVO getUserInfo(UserInfo params) throws Exception{
    ResultVO resultVO = new ResultVO();
    Map<String, Object> resultMap = new HashMap<>();
    resultMap.put("userInfo", adminUsersService.selectUserInfo(params.getUserSeq()));
    resultVO.setResult(resultMap);
    return resultVO;
  }

  @Operation(
      summary = "사용자 정보 수정",
      description = "사용자 정보 수정",
      tags = {"AdminUsersController"}
  )
  @ApiResponses(value = {
      @ApiResponse(responseCode = "200", description = "수정 성공"),
      @ApiResponse(responseCode = "403", description = "인가된 사용자가 아님")
  })
  @RequestMapping(method = RequestMethod.PUT, value = "/info")
  public ResultVO modifyUserInfo(@RequestBody @Valid UserInfo info, Errors errors, @AuthenticationPrincipal LoginVO user) throws Exception{
    ResultVO resultVO = new ResultVO();
    if(errors.hasErrors()){
      StringBuilder msg = new StringBuilder();
      for(FieldError error: errors.getFieldErrors()){
        msg.append(error.getDefaultMessage());
        msg.append("\n");
      }
      resultVO.setResultCode(ResponseCode.INPUT_CHECK_ERROR.getCode());
      resultVO.setResultMessage(msg.toString());
    }else if(!info.getPassword().equals(info.getPasswordChk())){
      resultVO.setResultCode(ResponseCode.SAVE_ERROR.getCode());
      resultVO.setResultMessage("비밀번호 확인이 잘못 입력되었습니다.");
    }else {
      Integer insertResult = adminUsersService.updateUserInfo(info, user.getId());
      if(insertResult!=null){
        if(insertResult==-1){
          resultVO.setResultCode(ResponseCode.SAVE_ERROR.getCode());
          resultVO.setResultMessage("수정 대상이 존재하지 않습니다.");
        }else if(insertResult==-2){
          resultVO.setResultCode(ResponseCode.SAVE_ERROR.getCode());
          resultVO.setResultMessage("가입된 이메일입니다.");
        }else{
          resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
          resultVO.setResultMessage("저장 되었습니다.");
        }
      }else{
        resultVO.setResultCode(ResponseCode.SAVE_ERROR.getCode());
        resultVO.setResultMessage("저장에 실패하였습니다.");
      }
    }
    return resultVO;
  }

  @Operation(
      summary = "사용자 정보 삭제",
      description = "사용자 정보 삭제",
      tags = {"AdminUsersController"}
  )
  @ApiResponses(value = {
      @ApiResponse(responseCode = "200", description = "삭제 성공"),
      @ApiResponse(responseCode = "403", description = "인가된 사용자가 아님")
  })
  @RequestMapping(method = RequestMethod.DELETE, value = "/info", consumes = MediaType.APPLICATION_JSON_VALUE)
  public ResultVO deleteUserInfo(@RequestBody UserInfo info) throws Exception{
    ResultVO resultVO = new ResultVO();
    adminUsersService.deleteUserInfo(info.getUserSeq());
    resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
    return resultVO;
  }

}
