package com.gxwebsoft.love.service.impl;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.common.core.utils.HttpUtils;
import com.gxwebsoft.common.core.utils.ImageUtil;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.love.entity.Certificate;
import com.gxwebsoft.love.mapper.CertificateMapper;
import com.gxwebsoft.love.param.CertificateParam;
import com.gxwebsoft.love.service.CertificateService;
import com.gxwebsoft.love.vo.idcheck.BackRecognitionResult;
import com.gxwebsoft.love.vo.idcheck.FrontRecognitionResult;
import com.gxwebsoft.love.vo.idcheck.Response;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 证件管理记录表Service实现
 *
 * @author 科技小王子
 * @since 2023-06-24 11:18:52
 */
@Service
public class CertificateServiceImpl extends ServiceImpl<CertificateMapper, Certificate> implements CertificateService {

    @Resource
    private RestTemplate restTemplate;

    private String appcode = "566b5786c5874464909d8c0b7f64cdc7";

    @Override
    public PageResult<Certificate> pageRel(CertificateParam param) {
        PageParam<Certificate, CertificateParam> page = new PageParam<>(param);
        //page.setDefaultOrder("create_time desc");
        List<Certificate> list = baseMapper.selectPageRel(page, param);
        return new PageResult<>(list, page.getTotal());
    }

    @Override
    public List<Certificate> listRel(CertificateParam param) {
        List<Certificate> list = baseMapper.selectListRel(param);
        // 排序
        PageParam<Certificate, CertificateParam> page = new PageParam<>();
        //page.setDefaultOrder("create_time desc");
        return page.sortRecords(list);
    }

    @Override
    public Certificate getByIdRel(Integer certificateId) {
        CertificateParam param = new CertificateParam();
        param.setCertificateId(certificateId);
        return param.getOne(baseMapper.selectListRel(param));
    }

    @Override
    public boolean verifyIdcard(Certificate param, List<String> files) {
        // 验证正面
        Response<FrontRecognitionResult> front = idcardfrontrecongnition(files.get(0));
        if(front.getError_code() != 0){
            ExceptionUtil.wrapAndThrow(new Exception(front.getReason()));
            return false;
        }


        // 验证反面
        Response<BackRecognitionResult> back = idcardbackrecongnition(files.get(1));
        if(back.getError_code() != 0){
            ExceptionUtil.wrapAndThrow(new Exception(back.getReason()));
            return false;
        }

        // 信息是否一致
        if(!param.getCertificateCode().equals(front.getResult().getIdcardno())){
            return false;
        }
        if(!param.getRealName().equals(front.getResult().getName())){
            return false;
        }
        boolean b = LocalDateTime.parse(back.getResult().getEndDate()).compareTo(LocalDateTime.now()) > 0;
        return b;
    }

    @Override
    public Response<FrontRecognitionResult> idcardfrontrecongnition(String imageUrl) {

        String host = "https://zidv2.market.alicloudapi.com";
        String path = "/thirdnode/ImageAI/idcardfrontrecongnition";
        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("base64Str", ImageUtil.ImageBase64(imageUrl));


        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            HttpEntity entity = response.getEntity();
            String string = EntityUtils.toString(entity);
            Response<FrontRecognitionResult> o = JSONObject.parseObject(string, new TypeReference<Response<FrontRecognitionResult>>() {
            });

            return o;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public Response<BackRecognitionResult> idcardbackrecongnition(String imageUrl) {

        String host = "https://zidv2.market.alicloudapi.com";
        String path = "/thirdnode/ImageAI/idcardbackrecongnition";
        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("base64Str", ImageUtil.ImageBase64(imageUrl));


        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            HttpEntity entity = response.getEntity();
            String string = EntityUtils.toString(entity);
            Response<BackRecognitionResult> o = JSONObject.parseObject(string, new TypeReference<Response<BackRecognitionResult>>() {
            });

            return o;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

}
