package com.gic.haoban.manage.web.controller;

import com.alibaba.fastjson.JSON;
import com.gic.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.enterprise.api.service.StoreService;
import com.gic.haoban.common.utils.CheckSmsCodeUtil;
import com.gic.haoban.common.utils.GooglePhoneNumberUtil;
import com.gic.haoban.common.utils.HaobanResponse;
import com.gic.haoban.manage.api.response.SendSmsResponse;
import com.gic.haoban.manage.api.service.ValidationCodeApiService;
import com.gic.haoban.manage.web.errCode.HaoBanErrCode;
import com.gic.redis.data.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SendCodeController extends WebBaseController {
    private static Logger logger = LoggerFactory.getLogger(SendCodeController.class);

    @Autowired
    private ValidationCodeApiService validationCodeService;
    @Autowired
    private ClerkService clerkService ;

    /**
     * 验证码发送
     *
     * @param phoneNumber
     * @return
     */
    @RequestMapping("/send-code")
    public HaobanResponse sendCode(String phoneNumber, @RequestParam(defaultValue = "86") String nationcode,
                                   Integer type, String wxEnterpriseId, String staffId,
                                   String storeId, String clerkId) {
        logger.info("短信验证码发送：wxEnterpriseId:{},storeId:{},staffId:{}", wxEnterpriseId, storeId, staffId);
        if (StringUtils.isBlank(phoneNumber) || null == type) {
            logger.info("没有phoneNumber!");
            return resultResponse(HaoBanErrCode.ERR_5);
        }
        if (phoneNumber.equals("--")) {
            logger.info("没有phoneNumber!");
            return resultResponse(HaoBanErrCode.ERR_600002);
        }

        if (!GooglePhoneNumberUtil.checkPhoneNumber(phoneNumber, nationcode)) {
            logger.info("区号或者手机号码不合法:{}-{}", nationcode, phoneNumber);
            return resultResponse(HaoBanErrCode.ERR_20);
        }

        String cacheKey = nationcode + phoneNumber + type;
        Object value = RedisUtil.getCache(cacheKey);
        if (value != null && (boolean) value) {
            logger.info("手机号码:{}-{} 验证码只能一分钟请求一次", nationcode, phoneNumber);
            return resultResponse(HaoBanErrCode.ERR_22);
        } else {
            RedisUtil.setCache(cacheKey, true, 60L);
        }

        String smsCode = "";
        if (CheckSmsCodeUtil.getCacheSmsCode(nationcode + "-" + phoneNumber, type) != null) {
            smsCode = (String) CheckSmsCodeUtil.getCacheSmsCode(nationcode + "-" + phoneNumber, type);
        } else {
            smsCode = CheckSmsCodeUtil.createSMSCode();
            CheckSmsCodeUtil.cacheSmsCode(nationcode + "-" + phoneNumber, smsCode, type);
        }
        logger.info("{}-{} 的 验证码：{}", nationcode, phoneNumber, smsCode);
        SendSmsResponse smsResponse = null;
        ClerkDTO clerk = this.clerkService.getClerkByClerkId(clerkId) ;
        smsResponse = validationCodeService.sendValidationCodeHb3(nationcode, phoneNumber, smsCode, clerk.getEnterpriseId(), storeId, clerkId, true);
        logger.info("{}-{} 的 验证码 发送结果回执：{}", nationcode, phoneNumber, JSON.toJSONString(smsResponse));
        if (!smsResponse.isSuccess()) {
            HaobanResponse response = new HaobanResponse();
            response.setMessage(smsResponse.getMessage());
            response.setErrorCode(HaoBanErrCode.ERR_13.getCode());
            return response;
        }
        return resultResponse(HaoBanErrCode.ERR_1);

    }

    /**
     * 验证码校验
     *
     * @param phoneNumber
     * @return
     */
    @RequestMapping("/validate-code")
    public HaobanResponse validateCode(String phoneNumber, @RequestParam(defaultValue = "86") String nationcode,
                                       String code, int type) {
        if (StringUtils.isBlank(phoneNumber) || StringUtils.isBlank(code)) {
            logger.info("没有phoneNumber!");
            return resultResponse(HaoBanErrCode.ERR_5);
        }
        boolean b = CheckSmsCodeUtil.checkSmsCode(nationcode + "-" + phoneNumber, code, type);

        boolean c = CheckSmsCodeUtil.checkSmsCodeIsDelay(nationcode + "-" + phoneNumber, code, type);
        if (!c) {
            logger.info("phoneNumber:{},code:{} 验证失败，验证码失效", nationcode + "-" + phoneNumber, code);
            return resultResponse(HaoBanErrCode.ERR_21);
        } else if (!b) {
            logger.info("phoneNumber:{},code:{} 验证失败，验证码失败", nationcode + "-" + phoneNumber, code);
            return resultResponse(HaoBanErrCode.ERR_21);
        } else {
            return resultResponse(HaoBanErrCode.ERR_1);
        }
    }

}
