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

import com.alibaba.fastjson.JSONObject;
import com.fzm.mall.server.admin.annotation.AdminLog;
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.MerchantDTO;
import com.fzm.mall.server.admin.home_page.entity.dto.RegisterDTO;
import com.fzm.mall.server.admin.home_page.entity.dto.SetPwdDTO;
import com.fzm.mall.server.admin.home_page.entity.vo.MerchantDetailVO;
import com.fzm.mall.server.admin.home_page.enums.status.MerchantRegisterEnum;
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.IDCardUtil;
import com.fzm.mall.server.admin.util.PhoneFormatCheckUtils;
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 lombok.extern.slf4j.Slf4j;
import org.dozer.DozerBeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @author wangp
 * @date 2021/4/13 15:28
 * @description 商户申请
 * @since JDK 1.8
 */
@Api(tags = "商户申请")
@RestController
@RequestMapping("/merchantApply")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
public class MerchantApplyController {

    private final IMerchantService merchantService;
    private final ResponseFactory resFac;
    private final Redis redis;
    private final IAdminService adminService;
    private final DozerBeanMapper beanMapper;

    //WAIT 平台审核的电话咨询和联系客服 缴纳费用的联系客服和去缴费

    @ApiOperation(value = "注册")
    @AdminLog(description = "首页-商户注册", module = OperateModuleEnum.HOME_PAGE, opType = OperateTypeEnum.REGISTER)
    @PostMapping("/register")
    public ResponseVO merchantRegister(@RequestBody @Valid RegisterDTO registerDTO) {
        String phone = registerDTO.getPhone();

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

        Merchant merchant = merchantService.getByRegisterPhone(phone);
        Integer status = null;

        if (merchant == null) {
            merchantService.merchantRegister(registerDTO);
        } else {
            status = merchantService.getByRegisterPhone(phone).getStatus();
        }

        /*if (merchantService.checkPhoneExist(phone)) {
            return resFac.getResponse(MallResponseError.PHONE_EXIST__ERROR);
        }
        if (adminService.checkAdminExist(phone)) {
            return resFac.getResponse(MallResponseError.PHONE_EXIST__ERROR);
        }*/

        String token = UUIDUtil.getUUID();
        redis.setKey(phone + MALLGlobalConfig.MERCHANT_REGISTER_SUFFIX, token, 10 * 60);

        JSONObject json = new JSONObject();
        json.put("token", token);
        json.put("status", status);
        return resFac.getSuccessResponseWithData(json);
    }

    @ApiOperation(value = "完善信息")
    @AdminLog(description = "首页-完善商户信息", module = OperateModuleEnum.HOME_PAGE, opType = OperateTypeEnum.MERCHANT)
    @PutMapping("/improveInfo")
    public ResponseVO<String> merchantImproveInfo(@RequestBody @Valid MerchantDTO merchantDTO) {
        System.err.println("merchantDTO:" + merchantDTO);
        String redisToken = redis.getKey(merchantDTO.getRegisterPhone() + MALLGlobalConfig.MERCHANT_REGISTER_SUFFIX);
        if (!merchantDTO.getToken().equals(redisToken)) {
            return resFac.getResponse(MallResponseError.INVALID_TOKEN_ERROR);
        }
        if (!PhoneFormatCheckUtils.isChinaPhoneLegal(merchantDTO.getApplyPhone())) {
            return resFac.getResponse(MallResponseError.PHONE_FORMAT__ERROR);
        }
        String validate = IDCardUtil.idCardValidate(merchantDTO.getIdCard());
        if (!validate.equals("YES")) {
            return resFac.getResponse(MallResponseError.ID_CARD_FORMAT_ERROR);
        }
        //BUG
        merchantService.merchantImproveInfo2(merchantDTO);
        return resFac.getSimpleSuccessResponse();
    }

    //WAIT 待晚上缴费逻辑
    @ApiOperation(value = "缴费")
    @AdminLog(description = "首页-注册缴费", module = OperateModuleEnum.HOME_PAGE)
    @PutMapping("/registerPay")
    public ResponseVO<String> registerPay(@RequestParam String phone) {
        merchantService.registerPay(phone);
        return resFac.getSimpleSuccessResponse();
    }

    @ApiOperation(value = "设置密码")
    @PutMapping("/pwdset")
    public ResponseVO SetPwd(@RequestBody SetPwdDTO dto) {
        log.info("设置密码:==========1========="+dto);
        String redisToken = redis.getKey(dto.getPhone() + MALLGlobalConfig.MERCHANT_REGISTER_SUFFIX);
        if (!dto.getToken().equals(redisToken)) {
            return resFac.getResponse(MallResponseError.INVALID_TOKEN_ERROR);
        }
        if (dto.getPwd().equals(MALLGlobalConfig.INIT_PASSWORD)) {
            return resFac.getResponse(MallResponseError.PASSWORD_INIT_ERROR);
        }
        if (!dto.getPwd().matches(MALLGlobalConfig.ADMIN_PASSWORD_REGEX)) {
            return resFac.getResponse(MallResponseError.PASSWORD_FORMAT_ERROR);
        }
        if (!dto.getPwd().equals(dto.getPwd2())) {
            return resFac.getResponse(MallResponseError.PASSWORDS_ENTERED_TWICE_ARE_INCONSISTENT);
        }
        adminService.SetPwd(dto);
        log.info("设置密码:===========4========");
        merchantService.updateStatusByAccount(dto.getPhone(), MerchantRegisterEnum.NORMAL.getStatus());
        return resFac.getSimpleSuccessResponse();
    }

    @ApiOperation(value = "申请进度查询")
    @GetMapping("/applyProgressQuery")
    public ResponseVO applyProgressQuery(@ApiParam(name = "phone", value = "手机号") @RequestParam String phone,
                                         @ApiParam(name = "code", value = "验证码") @RequestParam String code) {
        String redisCode = redis.getKey(phone + MALLGlobalConfig.PHONE_CODE_REGISTER_STATUS_REDIS_KEY_SUFFIX);
        if (!code.equals(redisCode)) {
            return resFac.getResponse(MallResponseError.PHONE_CODE__ERROR);
        }

        String token = UUIDUtil.getUUID();
        redis.setKey(phone + MALLGlobalConfig.MERCHANT_REGISTER_SUFFIX, token, 60 * 60);

        Merchant merchant = merchantService.getByRegisterPhone(phone);
        if (merchant == null) {
            return resFac.getResponse(MallResponseError.PHONE_NOT_REGISTER__ERROR);
        }

        JSONObject json = new JSONObject();
        json.put("token", token);
        json.put("status", merchant.getStatus());
        return resFac.getSuccessResponseWithData(json);
    }

    @ApiOperation(value = "手机号和token查询商户申请进度")
    @GetMapping("/getApplyProgressByPhoneAndToken")
    public ResponseVO getApplyProgressByPhoneAndToken(@ApiParam(name = "phone", value = "手机号") @RequestParam String phone,
                                                      @ApiParam(name = "token", value = "临时") @RequestParam String token) {
        String redisToken = redis.getKey(phone + MALLGlobalConfig.MERCHANT_REGISTER_SUFFIX);
        if (!token.equals(redisToken)) {
            return resFac.getResponse(MallResponseError.INVALID_TOKEN_ERROR);
        }
        Merchant merchant = merchantService.getByRegisterPhone(phone);
        MerchantDetailVO vo = beanMapper.map(merchant, MerchantDetailVO.class);
        if (merchant.getStatus().equals(2)) {
            vo = null;
        }
        JSONObject json = new JSONObject();
        json.put("status", merchant.getStatus());
        json.put("merchant", vo);
        return resFac.getSuccessResponseWithData(json);
    }

}
