package com.bcxin.identify.api.baidu.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.bcxin.identify.api.baidu.service.BaiduVerifaceService;
import com.bcxin.identify.startup.CacheService;
import com.bcxin.identify.util.Result;
import com.bcxin.identify.util.baidu.BaiduFaceCutUtil;
import com.bcxin.identify.util.baidu.BaiduHttpUtil;
import com.bcxin.identify.util.baidu.v3.Base64Util;
import com.bcxin.identify.util.baidu.v3.FaceMatch;
import com.bcxin.identify.util.codes.CommonConst;
import com.bcxin.identify.util.common.StringUtil;
import com.bcxin.identify.util.sys.ConfigUtil;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * <b> 负责对外接口 </b>
 * @author ZXF
 * @create 2021/01/28 0028 13:20
 * @version
 * @注意事项 </b>
 */
@Controller
@RequestMapping("/identify/api/baidu")
@Slf4j
public class BaiduController {

    @Resource
    private CacheService cacheService;
    @Resource
    private BaiduVerifaceService baiduVerifaceService;

    /**
     * <b> 人脸比对 </b>
     * @author ZXF
     * @create 2021/01/29 0029 13:41
     * @version
     * @注意事项 </b>
     */
    @RequestMapping("/match-face")
    @ResponseBody
    public Result matchFace(HttpServletRequest request) {
        String oneImg = request.getParameter("oneImg");
        String twoImg = request.getParameter("twoImg");
        String version = request.getParameter("version");
        String vtp = request.getParameter("vtp");
        String bizFaceMode = request.getParameter("bizFaceMode");
        String appointChannel = request.getParameter("appointChannel");
        Map<String, String> params = Maps.newHashMap();
        params.put("oneImg", oneImg);
        params.put("twoImg", twoImg);
        params.put("version", version);
        params.put("vtp", vtp);
        params.put("bizFaceMode", bizFaceMode);
        params.put("appointChannel", appointChannel);

        if (StrUtil.isEmpty(oneImg) || StrUtil.isEmpty(twoImg)) {
            return Result.fail("参数不完整");
        }

        Result result = baiduVerifaceService.matchFace(params);

        return result;
    }

    /**
     * <b> 设置高活性比对等级 </b>
     * @author ZXF
     * @create 2021/01/29 0029 13:41
     * @version
     * @注意事项 </b>
     */
    @RequestMapping("/level-face/{level}/{sign}")
    @ResponseBody
    public Result matchFace(@PathVariable("level") int level,@PathVariable("sign") String sign) {
        if("nfgm5zi6srUeag4t35y7hsFgj2jVmg".equals(sign)){
            FaceMatch.setLevel(level);
            return Result.success("操作成功");
        }
        return Result.fail("请求非法");
    }

    /**
     * <b> 身份证识别 </b>
     * @author ZXF
     * @create 2021/01/29 0029 13:41
     * @version
     * @注意事项 </b>
     */
    @RequestMapping("/parsing-idcard")
    @ResponseBody
    public Result parsingIdcard(HttpServletRequest request) {
        String imgPath = request.getParameter("imgPath");
        String side = request.getParameter("side");
//        String token = request.getParameter("token");
//        log.debug("接口【/identify/api/baidu/parsing-idcard】token:"+token);
//        Claims claims;
//        try {
//            claims = JwtUtil.parseJWT(token, ConfigUtil.getValue("JWT_SECRET"));
//        } catch (Exception e) {
//            return Result.fail("秘钥不对，解密失败");
//        }
//        String subject = claims.getSubject();
//        Map<String,String> params = JSON.parseObject(subject, new TypeReference<Map>(){ });
        Map<String,String> params = Maps.newHashMap();
        params.put("imgPath",imgPath);
        params.put("side",side);
        if (StrUtil.isEmpty(params.get("imgPath"))
                || StrUtil.isEmpty(params.get("side"))
                ) {
            return Result.fail("参数不完整");
        }
        log.debug("接口【/identify/api/baidu/parsing-idcard】百度身份证识别流程开始。");
        Result result = baiduVerifaceService.parsingIdcard(new HashMap<>(params));
        log.debug("接口【/identify/api/baidu/parsing-idcard】百度身份证识别流程结束。");
        return result;
    }

    @PostMapping(value = "/create-colour-photo")
    public @ResponseBody Result createColourPhoto(@RequestParam("xfile") MultipartFile xfile, String colorStr) {
        if(xfile == null){
            return Result.fail("请上传图片");
        }
        long startTime = System.currentTimeMillis();
        try {
            /*** 获取百度api的 access_token ****/
            String accessToken = baiduVerifaceService.getBaiduKTAccessToken();
            if(StringUtil.isEmpty(accessToken)){
                return  Result.fail("获取token异常");
            }
            String platform = ConfigUtil.getValue(CommonConst.ENVI_PROD);
            //String uploadPath = "d:\\ase\\upload\\identify\\";
            String uploadPath = ConfigUtil.getValue(CommonConst.SYS_PIC_PATH);

            /*** 生成文件路径 ***/
            String randomNumber = DateUtil.current(false) + RandomUtil.randomNumbers(6);
            String fileName = randomNumber + CommonConst.DOT + "jpg";
            String targetImg = uploadPath + DateUtil.today() + "/" + fileName;

            /*** 先把照片上传到服务器本地 ***/
            File dir = new File(uploadPath + DateUtil.today());
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File targetFile = new File(targetImg);
            xfile.transferTo(targetFile);

            /*** 调用百度api生成一寸免冠彩照并上传华为云 ***/
            String fileUrl = BaiduFaceCutUtil.faceCut(accessToken,platform,targetImg,colorStr);
            long endTime = System.currentTimeMillis();
            log.info("生成证件照耗时："+(endTime-startTime)+"毫秒, FILE："+fileUrl);
            if (StringUtil.isNotEmpty(fileUrl)) {
                return Result.success(Result.SUCCESS_QUERY_MSG,fileUrl);
            } else {
                return Result.fail("生成证件照片失败");
            }
        } catch (Exception e) {
            return Result.fail("生成证件照片异常");
        }
    }

    @PostMapping(value = "/ocr-file-analysis")
    public @ResponseBody String ocrFileAnalysis(@RequestParam("xfile") MultipartFile file) {
        try {
            String tokenBD = cacheService.getBaiduORCAccessToken();
            byte[] fileData = file.getBytes();
            String fileStr = Base64Util.encode(fileData);
            String fileParam = URLEncoder.encode(fileStr, "UTF-8");
            String param = "pdf_file=" +fileParam;
            return BaiduHttpUtil.post("https://aip.baidubce.com/rest/2.0/ocr/v1/accurate", tokenBD, param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

}
