package cn.hmsoft.hmplatform.identity.control;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.hmsoft.ai.idcard.IdCard;
import cn.hmsoft.ai.idcard.IdCardOcr;
import cn.hmsoft.application.web.Ajax;
import cn.hmsoft.application.web.AjaxControl;
import cn.hmsoft.frame.exception.BusinessException;
import cn.hmsoft.frame.util.FrameAssertUtil;
import cn.hmsoft.helper.CollectionHelper;
import cn.hmsoft.helper.SecureHelper;
import cn.hmsoft.hmplatform.constants.StdResType;
import cn.hmsoft.hmplatform.helper.ParamHelper;
import cn.hmsoft.hmplatform.helper.PlatformParamHelper;
import cn.hmsoft.hmplatform.identity.data.dao.PStdRegDao;
import cn.hmsoft.hmplatform.identity.data.dao.PStdResLogDao;
import cn.hmsoft.hmplatform.identity.data.model.PStdReg;
import cn.hmsoft.hmplatform.identity.data.model.PStdResLog;
import cn.hmsoft.hmplatform.identity.service.IdentifyService;
import cn.hmsoft.hmplatform.identity.service.PStdRegService;
import cn.hmsoft.hmplatform.identity.util.EncodeHelper;

/**
 * @公安部身份认证
 *
 */
@RestController
public class IdentifyControl extends AjaxControl {

	@Autowired
	private PStdRegDao daoStd;
	@Autowired
	private PStdResLogDao daoResLog;
	@Autowired
	private IdentifyService serviceIden;
	
	/**
	 * ocr身份证识别.
	 * @param request_key
	 * @param cert_image url、base64
	 * @return
	 */
	@RequestMapping("/platform/identity/idcard/ocr")
	public Ajax ocrIdCard(String request_key, String cert_image) {
		FrameAssertUtil.isNotEmpty(request_key, "秘钥不能为空!");
		FrameAssertUtil.isNotEmpty(cert_image, "身份证证明照不能为空!");
		File certFile = PlatformParamHelper.createTempFile();
		String base64Str = cert_image;
		if (cert_image.startsWith("http")) {
			base64Str = EncodeHelper.encodeUrlImageToBase64(cert_image);
		}
		try {
			int startPos = base64Str.indexOf(";base64");
			if (startPos > 0) {
				base64Str = base64Str.substring(startPos + 8, base64Str.length());
			}
			base64Str = base64Str.replaceAll("\n", "");
			byte[] bytes = Base64.getDecoder().decode(base64Str);
			Files.write(Paths.get(certFile.getAbsolutePath()), bytes, StandardOpenOption.CREATE);
			IdCard idcard = IdCardOcr.instance().ocrIdCard(certFile);
			if (idcard.isOcr_success()) {
				idcard.setBirthday(null);
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("IdCardInfo", idcard);
				map.put("IdCardFileName", idcard.getPerson_code() + ".jpg");
				return new Ajax(map);
			} else {
				throw new BusinessException("无法识别居民身份证信息，请重新上传清晰的含居民照片的一面");
			}
		} catch (Exception e) {
			throw new BusinessException("ocr异常，获取正面照片失败:" + e.getMessage());
		}
	}
	
	/**
	 * @检查并返回认证 .
	 * @param request_key
	 * @param cert_id 身份证号-必须
	 * @param std_name 姓名号-必须
	 * @param image_file 头像照片url、base64
	 * @return
	 */
	@RequestMapping("platform/identity/verify")
	public Ajax check(String request_key, String cert_id, String std_name, 
			String image, String from_project) {
		FrameAssertUtil.isNotEmpty(request_key, "秘钥不能为空!");
		FrameAssertUtil.isNotEmpty(cert_id, "身份证号不能为空!");
		FrameAssertUtil.isNotNull(std_name, "考生姓名不能为空!");
		FrameAssertUtil.isNotEmpty(image, "认证头像不能为空!");
		FrameAssertUtil.isEqual(request_key, SecureHelper.md5(PlatformParamHelper.IdentifyVerifyPass), "秘钥错误!");
		Map<String, Object> map = this.serviceIden.verify(cert_id, std_name, image, from_project);
		return new Ajax(map);
	}
	
	/**
	 * @公安部身份认证.
	 * @param request_key
	 * @param cert_id 身份证号-必须
	 * @param std_name 姓名号-必须
	 * @param image_file 头像照片url、base64
	 * @return
	 */
	@RequestMapping("platform/identity/check")
	public Ajax check(String request_key, String cert_id) {
		FrameAssertUtil.isNotEmpty(request_key, "秘钥不能为空!");
		FrameAssertUtil.isNotEmpty(cert_id, "身份证号不能为空!");
		Map<String, Object> map = new HashMap<String, Object>();
		PStdReg std = this.daoStd.findBySql("select * from p_std_reg where cert_id=?", cert_id);
		if (std != null) {
			List<PStdResLog> resLogList = this.daoResLog.listBySql("select * from p_std_res_log where res_type=? and std_id=? order by res_time desc", 
					StdResType.Identify.toString(), std.getStd_id());
			if (std.getVerify_status().equals("Active")) {
				if (resLogList.size() > 0) {
					map.put("success", true);
					map.put("error_msg", "成功！");
					map.put("percent", Double.valueOf(resLogList.get(0).getRes_result()));
					map.put("image_url", std.getStd_image());
					return new Ajax(map);
				}
			} else {
				if (resLogList.size() > 0) {
					map.put("success", false);
					map.put("error_msg", resLogList.get(0).getRes_desc());
					map.put("percent", Double.valueOf(resLogList.get(0).getRes_result()));
					map.put("image_url", std.getStd_image());
					return new Ajax(map);
				}
			}

		}
		map.put("success", false);
		map.put("error_msg", "没有认证记录!");
		map.put("percent", 0);
		map.put("image_url", "");
		return new Ajax(map);
	}
	
	public static void main2(String[] args) throws FileNotFoundException, IOException {
		String str = Base64.getEncoder().encodeToString(org.apache.commons.io.IOUtils.toByteArray(new FileInputStream(new File("C:/Users/Lenovo/Desktop/2.png"))));
		System.err.println(str);

	}
	public static void main(String[] args) {
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("success", true);
		map.put("error_msg", "该考生今天身份证超限，明天再试！");
		map.put("percent", 0);
		System.out.println(map.get("success"));
		if (Boolean.valueOf(map.get("success").toString()) == true) {
			System.out.println(77);
		}
		
	}
}
