package com.kmall.api.service.faceid;

import com.google.common.collect.ImmutableBiMap;
import com.kmall.api.dao.*;
import com.kmall.api.entity.*;
import com.kmall.manager.dto.FaceIdRequestDto;
import com.kmall.common.constant.Dict;
import com.kmall.common.utils.*;
import com.kmall.manager.manager.faceid.FaceCheckUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * @author huangyq
 * @version 1.0
 * 2019-11-21 15:52
 */
@Service
public class ApiFaceIdService {
    @Autowired
    private ApiThirdMerchantBizMapper apiThirdMerchantBizMapper;
    @Autowired
    private ApiMerchMapper apiMerchMapper;
    @Autowired
    private ApiUserMapper apiUserMapper;
    @Autowired
    private ApiFaceLivenessRecognitionReturnDataMapper apiFaceLivenessRecognitionReturnDataMapper;
    @Autowired
    private ApiOrderMapper apiOrderMapper;

    /**
     * （待小程序开放人脸识别类目）
     * @param faceIdRequestDto
     * @param storeId
     * @param userId
     * @return
     */
    @Transactional
    public String checkLivenessRecognition(FaceIdRequestDto faceIdRequestDto, Long storeId, Long userId) {
        Map<String, Object> valideDate = MapBeanUtil.fromObject(faceIdRequestDto);
        ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder();
        builder.put("merchId", "商户编号");
        builder.put("idCard", "身份证号");
        builder.put("name", "姓名");
        builder.put("videoBase64", "视频的BASE64值");
        builder.put("livenessType", "活体检测类型");
        R r = ValidatorUtil.isEmpty(builder.build(), valideDate);
        if (Integer.valueOf(r.get("code").toString()) != 0) {
            throw new RRException(r.get("msg").toString());
        }

        if(!faceIdRequestDto.getLivenessType().equalsIgnoreCase(Dict.livenessType.item_SILENT.getItem())){
            if(faceIdRequestDto.getLivenessType().equalsIgnoreCase(Dict.livenessType.item_ACTION.getItem())){
                builder.put("validateData", "动作顺序");
            }
            if(faceIdRequestDto.getLivenessType().equalsIgnoreCase(Dict.livenessType.item_LIP.getItem())){
                builder.put("validateData", "数字验证码");
            }
            r = ValidatorUtil.isEmpty(builder.build(), valideDate);
            if (Integer.valueOf(r.get("code").toString()) != 0) {
                throw new RRException(r.get("msg").toString());
            }
        }
        String merchSn = faceIdRequestDto.getMerchId();
        MerchVo merchVo = apiMerchMapper.queryObjectByMerchSn(merchSn);
        if(merchVo == null){
            throw new RRException("商户不存在");
        }
        ThirdMerchantBizVo thirdMerchantBizVo = apiThirdMerchantBizMapper.queryDataByStoreId(storeId);
        if(thirdMerchantBizVo == null){
            throw new RRException("该门店的第三方商户不存在");
        }
        faceIdRequestDto.setMerchName(merchVo.getMerchName());
        faceIdRequestDto.setThirdPartyMerchCode(thirdMerchantBizVo.getThirdPartyMerchCode());
        faceIdRequestDto.setThirdPartyMerchName(thirdMerchantBizVo.getThirdPartyMerchName());

        ResponseData responseData = FaceCheckUtil.checkLivenessRecognition(faceIdRequestDto);
        if(!responseData.getCode().equalsIgnoreCase("0")){
            throw new RRException(responseData.getMsg());
        }else{
            //人脸核验成功了，保存用户表中的最后活体人脸核身时间
            Map faceIdResponseDto = (Map)responseData.getData().getRows().get(0);
            UserVo user = new UserVo();
            user.setId(userId);
            if(StringUtils.isNotEmpty((String)faceIdResponseDto.get("returnTime"))) {
                user.setLastFaceTime((String)faceIdResponseDto.get("returnTime"));
            }
            apiUserMapper.update(user);
            return responseData.getMsg();
        }
    }

    /**
     * 根据订单号获取是否人脸认证成功
     * @param orderIds
     * @return 1：认证成功，2：没有保税展示跨境订单，0/null：未认证
     */
    public String getFaceDataByOrderId(Long[] orderIds){
        int count =0;
        for (Long orderId: orderIds){
            OrderVo orderVo = apiOrderMapper.queryObject(orderId);
            if(orderVo != null){
                if(orderVo.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_10.getItem())){
                    FaceLivenessRecognitionReturnDataVo face = apiFaceLivenessRecognitionReturnDataMapper.getFaceByOrderSn(orderVo.getOrder_sn());
                    if (face != null){
                        return face.getIsFaceCheck();
                    }
                }else{
                    count = count+1;
                }
            }
        }
        if(count==orderIds.length){
            return "2";//没有门店现场订单
        }
        return null;
    }
}
