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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.SystemClock;
import com.fzm.mall.server.admin.annotation.AdminLog;
import com.fzm.mall.server.admin.auth_center.entity.vo.AuthMenuVO;
import com.fzm.mall.server.admin.auth_center.service.IAuthMenuService;
import com.fzm.mall.server.admin.chain.FzmChain;
import com.fzm.mall.server.admin.config.Redis;
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.LoginDTO;
import com.fzm.mall.server.admin.home_page.entity.dto.ResetPwdDTO;
import com.fzm.mall.server.admin.home_page.entity.vo.MerchantStatistics;
import com.fzm.mall.server.admin.home_page.entity.vo.PersonInfoVO;
import com.fzm.mall.server.admin.home_page.entity.vo.PlatformStatistics;
import com.fzm.mall.server.admin.home_page.enums.status.AdminStatusEnum;
import com.fzm.mall.server.admin.home_page.enums.status.MerchantRegisterEnum;
import com.fzm.mall.server.admin.home_page.enums.type.AdminTypeEnum;
import com.fzm.mall.server.admin.home_page.model.Admin;
import com.fzm.mall.server.admin.home_page.model.Merchant;
import com.fzm.mall.server.admin.home_page.service.IAdminService;
import com.fzm.mall.server.admin.home_page.service.IMerchantService;
import com.fzm.mall.server.admin.repo.ResponseFactory;
import com.fzm.mall.server.admin.repo.ResponseVO;
import com.fzm.mall.server.admin.util.TCaptchaVerify;
import com.fzm.mall.server.admin.util.UUIDUtil;
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;
import java.util.List;

/**
 * @author wangp
 * @date 2021/4/13 14:14
 * @description 首页-登录
 * @since JDK 1.8
 */
@Api(tags = "首页-登录")
@RestController
@RequestMapping("/homePage")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class LoginController {

    private final IMerchantService merchantService;
    private final IAdminService adminService;
    private final ResponseFactory resFac;
    private final Redis redis;
    private final IAuthMenuService authMenuService;
    private final FzmChain fzmChain;

    @ApiOperation(value = "登录")
    @AdminLog(description = "首页-管理员登陆", module = OperateModuleEnum.HOME_PAGE, opType = OperateTypeEnum.LOGIN)
    @PostMapping("/login")
    public ResponseVO login(@RequestBody @Valid LoginDTO loginDTO) {
        int verifyTicket = TCaptchaVerify.verifyTicket(loginDTO.getTicket(), loginDTO.getRand(), loginDTO.getUserIp());
        if (verifyTicket != 1) {
            return resFac.getResponse(MallResponseError.VERIFICATION_CODE_ERROR);
        }

        Admin admin = adminService.login(loginDTO.getAccount(), loginDTO.getPassword());
        if (admin == null) {
            return resFac.getResponse(MallResponseError.ACCOUNT_OR_PASSWORD_ERROR);
        }
        if (admin.getStatus().equals(AdminStatusEnum.DISABLE.getStatus())) {
            return resFac.getResponse(MallResponseError.HAS_LOCKING_ERROR);
        }
        if (admin.getType().equals(AdminTypeEnum.MERCHANT.getType())) {
            Merchant merchant = merchantService.getByMerchantId(admin.getMerchantId());
            //商户锁定禁止登陆
            if (merchant.getStatus().equals(MerchantRegisterEnum.LOCKING.getStatus())) {
                return resFac.getResponse(MallResponseError.HAS_LOCKING_ERROR);
            }
            //最近登陆时间
            merchantService.lastLoginTime(merchant.getMerchantId(), SystemClock.now());
        }

        String adminId = admin.getAdminId();
        String token = UUIDUtil.getUUID();
        redis.setKey(adminId + MALLGlobalConfig.MALL_TOKEN_REDIS_KEY_SUFFIX, token, 24 * 60 * 60);

        JSONObject data = new JSONObject();
        data.put("adminId", adminId);
        data.put("token", token);
        data.put("headImg", admin.getHeadImg());
        data.put("type", admin.getType());
//        data.put("auth", authMenuService.getAdminAuthMenuVO(adminId));
        return resFac.getSuccessResponseWithData(data);
    }

    @ApiOperation(value = "登出")
    @AdminLog(description = "首页-管理员登出", module = OperateModuleEnum.HOME_PAGE)
    @PostMapping("/logout")
    public ResponseVO logout(@RequestHeader String adminId) {
        redis.del(adminId + MALLGlobalConfig.MALL_TOKEN_REDIS_KEY_SUFFIX);
        return resFac.getSimpleSuccessResponse();
    }

    @ApiOperation(value = "验证身份")
    @GetMapping("/authentication")
    public ResponseVO<String> authentication(@ApiParam(name = "phone", value = "注册手机号") @RequestParam String phone,
                                             @ApiParam(name = "code", value = "验证码") @RequestParam String code) {
        if (!adminService.checkAdminExist(phone)) {
            return resFac.getResponse(MallResponseError.PHONE_NOT_REGISTER__ERROR);
        }

        String redisCode = redis.getKey(phone + MALLGlobalConfig.PHONE_CODE_IDENTITY_REDIS_KEY_SUFFIX);
        if (!code.equals(redisCode)) {
            return resFac.getResponse(MallResponseError.PHONE_CODE__ERROR);
        }

        String token = UUIDUtil.getUUID();
        redis.setKey(phone + MALLGlobalConfig.IDENTITY_AUTH_REDIS_KEY_SUFFIX, token, 5 * 60);
        return resFac.getSuccessResponseWithData(token);
    }

    @ApiOperation(value = "重置密码")
    @AdminLog(description = "首页-重置密码", module = OperateModuleEnum.HOME_PAGE, opType = OperateTypeEnum.FORGET_RESET_PWD)
    @PutMapping("/resetPwd")
    public ResponseVO<String> resetPwd(@RequestBody @Valid ResetPwdDTO resetPwdDTO) {
        if (resetPwdDTO.getNewPwd().equals(MALLGlobalConfig.INIT_PASSWORD)) {
            return resFac.getResponse(MallResponseError.PASSWORD_INIT_ERROR);
        }
        if (!resetPwdDTO.getNewPwd().matches(MALLGlobalConfig.ADMIN_PASSWORD_REGEX)) {
            return resFac.getResponse(MallResponseError.PASSWORD_FORMAT_ERROR);
        }
        if (!resetPwdDTO.getNewPwd().equals(resetPwdDTO.getNewPwd2())) {
            return resFac.getResponse(MallResponseError.PASSWORDS_ENTERED_TWICE_ARE_INCONSISTENT);
        }

        String token = redis.getKey(resetPwdDTO.getPhone() + MALLGlobalConfig.IDENTITY_AUTH_REDIS_KEY_SUFFIX);
        if (!token.equals(resetPwdDTO.getToken())) {
            return resFac.getResponse(MallResponseError.TOKEN_ERROR);
        } else {
            redis.del(resetPwdDTO.getPhone() + MALLGlobalConfig.IDENTITY_AUTH_REDIS_KEY_SUFFIX);
        }

        adminService.resetPwd(resetPwdDTO);
        return resFac.getSimpleSuccessResponse();
    }

    @ApiOperation(value = "查询管理员权限")
    @GetMapping("/getAdminAuthMenu")
    public ResponseVO getAdminAuthMenuVO(@RequestHeader String adminId) {
        List<AuthMenuVO> authMenuVO = authMenuService.getAdminAuthMenuVO(adminId);
        return resFac.getSuccessResponseWithData(authMenuVO);
    }

    @ApiOperation(value = "首页统计-商户")
    @GetMapping("/merchantStatistics")
    public ResponseVO merchantStatistics(@RequestHeader String adminId) {
        Admin admin = adminService.getByAdminId(adminId);
        if (!(admin.getType().equals(AdminTypeEnum.MERCHANT.getType())
                || admin.getType().equals(AdminTypeEnum.PLATFORM_MERCHANT.getType()))) {
            return resFac.getResponse(MallResponseError.NO_AUTH_ERROR);
        }
        MerchantStatistics merchantStatistics = adminService.merchantStatistics(admin.getMerchantId());
        return resFac.getSuccessResponseWithData(merchantStatistics);
    }

    @ApiOperation(value = "首页统计-平台")
    @GetMapping("/platformStatistics")
    public ResponseVO platformStatistics(@RequestHeader String adminId) {
        Admin admin = adminService.getByAdminId(adminId);
        if (!(admin.getType().equals(AdminTypeEnum.PLATFORM_ADMINISTRATOR.getType())
                || admin.getType().equals(AdminTypeEnum.PLATFORM.getType()))) {
            return resFac.getResponse(MallResponseError.NO_AUTH_ERROR);
        }
        PlatformStatistics platformStatistics = adminService.platformStatistics();
        return resFac.getSuccessResponseWithData(platformStatistics);
    }

    @ApiOperation(value = "查询商户信息")
    @GetMapping("/getMerchantInfo")
    public ResponseVO getMerchantInfo(@RequestHeader String adminId) {
        PersonInfoVO merchantInfo = adminService.getMerchantInfo(adminId);
        return resFac.getSuccessResponseWithData(merchantInfo);
    }

    @ApiOperation("查询身份证详细信息")
    @GetMapping("/queryIdCard")
    public ResponseVO queryIdCard(@RequestHeader String adminId) {
        Admin admin = adminService.getByAdminId(adminId);
        Merchant merchant = merchantService.getByMerchantId(admin.getMerchantId());
        return resFac.getSuccessResponseWithData(merchant.getIdCard());
    }

    @ApiOperation("修改头像")
    @PutMapping("/repairHeadImg")
    public ResponseVO repairHeadImg(@RequestParam String headImg, @RequestHeader String adminId) {
        adminService.repairHeadImg(adminId, headImg);
        return resFac.getSimpleSuccessResponse();
    }

}
