package com.iotechn.unimall.admin.api.card.impl;

import java.util.*;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iotechn.unimall.data.dto.DistinguishView;
import com.iotechn.unimall.data.util.HttpUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.iotechn.unimall.core.exception.ServiceException;
import com.iotechn.unimall.data.util.ExcelUtil;
import com.iotechn.unimall.data.mapper.CertificateManagementInfoMapper;
import com.iotechn.unimall.data.domain.CertificateManagementInfo;
import com.iotechn.unimall.admin.api.card.ICertificateManagementInfoService;
import com.iotechn.unimall.data.model.Page;
import java.util.Date;
import org.springframework.transaction.annotation.Transactional;

/**
 * 证件管理Service业务层处理
 *
 * @author jlb
 * @date 2023-04-10
 */
@Service
public class CertificateManagementInfoServiceImpl implements ICertificateManagementInfoService {
	@Autowired
	private CertificateManagementInfoMapper certificateManagementInfoMapper;

	@Override
	public Boolean add(CertificateManagementInfo certificateManagementInfo) throws ServiceException {
		Date now = new Date();
		certificateManagementInfo.setGmtCreate(now);
		certificateManagementInfo.setGmtUpdate(now);
		return certificateManagementInfoMapper.insert(certificateManagementInfo) > 0;
	}

	@Override
	public Page<CertificateManagementInfo> list(Long commonId, String certificateName, String certificateImage, Date gmtCreate, Date gmtUpdate, Long deleteFlag, Integer page, Integer limit) throws ServiceException {
		Wrapper<CertificateManagementInfo> wrapper = new EntityWrapper<CertificateManagementInfo>();
		if (!StringUtils.isEmpty(commonId)) {
			wrapper.eq("common_id", commonId);
		}
		if (!StringUtils.isEmpty(certificateName)) {
			wrapper.eq("certificate_name", certificateName);
		}
		if (!StringUtils.isEmpty(certificateImage)) {
			wrapper.eq("certificate_image", certificateImage);
		}
		if (!StringUtils.isEmpty(gmtCreate)) {
			wrapper.eq("gmt_create", gmtCreate);
		}
		if (!StringUtils.isEmpty(gmtUpdate)) {
			wrapper.eq("gmt_update", gmtUpdate);
		}
		if (!StringUtils.isEmpty(deleteFlag)) {
			wrapper.eq("delete_flag", deleteFlag);
		}
		wrapper.eq("delete_flag", 0);
		List<CertificateManagementInfo> list = certificateManagementInfoMapper.selectPage(new RowBounds((page - 1) * limit, limit), wrapper);
		Integer count = certificateManagementInfoMapper.selectCount(wrapper);
		return new Page<CertificateManagementInfo>(list, page, limit, count);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean delete(String id) {
		String[] ids = String.valueOf(id).split(",");
		for (String tt : ids) {
			CertificateManagementInfo tmp = certificateManagementInfoMapper.selectById(Long.parseLong(tt));
			if (tmp != null) {
				tmp.setDeleteFlag(1l);
				tmp.setGmtUpdate(new Date());
				certificateManagementInfoMapper.updateById(tmp);
			}
		}
		return true;
	}

	@Override
	public Boolean update(CertificateManagementInfo certificateManagementInfo) throws ServiceException {
		Date now = new Date();
		certificateManagementInfo.setGmtUpdate(now);
		return certificateManagementInfoMapper.updateById(certificateManagementInfo) > 0;
	}

	@Override
	public CertificateManagementInfo get(Long id) throws ServiceException {
		return certificateManagementInfoMapper.selectById(id);
	}

	@Override
	public String export(Long commonId, String certificateName, String certificateImage, Date gmtCreate, Date gmtUpdate, Long deleteFlag, Integer page, Integer limit) throws ServiceException {
		Wrapper<CertificateManagementInfo> wrapper = new EntityWrapper<CertificateManagementInfo>();
		if (!StringUtils.isEmpty(commonId)) {
			wrapper.eq("common_id", commonId);
		}
		if (!StringUtils.isEmpty(certificateName)) {
			wrapper.eq("certificate_name", certificateName);
		}
		if (!StringUtils.isEmpty(certificateImage)) {
			wrapper.eq("certificate_image", certificateImage);
		}
		if (!StringUtils.isEmpty(gmtCreate)) {
			wrapper.eq("gmt_create", gmtCreate);
		}
		if (!StringUtils.isEmpty(gmtUpdate)) {
			wrapper.eq("gmt_update", gmtUpdate);
		}
		if (!StringUtils.isEmpty(deleteFlag)) {
			wrapper.eq("delete_flag", deleteFlag);
		}
		List<CertificateManagementInfo> list = certificateManagementInfoMapper.selectList(wrapper);
		ExcelUtil<CertificateManagementInfo> util = new ExcelUtil<CertificateManagementInfo>(CertificateManagementInfo.class);
		return util.exportExcel(list, "操作日志");
	}

	@Override
	public DistinguishView personShibie(String certificateImage) throws ServiceException {
		String appcode = "2d59bfa794994f5f94d1d98b7b5bd102";
		//API产品路径
		String requestUrl = "https://personcard.market.alicloudapi.com/ai_market/ai_ocr_universal/shen_fen_zheng/ch/v1";
		//阿里云APPCODE
		DistinguishView distinguishView = new DistinguishView();
		CloseableHttpClient httpClient = null;
		try {
			httpClient = HttpClients.createDefault();
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			//启用URL方式进行识别
			//内容数据类型是图像文件URL链接
			params.add(new BasicNameValuePair("IMAGE", certificateImage));
			params.add(new BasicNameValuePair("IMAGE_TYPE", "1"));

			// 创建一个HttpPost实例
			HttpPost httpPost = new HttpPost(requestUrl);
			httpPost.addHeader("Authorization", "APPCODE " + appcode);
			httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

			// 设置请求参数
			httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));

			// 发送POST请求
			HttpResponse execute = httpClient.execute(httpPost);

			// 获取状态码
			int statusCode = execute.getStatusLine().getStatusCode();
			System.out.println(statusCode);

			// 获取结果
			HttpEntity entity = execute.getEntity();
			String body = EntityUtils.toString(entity);
			System.out.println(body);
			JSONObject jsonObject = JSONObject.parseObject(body);
			distinguishView.setRecPersonNo(jsonObject.getJSONObject("身份证识别实体信息").getJSONObject("身份证人像面实体信息").getString("身份证号"));
			return distinguishView;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public DistinguishView bankShibie(String certificateImage) throws ServiceException {
		String appcode = "2d59bfa794994f5f94d1d98b7b5bd102";
		String host = "https://api06.aliyun.venuscn.com";
		String path = "/ocr/bank-card";
		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("pic", certificateImage);
		try {
			HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
			String body = EntityUtils.toString(response.getEntity());
			System.out.println(body);
			JSONObject jsonObject = JSONObject.parseObject(body);
			if ("200".equals(jsonObject.getString("ret"))) {
				JSONObject data = JSONObject.parseObject(jsonObject.getString("data"));
				DistinguishView distinguishView = new DistinguishView();
				distinguishView.setBankNo(data.getString("number"));

				host = "https://yhkgsd.market.alicloudapi.com";
				path = "/bankcard/region";
				method = "GET";
				headers = new HashMap<String, String>();
				//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
				headers.put("Authorization", "APPCODE " + appcode);
				querys = new HashMap<String, String>();
				querys.put("bankcard", distinguishView.getBankNo());
				try {
					response = HttpUtils.doGet(host, path, method, headers, querys);
					body = EntityUtils.toString(response.getEntity());
					System.out.println(body);
					jsonObject = JSONObject.parseObject(body);
					if ("0".equals(jsonObject.getString("code"))) {
						data = JSONObject.parseObject(jsonObject.getString("data"));
						JSONObject detail = JSONObject.parseObject(data.getString("detail"));
						String[] area = detail.getString("area").split(" - ");
						String province = "";
						String city = "";
						if (area.length > 1) {
							province = area[0];
							city = area[1];
						}

						host = "https://cnaps.market.alicloudapi.com";
						path = "/lianzhuo/querybankaps";
						method = "GET";
						headers = new HashMap<String, String>();
						//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
						headers.put("Authorization", "APPCODE " + appcode);
						querys = new HashMap<String, String>();
						querys.put("card", distinguishView.getBankNo());
						querys.put("province", province);
						querys.put("city", city);
						try {
							response = HttpUtils.doGet(host, path, method, headers, querys);
							System.out.println(response.toString());
							body = EntityUtils.toString(response.getEntity());
							System.out.println(body);
							jsonObject = JSONObject.parseObject(body);
							JSONObject jsonData = jsonObject.getJSONObject("data");
							JSONObject res = jsonObject.getJSONObject("resp");
							if ("200".equals(res.get("RespCode"))) {
								JSONArray jsonArray = jsonData.getJSONArray("record");
								List<String> bankList = new ArrayList<>();
								for (int i = 0; i < jsonArray.size(); i++) {
									bankList.add(jsonArray.getJSONObject(i).get("lName").toString());
								}
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return distinguishView;
			} else {
				System.out.println(jsonObject.getString("msg"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}

