package com.mortals.xhx.module.idCard.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.mortals.framework.util.DataUtil;
import com.mortals.xhx.busiz.rsp.IdCardResp;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.common.utils.Base64Util;
import com.mortals.xhx.module.idCard.TMZMain;
import com.mortals.xhx.module.idCard.model.IdCardCons;
import com.mortals.xhx.module.idCard.model.XzxIdCard;
import com.mortals.xhx.module.idCard.service.IdCardService;
import com.mortals.xhx.module.idCard.service.TMZSDK;
import com.sun.jna.ptr.IntByReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * TMZ身份证实现类
 * <p>
 * 加载so 调用so方法 完成身份证阅读
 *
 * @author: zxfei
 * @date: 2023/12/12 15:04
 */
@Service
@Slf4j
@ConditionalOnProperty(prefix = "config", name = "idcard", havingValue = "tmz")
public class TMZIdCardServiceImpl implements IdCardService {

    private Boolean DevOpen = false;

    private Integer waitTime = 60;//单位秒

    @Override
    public IdCardResp readIdCardMessage(IdCardCons cons) {
        if (cons.getWaitTime() != null) {
            DataUtil.converStr2Int(cons.getWaitTime(), 60);
        }

        IdCardResp idCardResp = new IdCardResp();
        idCardResp.setStatus(YesNoEnum.NO.getValue() + "");

        boolean sdkInstance = TMZMain.createSDKInstance();
        if (!sdkInstance) {
            idCardResp.setMessage("身份证阅读器初始化sdk失败！");
            return idCardResp;
        }
        if (DevOpen) {
            //关闭设备
            TMZMain.tmzSDK._SDT_CloseDev();
        }
        int openret = TMZMain.tmzSDK._SDT_OpenUsbByFD(0);
        log.info("打卡usb:{}", Integer.toHexString(openret));
        if (Integer.toHexString(openret).equals("90")) {
            ReadIDCardCycle(idCardResp);
        }
        return idCardResp;

    }

    /**
     * 循环读卡
     *
     * @param idCardResp
     * @return
     */
    private IdCardResp ReadIDCardCycle(IdCardResp idCardResp) {
        //等待时间 判断退出
        DateTime endTime = DateUtil.offsetSecond(new Date(), waitTime);
        while (true) {
            int compare = DateUtil.compare(new Date(), endTime);
            if (compare > 0) {
                //超过读取时间，跳出循环，返回超时读取错误
                idCardResp.setStatus(YesNoEnum.NO.getValue() + "");
                idCardResp.setMessage("读取超时！");
                break;
            }
            Boolean readIDCard = this.ReadIDCard(idCardResp);
            if (readIDCard) {
                log.info("读取成功！");
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                log.error(e.getMessage());
            }
        }
        return idCardResp;

    }

    private Boolean ReadIDCard(IdCardResp idCardResp) {
        //寻卡
        byte[] pucManaInfo = new byte[4];
        int ret = TMZMain.tmzSDK._SDT_StartFindIDCard(pucManaInfo);
        log.info("寻卡:0x{},pucManaInfo:{}", Integer.toHexString(ret), pucManaInfo);

        //选卡
        int selectret = TMZMain.tmzSDK._SDT_SelectIDCard(pucManaInfo);
        log.info("选卡:0x{}", Integer.toHexString(selectret));
        //读卡
        byte[] pucCHMsg = new byte[512];
        byte[] pucPHMsg = new byte[2048];
        byte[] pucFPMsg = new byte[2048];

        IntByReference puiCHMsgLen = new IntByReference();
        IntByReference puiPHMsgLen = new IntByReference();
        IntByReference puiFHMsgLen = new IntByReference();
        int readret = TMZMain.tmzSDK._SDT_ReadBaseFPMsg(pucCHMsg, puiCHMsgLen, pucPHMsg, puiPHMsgLen, pucFPMsg, puiFHMsgLen);
        log.info("读卡:0x{}", Integer.toHexString(readret));

        IntByReference iType = new IntByReference();
        byte[] pSFZInfo = new byte[260];
        int parseret = TMZMain.tmzSDK._SDT_ParseIDCardTextInfo(pucCHMsg, puiCHMsgLen.getValue(), iType, pSFZInfo);
        String sfzStr = new String(pSFZInfo, StandardCharsets.UTF_8);
        List<String> splitList = StrUtil.split(sfzStr, "|");

        //String[] split = sfzStr.split("|");
        log.info("parseret:0x{},sfzStr:{}", Integer.toHexString(parseret), sfzStr);
        //身份证信息封装
        if (splitList.size() > 7) {
            if (ObjectUtils.isEmpty(splitList.get(0))) {
                log.info("身份证号码为空！");
                return false;
            }

            idCardResp.setUsername(splitList.get(0));
            idCardResp.setSex(splitList.get(1));
            idCardResp.setNation(splitList.get(2));
            idCardResp.setBorn(splitList.get(3));
            idCardResp.setAddress(splitList.get(4));
            idCardResp.setIdcardno(splitList.get(5));
            idCardResp.setGrantDept(splitList.get(6));
            idCardResp.setUserLifeBegin(splitList.get(7));
            idCardResp.setUserLifeEnd(splitList.get(8));
            String fileName = "/tmp/sfz_" + new Date().getTime() + ".jpg";
            byte[] pBmpFile = fileName.getBytes(StandardCharsets.UTF_8);
            int photoRet = TMZMain.tmzSDK._SDT_ParsePhotoInfo(pucPHMsg, puiPHMsgLen.getValue(), 4, pBmpFile);
            log.info("photoRet:0x{},pucPHMsg lens:{}", Integer.toHexString(photoRet), pucPHMsg.length);

            boolean exist = FileUtil.exist(fileName);
            if(exist){
                byte[] bytes = FileUtil.readBytes(fileName);
                String photoBase64 = Base64.encode(bytes);
                idCardResp.setPhotoBase64String("data:image/jpg;base64," + photoBase64);
            }
            idCardResp.setStatus(YesNoEnum.YES.getValue() + "");
            idCardResp.setMessage("获取身份证成功");
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
 /*       byte[] bytes = FileUtil.readBytes("E:\\pic\\1.png");

        String s = Base64.encode(bytes);
        System.out.println(s);
*/

        String str = "||||||||||";

        // String[] split = str.split("|");

        List<String> split = StrUtil.split(str, "|");
        System.out.println(split.get(0));

    }

}
