package com.zhongzheng.modules.face.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.faceid.v20180301.FaceidClient;
import com.tencentcloudapi.faceid.v20180301.models.*;
import com.zhongzheng.common.utils.DateUtils;
import com.zhongzheng.common.utils.file.ImageUtils;
import com.zhongzheng.modules.alioss.service.OssService;
import com.zhongzheng.modules.course.mapper.CourseMapper;
import com.zhongzheng.modules.exam.domain.ExamArrangementGuide;
import com.zhongzheng.modules.face.bo.FaceVo;
import com.zhongzheng.modules.face.service.IFaceService;
import com.zhongzheng.modules.user.bo.UserEditBo;
import com.zhongzheng.modules.user.bo.UserOcrAddBo;
import com.zhongzheng.modules.user.domain.User;
import com.zhongzheng.modules.user.domain.UserOcr;
import com.zhongzheng.modules.user.mapper.UserMapper;
import com.zhongzheng.modules.user.service.IUserOcrService;
import com.zhongzheng.modules.user.service.IUserService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class FaceServiceImpl implements IFaceService {

    @Value("${tencent.cloud.SecretId}")
    private String SecretId;

    @Value("${tencent.cloud.SecretKey}")
    private String SecretKey;

    @Value("${aliyun.oss.endpoint}")
    private String ossHost;

    @Autowired
    private OssService ossService;

    @Autowired
    private IUserOcrService iUserOcrService;

    @Autowired
    private UserMapper userMapper;



    @Override
    public FaceVo getFaceDetectAuth(String RuleId) {
        try{
            Credential cred = new Credential(SecretId, SecretKey);

            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("faceid.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            FaceidClient client = new FaceidClient(cred, "", clientProfile);
            String params = "{\"RuleId\":\""+RuleId+"\"}";
            DetectAuthRequest req = DetectAuthRequest.fromJsonString(params, DetectAuthRequest.class);
    //        DetectAuthRequest req = new DetectAuthRequest();
            DetectAuthResponse resp = client.DetectAuth(req);
            System.out.println(DetectAuthResponse.toJsonString(resp));
            FaceVo vo = BeanUtil.toBean(resp, com.zhongzheng.modules.face.bo.FaceVo.class);
            return vo;
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }
        return null;
    }

    @Override
    public void getDetectInfo(String bizToken,Long userId) {
        try{
            Credential cred = new Credential(SecretId, SecretKey);

            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("faceid.tencentcloudapi.com");

            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);

            FaceidClient client = new FaceidClient(cred, "", clientProfile);

            GetDetectInfoRequest req = new GetDetectInfoRequest();
            req.setBizToken(bizToken);
            req.setRuleId("0");
            GetDetectInfoResponse resp = client.GetDetectInfo(req);
            JSONObject resultObject = JSONObject.parseObject(resp.getDetectInfo());
            if (resultObject.containsKey("Text")){
                Map entry = (Map)resultObject.get("Text");
                int ErrCode = ((Integer)entry.get("ErrCode"));
                if(ErrCode==0){ //0为成功
                    String IdCard = ((String)entry.get("IdCard"));
                    String Name = ((String)entry.get("Name"));
                    //照片
                    Map IdCardData = (Map)resultObject.get("IdCardData");
                    String OcrFront = ((String)IdCardData.get("OcrFront"));
                    String OcrFrontFileName = ossService.uploadBase64(OcrFront);
                    String OcrBack = ((String)IdCardData.get("OcrBack"));
                    String OcrBackFileName = ossService.uploadBase64(OcrBack);
                    //视频最佳帧截图
                    Map BestFrame = (Map)resultObject.get("BestFrame");
                    String imgBestFrame = ((String)BestFrame.get("BestFrame"));
                    String imgBestFrameFileName = ossService.uploadBase64(imgBestFrame);

                    User user = new User();
                    user.setUserId(userId);
                    user.setIdCardImg1(OcrFrontFileName);
                    user.setIdCardImg2(OcrBackFileName);
                    user.setRealname(Name);
                    user.setIdCard(IdCard);
                    user.setCertified(1);
                    user.setCertifiedTime(DateUtils.getNowTime());
                    user.setUpdateTime(DateUtils.getNowTime());
                    userMapper.updateById(user);

                    UserOcrAddBo bo = new UserOcrAddBo();
                    bo.setBestFrame(imgBestFrameFileName);
                    bo.setOcrFront(OcrFrontFileName);
                    bo.setOcrBack(OcrBackFileName);
                    bo.setUserId(userId);
                    bo.setOcrInfo(JSONObject.toJSONString(entry));
                    bo.setStatus(1);
                    iUserOcrService.insertByAddBo(bo);
                    ossService.closeClient();
                }
            }
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }
    }

    @Override
    public FaceVo getPicFaceDetectAuth(String RuleId,Long userId) {
        try{
            Credential cred = new Credential(SecretId, SecretKey);

            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("faceid.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            FaceidClient client = new FaceidClient(cred, "", clientProfile);


            User user = userMapper.selectById(userId);
            if(user.getCertified()==1){
                String IdCard = user.getIdCard();
                String Name = user.getRealname();
                String ImageBase64 = user.getRealname();

                UserOcr ocr = iUserOcrService.queryByUserId(userId);
                String bestFile = ocr.getBestFrame();
                String base64 = ImageUtils.encodeImgageToBase64(ossHost+"/"+bestFile);
              /*  String params = "{\"RuleId\":\""+RuleId+"\",\"IdCard\":\""+IdCard+"\",\"Name\":\""+Name+"\"" +
                        ",\"ImageBase64\":\""+base64+"\"}";*/
                String params = "{\"RuleId\":\""+RuleId+"\",\"IdCard\":\""+IdCard+"\",\"Name\":\""+Name+"\"" +
                        ",\"ImageBase64\":\""+base64+"\"}";
                DetectAuthRequest req = DetectAuthRequest.fromJsonString(params, DetectAuthRequest.class);
                //        DetectAuthRequest req = new DetectAuthRequest();
                DetectAuthResponse resp = client.DetectAuth(req);
                FaceVo vo = BeanUtil.toBean(resp, com.zhongzheng.modules.face.bo.FaceVo.class);
                return vo;
            }
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }
        return null;
    }

    @Override
    public Integer getPicDetectInfo(String bizToken, Long userId) {
        try{
            Credential cred = new Credential(SecretId, SecretKey);

            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("faceid.tencentcloudapi.com");

            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);

            FaceidClient client = new FaceidClient(cred, "", clientProfile);

            GetDetectInfoRequest req = new GetDetectInfoRequest();
            req.setBizToken(bizToken);
            req.setRuleId("1");
            GetDetectInfoResponse resp = client.GetDetectInfo(req);
            System.out.println(resp.getDetectInfo());
            JSONObject resultObject = JSONObject.parseObject(resp.getDetectInfo());
            Map entry = (Map)resultObject.get("Text");
            UserOcrAddBo bo = new UserOcrAddBo();
            bo.setUserId(userId);
            bo.setOcrInfo(JSONObject.toJSONString(entry));
            bo.setStatus(1);
            iUserOcrService.insertByAddBo(bo);
            int ErrCode = ((Integer)entry.get("ErrCode"));
            return ErrCode;
        } catch (TencentCloudSDKException e) {
        }
        return -1;
    }


}
