package com.inkasso.factoring.zhongjiaoxinglu.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.inkasso.adapter.exception.BusinessException;
import com.inkasso.adapter.util.CodeUtil;
import com.inkasso.adapter.util.SpringUtil;
import com.inkasso.config.cache.RedisCache;
import com.inkasso.factoring.file.entity.FileStorageDO;
import com.inkasso.factoring.file.service.FileService;
import com.inkasso.factoring.zhongjiaoxinglu.constant.ZhongJiaoXingLuConstant;
import com.inkasso.factoring.zhongjiaoxinglu.entity.BusinessLicenseOCR;
import com.inkasso.factoring.zhongjiaoxinglu.entity.ZjxlIdCardOcr;
import com.inkasso.factoring.zhongjiaoxinglu.service.ZhongJiaoXingLuService;
import com.inkasso.factoring.zhongjiaoxinglu.util.ZhongJiaoXingLuFileUtil;
import com.openapi.sdk.service.DataExchangeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.bind.ValidationException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.Base64;
import java.util.HashMap;

/**
 * 中交兴路实现层
 *
 * @author fengxuan
 * @email xuan.feng@changan-inkasso.com
 * @date 2021/12/13 11:38
 */
@Service
public class ZhongJiaoXingLuServiceImpl implements ZhongJiaoXingLuService {

    private static RedisCache redisCache;

    private String zjxl_token = "zjxl_token";

    @Autowired
    private FileService fileService;

    @Override
    public ZjxlIdCardOcr idCardOCR(Long frontId, Long backId) {
        File front = null;
        File newFile = null;
        File back = null;
        File newFile2 = null;
        try {
            //查询token
            String token = (String) getRedisCache().get(zjxl_token);
            DataExchangeService des = new DataExchangeService(5000, 8000);
            if (token == null) {
                token = getToken(des);
                redisCache.set(zjxl_token, 60 * 60 * 24, token);
            }
            //前
            FileStorageDO frontFile = fileService.getById(frontId);
            front = new File(frontFile.getAbsolutePath());
            String absolutePath = front.getAbsolutePath();
            String[] split = absolutePath.split("\\.");
            if (front.length() > 800000) {
                absolutePath = split[0] + "2." + split[1];
                ZhongJiaoXingLuFileUtil.compressImg(front.getAbsolutePath(), absolutePath, 0, 0, 0.4f);
                newFile = new File(absolutePath);
            }
            HashMap<String, String> map = new HashMap<>();
            String fileStr = getFileStr(absolutePath);
            String mimeType = Files.probeContentType(front.toPath());
            map.put("faceData", "data:" + mimeType + ";base64," + fileStr);
            //后
            FileStorageDO backFile = fileService.getById(backId);
            back = new File(backFile.getAbsolutePath());
            String absolutePath2 = back.getAbsolutePath();
            String[] split2 = absolutePath2.split("\\.");
            if (back.length() > 800000) {
                absolutePath2 = split2[0] + "2." + split2[1];
                ZhongJiaoXingLuFileUtil.compressImg(back.getAbsolutePath(), absolutePath2, 0, 0, 0.4f);
                newFile2 = new File(absolutePath2);
            }
            String fileStr2 = getFileStr(absolutePath2);
            String mimeType2 = Files.probeContentType(back.toPath());
            map.put("backData", "data:" + mimeType2 + ";base64," + fileStr2);
            map.put("token", token);
            map.put("cid", ZhongJiaoXingLuConstant.CLIENTID);
            map.put("srt", ZhongJiaoXingLuConstant.SECRET);

            String result = des.postHttps("https://zhiyunopenapi.95155.com/save/apis/idCardLicenseV2", map);
            JSONObject json = (JSONObject) JSONObject.parse(result);
            String status = json.getString("status");
            if ("1001".equals(status)) {
                //查询数据入库
                JSONObject jsonObject = json.getJSONObject("result");
                ZjxlIdCardOcr zjxlIdCardOcr = jsonObject.toJavaObject(ZjxlIdCardOcr.class);

                if (StringUtils.isEmpty(zjxlIdCardOcr.getName())) {
                    throw new ValidationException("身份证 ocr失败识别，请手动录入相关信息");
                }
                return zjxlIdCardOcr;
            } else {
                throw new BusinessException(CodeUtil.FAIL, "身份证OCR出现异常:" + status);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(CodeUtil.FAIL, "身份证OCR出现异常:" + e);
        } finally {
            if (newFile != null) {
                newFile.delete();
            }
            if (newFile2 != null) {
                newFile2.delete();
            }
        }
    }

    @Override
    public BusinessLicenseOCR do_businessLicenseOCR(Long fileId) {
        try {
            //查询token
            String token = (String) getRedisCache().get(zjxl_token);
            DataExchangeService des = new DataExchangeService(5000, 8000);
            if (token == null) {
                token = getToken(des);
                redisCache.set(zjxl_token, 60 * 60 * 24, token);
            }
            HashMap<String, String> map = new HashMap<>();
            //后
            FileStorageDO fileStorageDO = fileService.getById(fileId);
            File file = new File(fileStorageDO.getAbsolutePath());
            String absolutePath2 = file.getAbsolutePath();
            String fileStr2 = getFileStr(absolutePath2);
            String mimeType2 = Files.probeContentType(file.toPath());
            map.put("faceData", "data:" + mimeType2 + ";base64," + fileStr2);
            map.put("token", token);
            map.put("cid", ZhongJiaoXingLuConstant.CLIENTID);
            map.put("srt", ZhongJiaoXingLuConstant.SECRET);

            String result = des.postHttps("https://zhiyunopenapi.95155.com/save/apis/businessLicenseOCR", map);
            JSONObject json = (JSONObject) JSONObject.parse(result);
            String status = json.getString("status");
            if ("1001".equals(status)) {
                JSONObject jsonObject = json.getJSONObject("result");
                BusinessLicenseOCR businessLicenseOCR = jsonObject.toJavaObject(BusinessLicenseOCR.class);

                if (StringUtils.isEmpty(businessLicenseOCR.getName())) {
                    throw new ValidationException("营业执照 ocr失败识别，请手动录入相关信息");
                }
                return businessLicenseOCR;
            } else {
                throw new BusinessException(CodeUtil.FAIL, "营业执照OCR出现异常:" + status);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(CodeUtil.FAIL, "营业执照OCR出现异常:" + e);
        }
    }


    public static String getFileStr(String filePath) {
        InputStream in = null;
        byte[] data = null;
        // 读取文件字节数组
        try {
            in = new FileInputStream(filePath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 对字节数组Base64编码
        Base64.Encoder encoder = Base64.getEncoder();
        // 返回 Base64 编码过的字节数组字符串
        return encoder.encodeToString(data);
    }

    /**
     * 获取中交兴路token
     *
     * @return
     */
    private String getToken(DataExchangeService des) {
        HashMap<String, String> map = new HashMap<>();
        map.put("user", ZhongJiaoXingLuConstant.USERNAME);
        map.put("pwd", ZhongJiaoXingLuConstant.PASSWORD);
        map.put("cid", ZhongJiaoXingLuConstant.CLIENTID);
        map.put("srt", ZhongJiaoXingLuConstant.SECRET);
        try {
            String result = des.postHttps(ZhongJiaoXingLuConstant.GETTOKENURL, map);
            JSONObject json = (JSONObject) JSONObject.parse(result);
            String status = json.getString("status");
            if ("1001".equals(status)) {
                return json.getString("result");
            } else {
                throw new BusinessException(CodeUtil.FAIL, "获取中交兴路token出现异常:" + status);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(CodeUtil.FAIL, "获取中交兴路token出现异常：" + e);
        }
    }


    private RedisCache getRedisCache() {
        if (redisCache == null) {
            redisCache = SpringUtil.getBeanByType(RedisCache.class);
        }
        return redisCache;
    }
}
