package com.bonus.core.customer.controller;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.core.web.controller.BaseController;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.core.common.utils.HeaderFetchUtil;
import com.bonus.core.customer.dto.UploadPhotoGenCodeDTO;
import com.bonus.core.customer.v4.mobile.service.CustPhotoService;
import com.bonus.encrypt.RequiresGuest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Map;

@Api(
   tags = {"customer-人脸照片控制器"}
)
@RestController
public class CustPhotoController extends BaseController {
   private static final Logger log = LoggerFactory.getLogger(CustPhotoController.class);
   @Resource
   private CustPhotoService custPhotoService;

   @ApiOperation("小程序保存人脸图片")
   @PostMapping({"/custInfo/uploadPhotoGenCodeForApp"})
   @RequiresGuest
   public AjaxResult uploadPhotoGenCodeForApp(@RequestBody @Valid UploadPhotoGenCodeDTO dto) {
      try {
         if (ObjectUtil.isNull(dto.getCustId())) {
            throw new ServiceException("customer.casual.login.bindInExists");
         } else {
            return this.custPhotoService.appletRegisterAndSaveFaceInfo(dto);
         }
      } catch (Exception e) {
            log.error("小程序保存人脸图片失败", e);
            return AjaxResult.error("小程序保存人脸图片失败");
      }
   }

   protected String getOpenidByHeaders(Map<String, String> headers) {
      return HeaderFetchUtil.getValueFromHeadersIgnoreCase(headers, "openid");
   }

   protected Integer getSourceTypeByHeaders(Map<String, String> headers) {
      String value = HeaderFetchUtil.getValueFromHeadersIgnoreCase(headers, "source-type");
      return CharSequenceUtil.isNotBlank(value) ? Integer.valueOf(value) : null;
   }
}
