package com.fzm.mall.server.admin.home_page.controller;

import com.fzm.mall.server.admin.annotation.AdminLog;
import com.fzm.mall.server.admin.constant.MALLGlobalConfig;
import com.fzm.mall.server.admin.constant.MallResponseError;
import com.fzm.mall.server.admin.enums.log.OperateModuleEnum;
import com.fzm.mall.server.admin.enums.log.OperateTypeEnum;
import com.fzm.mall.server.admin.home_page.entity.dto.RepairPwdDTO;
import com.fzm.mall.server.admin.home_page.model.Admin;
import com.fzm.mall.server.admin.home_page.service.IAdminService;
import com.fzm.mall.server.admin.repo.ResponseFactory;
import com.fzm.mall.server.admin.repo.ResponseVO;
import com.fzm.mall.server.admin.util.Sha256Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @author wangp
 * @date 2021/4/13 14:27
 * @description 个人信息
 * @since JDK 1.8
 */
@Api(tags = "个人信息")
@RestController
@RequestMapping("/personalInfo")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class PersonalInfoController {

    private final IAdminService adminService;
    private final ResponseFactory resFac;

    @ApiOperation(value = "修改密码")
    @AdminLog(description = "首页-修改密码", module = OperateModuleEnum.HOME_PAGE, opType = OperateTypeEnum.REPAIR_PWD)
    @PutMapping("/repairPwd")
    public ResponseVO<String> repairPwd(@RequestBody @Valid RepairPwdDTO repairPwdDTO, @RequestHeader String adminId) {
        if (repairPwdDTO.getNewPwd().equals(MALLGlobalConfig.INIT_PASSWORD)) {
            return resFac.getResponse(MallResponseError.PASSWORD_INIT_ERROR);
        }
        if (!repairPwdDTO.getNewPwd().matches(MALLGlobalConfig.ADMIN_PASSWORD_REGEX)) {
            return resFac.getResponse(MallResponseError.PASSWORD_FORMAT_ERROR);
        }
        if (!repairPwdDTO.getNewPwd().equals(repairPwdDTO.getNewPwd2())) {
            return resFac.getResponse(MallResponseError.PASSWORDS_ENTERED_TWICE_ARE_INCONSISTENT);
        }
        String code = adminService.repairPwd(repairPwdDTO, adminId);
        return resFac.getResponse(code);
    }

    @ApiOperation(value = "判断是否是初始密码")
    @GetMapping("/isInitPwd")
    public ResponseVO isInitPwd(@ApiParam(name = "adminId", value = "管理员id") @RequestHeader String adminId) {
        Admin admin = adminService.getByAdminId(adminId);
        boolean equals = admin.getPassword().equals(Sha256Util.encode(MALLGlobalConfig.INIT_PASSWORD));
        return resFac.getSuccessResponseWithData(equals);
    }

}
