package cn.hmsoft.hmplatform.identity.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
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.stereotype.Service;

import cn.hmsoft.ai.identity.IdentifiedResult;
import cn.hmsoft.ai.identity.IdentityAI;
import cn.hmsoft.frame.exception.BusinessException;
import cn.hmsoft.helper.CollectionHelper;
import cn.hmsoft.hmplatform.constants.StdResType;
import cn.hmsoft.hmplatform.helper.ParamHelper;
import cn.hmsoft.hmplatform.identity.data.dao.PStdRegDao;
import cn.hmsoft.hmplatform.identity.data.dao.PStdResDao;
import cn.hmsoft.hmplatform.identity.data.dao.PStdResLogDao;
import cn.hmsoft.hmplatform.identity.data.model.PStdReg;
import cn.hmsoft.hmplatform.identity.data.model.PStdRes;
import cn.hmsoft.hmplatform.identity.data.model.PStdResLog;
import cn.hmsoft.hmplatform.identity.util.EncodeHelper;
import cn.hmsoft.log.LogHelper;

@Service
public class IdentifyService {
	
	@Autowired
	private PStdRegDao daoStd;
	@Autowired
	private PStdResDao daoRes;
	@Autowired
	private PStdResLogDao daoResLog;
	
	/**
	 * @公安部身份认证.
	 * @param cert_id
	 * @param std_name
	 * @param image_file 待写入的路径
	 * @param image 客户端传入的照片
	 * @return
	 */
	public Map<String, Object> verify(String cert_id, String std_name, String image, String from_project) {
		IdentifiedResult result = null;
		PStdRes res = this.daoRes.findRes(cert_id, LocalDate.now(), StdResType.Identify.toString());
		String max = CollectionHelper.getParamValue(ParamHelper.GobalParamMap, "IdentifyCallNumber", "5");
		Map<String, Object> map = new HashMap<String, Object>();
		if (res != null && res.getRes_number() != null && res.getRes_number() >= (Integer.parseInt(max) + res.getRes_plus())) {
			map.put("success", false);
			map.put("error_msg", "该考生今天身份证超限，明天再试！");
			map.put("percent", 0);
			map.put("image_url", "");
			return map;
		}
		PStdReg std = this.daoStd.findBySql("select * from p_std_reg where cert_id=?", cert_id);
		if (std != null && std.getVerify_status().equals("Active")) {
			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());
			//LogHelper.info("--------88------" + std.getCert_id() + "," + resLogList.size());			
			if (resLogList.size() > 0) {
				//LogHelper.info("----------99------" + resLogList.get(0).getRes_result());					
				map.put("success", true);
				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 map;
			}
		} else {
			String localDir = CollectionHelper.getParamValue(ParamHelper.GobalParamMap, "MaterialLocalPath", "/data/uploadfile/image/");
			File dir = new File(localDir);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			File imageFile = new File(localDir + cert_id + ".jpg");
			this.saveStdImage(imageFile, image);//先写入照片
			result = IdentityAI.instance().verify(imageFile, cert_id, std_name);//比对
			if (std == null) {
				std = new PStdReg();
				std.setStd_name(std_name);
				std.setCert_id(cert_id);
				std.setFrom_project(from_project);
				std.setStd_birthday(null);
				std.setStd_nation(null);
				std.setStd_sex(null);
				std.setVerify_time(LocalDateTime.now());
				std.setVerify_status("InActive");//默认
				this.daoStd.insert(std);
			}
			PStdResLog log = new PStdResLog();
			log.setStd_id(std.getStd_id());
			log.setRes_desc(result.getError_msg());
			if (result.getPercent() >= 70 && result.isSuccess()) {
				log.setRes_desc("成功！");
				std.setVerify_status("Active");
				String std_image = CollectionHelper.getParamValue(ParamHelper.GobalParamMap, "MaterialWebPath", 
						"http://p.hmsoft.cn/image/") + cert_id + ".jpg";
				std.setStd_image(std_image);
				this.daoStd.update(std);
				map.put("success", true);
				map.put("error_msg", result.getError_msg());
				map.put("percent", result.getPercent());
				map.put("image_url", std_image);
			} else {
				std.setVerify_status("InActive");
				this.daoStd.update(std);
				map.put("success", false);
				map.put("error_msg", result.getError_msg());
				map.put("percent", result.getPercent());
				map.put("image_url", "");
			}
			log.setRes_result(String.valueOf(result.getPercent()));
			log.setRes_time(LocalDateTime.now());
			log.setRes_param(cert_id + "," + std_name);
			log.setRes_type(StdResType.Identify.toString());
			this.daoResLog.insert(log);
		}
		//更新限制
		if (res == null) {
			res = new PStdRes();
			res.setRes_date(LocalDate.now());
			res.setRes_number(1);
			res.setRes_plus(0);
			res.setCert_id(cert_id);
			res.setRes_type(StdResType.Identify.toString());
			res.setStd_id(std.getStd_id());
			this.daoRes.insert(res);
		} else {
			res.setRes_number(res.getRes_number() + 1);
			this.daoRes.updateBySql("update p_std_res set res_number=? where res_date=? and std_id=? and res_type=?", 
					res.getRes_number() + 1,LocalDate.now(), std.getStd_id(), StdResType.Identify.toString());
		}
		return map;
	}
	
	private void saveStdImage(File imageFile, String image) {
		String base64Str = image;
		if (image.startsWith("http")) {
			base64Str = EncodeHelper.encodeUrlImageToBase64(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);
			OutputStream out = new FileOutputStream(imageFile);
			out.write(bytes);
			out.flush();
			out.close();
		} catch (Exception e) {
			throw new BusinessException("认证异常，获取认证照片失败:" + e.getMessage());
		}
	}
	
}
