package cn.quantgroup.xyqb.controller.middleoffice.image;

import cn.quantgroup.xyqb.Constants;
import cn.quantgroup.xyqb.controller.middleoffice.common.image.ImageDTO;
import cn.quantgroup.xyqb.controller.middleoffice.common.image.ImageVerifyStrategyFactory;
import cn.quantgroup.xyqb.controller.middleoffice.common.image.ImageVerifyTypeEnum;
import cn.quantgroup.xyqb.model.ClientType;
import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.service.captcha.IGeetestCaptchaService;
import cn.quantgroup.xyqb.service.captcha.IQuantgroupCaptchaService;
import org.apache.commons.codec.digest.Md5Crypt;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;

/**
 * 图形验证码
 */
@RestController
@RequestMapping("/middle_office/image")
public class ImageController {


    @Resource
    private IGeetestCaptchaService geetestCaptchaService;
    @Resource
    private IQuantgroupCaptchaService quantgroupCaptchaService;

    @Value("${geetest.close:false}")
    private Boolean geetestClose;


    @GetMapping
    public JsonResult image(String userIp, String clientType, String phoneNo) {
        Locale locale = Locale.CHINA;
        String markId = Md5Crypt.md5Crypt(phoneNo.getBytes());
        Map<String, String> data = new HashMap<>();
        Map<String, String> imgMap = null;
        // 优先获取极验
        if (!geetestClose) {
            imgMap = geetestCaptchaService.fetchGeetestCaptcha(markId, userIp, ClientType.valueByName(clientType));
            data.put(Constants.VERIFY_PARAM, Constants.VERIFY_TYPE_GT);
        }
        // 备选方案：量化派图形验证码
        if (Objects.isNull(imgMap) || imgMap.isEmpty()) {
            imgMap = quantgroupCaptchaService.fetchQuantgroupCaptcha(locale);
            data.put(Constants.VERIFY_PARAM, Constants.VERIFY_TYPE_QG);
        }
        // 返回结果
        if (Objects.isNull(imgMap) || imgMap.isEmpty()) {
            return JsonResult.buildErrorStateResult("获取验证码失败", "");
        }
        // 填充数据并返回
        data.putAll(imgMap);
        data.put(Constants.GT_UNIQUE_KEY, markId);
        return JsonResult.buildSuccessResultGeneric(data);
    }

    /**
     * 验证图形验证码
     *
     * @return
     */
    @PostMapping("/verify/{type}")
    public JsonResult verifyGT(@PathVariable ImageVerifyTypeEnum type, @RequestBody ImageDTO imageDTO) {
        boolean verify = ImageVerifyStrategyFactory.get(type).verify(imageDTO);
        if (verify) {
            return JsonResult.buildSuccessResult();
        }
        return JsonResult.buildErrorStateResult("验证码错误", null);
    }

}
