package com.sifang.modules.sys.web;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.sifang.modules.alioss.AliyunOSSClientUtil;
import com.sifang.modules.esign.cn.tsign.hz.comm.EsignHttpCfgHelper;
import com.sifang.modules.esign.cn.tsign.hz.comm.EsignHttpResponse;
import com.sifang.modules.esign.cn.tsign.hz.enums.EsignRequestType;
import com.sifang.modules.esign.cn.tsign.hz.exception.EsignDemoException;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sys.common.utils.FileUtils;
import com.sifang.modules.sys.common.utils.StringUtil;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.OcrUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "${adminPath}/common" )
public class CommonController {

	@Value("${img.domain}")
	private String commonStaticImgPath;

	private Logger logger = LoggerFactory.getLogger(getClass());

    /*
     * 上传图片
     *
    */
    @RequestMapping(value = "uploadFile", method = { RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Object webuploadImagesSite(MultipartFile file,HttpServletRequest request, HttpServletResponse response) {
        String filename= file.getOriginalFilename();
        int filenameLeng = filename.lastIndexOf(".");
        String extName = filename.substring(filenameLeng).toLowerCase();
		String pathrul =null;
        Map<String, Object> ret = new HashMap<>();
		try {
			if (".jpeg".equalsIgnoreCase(extName) || ".jpg".equalsIgnoreCase(extName)
					|| ".png".equalsIgnoreCase(extName)) {
				filename = CrmUtils.no();
			}else{
				filename=filename.substring(0,filenameLeng);
			}
			pathrul = AliyunOSSClientUtil.uploadImage(file.getBytes(), extName, filename);

	    	if(StringUtils.isNotBlank(pathrul)){
				ret.put("path", StringUtil.convertBackSlant(pathrul));
                ret.put("filename", filename);
                ret.put("extName", extName);
			}
		}catch (MaxUploadSizeExceededException e){

		}catch (Exception e1) {
			e1.printStackTrace();
			logger.error("webuploadImagesSite --------- > Exception :{}  ",e1);
		}
        System.out.println("uploadFile:" + ret.toString());
        return ret;
    }

	@RequestMapping(value = "uploadFile_Name", method = { RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public Object webuploadFileByName(MultipartFile file,HttpServletRequest request, HttpServletResponse response) {
    	String fileName = request.getParameter("fileName");
		String filename= file.getOriginalFilename();
		int filenameLeng = filename.lastIndexOf(".");
		String extName = filename.substring(filenameLeng).toLowerCase();
		String fileInfo = null;
		Map<String, Object> ret = new HashMap<>();
		try {
			fileInfo = AliyunOSSClientUtil.uploadImage(file.getBytes(), extName,fileName);
			if(StringUtils.isNotBlank(fileInfo)){
				ret.put("path", StringUtil.convertBackSlant(fileInfo));
				ret.put("filename", filename);
				ret.put("extName", extName);
			}
		} catch (Exception e1) {
			e1.printStackTrace();
			logger.error("webuploadImagesSite --------- > Exception :{}  ",e1);
		}
		System.out.println("uploadFile:" + ret.toString());
		return ret;
	}

	@RequestMapping(value = "uploadFileKeepName", method = { RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public Object uploadFileKeepName(MultipartFile file,HttpServletRequest request, HttpServletResponse response) {
		String filename= file.getOriginalFilename();
		int filenameLeng = filename.lastIndexOf(".");
		String extName = filename.substring(filenameLeng).toLowerCase();
		String fileInfo = null;
		Map<String, Object> ret = new HashMap<>();
		try {
			fileInfo = AliyunOSSClientUtil.uploadImage(file.getBytes(), extName, filename);
			if(StringUtils.isNotBlank(fileInfo)){
				ret.put("path", StringUtil.convertBackSlant(fileInfo));
				ret.put("filename", filename);
				ret.put("extName", extName);
			}
		} catch (Exception e1) {
			e1.printStackTrace();
			logger.error("webuploadImagesSite --------- > Exception :{}  ",e1);
		}
		System.out.println("uploadFile:" + ret.toString());
		return ret;
	}


	@ResponseBody
	@RequestMapping("transit")
	public Result transitHttpRequest(@RequestBody  JSONObject js) {
		System.out.println(js);
		Gson gson = new Gson();
		EsignRequestType reqType = EsignRequestType.POST;
        try {
            EsignHttpResponse esignHttpResponse = EsignHttpCfgHelper.sendHttp(reqType,"https://211.160.73.233:29944/gfyun-business-service/rest/repayPlan/impUserInfo", null, js.toString(), true);
			JSONObject jsonObject = gson.fromJson(esignHttpResponse.getBody(), JSONObject.class);
			if (jsonObject.getString("rtnCode").equals("1")){
				return Result.success(jsonObject);
			}else {
				return Result.fail("502","连接三方服务器错误");
			}
        } catch (EsignDemoException e) {
            throw new RuntimeException(e);
        }

	}

	@RequestMapping(value = "AppUploadFile", method = { RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public Object AppUploadFile(HttpServletRequest request) throws IOException {
		Map<String,String> map = Maps.newHashMap();
		String fileType = request.getParameter("file");
		String extName = request.getParameter("extName");
	/*	if (speratorIndex <= -1) {
			map.put("code","205");
			map.put("msg","文件上传失败");
			return map;
		}*/
		byte[] contentBytes = Base64.decodeBase64(fileType);
		try {
			String fileInfo = AliyunOSSClientUtil.uploadImage(contentBytes, extName,extName);
			if(StringUtils.isBlank(fileInfo)){
				map.put("code","205");
				map.put("msg","文件上传失败");
				return map;
			}
			map.put("data", StringUtil.convertBackSlant(fileInfo));
			map.put("code", "200");
			map.put("extName", extName);
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			map.put("code","205");
			map.put("msg","文件上传失败"+e);
			return map;
		}
	}




    /**小程序上传图片使用
    */
    @ResponseBody
	@RequestMapping(value = "/weChat/uploadImage", method = { RequestMethod.POST,RequestMethod.GET})
	public Object uploadImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
		MultipartHttpServletRequest req =(MultipartHttpServletRequest)request;
		MultipartFile file =  req.getFile("file");
		String filename= file.getOriginalFilename();
		String extName = filename.substring(filename.lastIndexOf(".")).toLowerCase();
		String fileInfo = null;
		Map<String, Object> ret = new HashMap<>();
		String path="";
		try {
			fileInfo = AliyunOSSClientUtil.uploadImage(file.getBytes(), extName,filename.replace(extName,""));
			if(StringUtils.isNotBlank(fileInfo)){
				path=StringUtil.convertBackSlant(fileInfo);
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return path;
	}


    //上传其他文件
    @RequestMapping(value = "uploadFile2", method = RequestMethod.POST)
    @ResponseBody
    public Object webuploadImagesSites(MultipartFile file,HttpServletRequest request, HttpServletResponse response) {
		String filename= file.getOriginalFilename();
		String extName = filename.substring(filename.lastIndexOf(".")).toLowerCase();
		String fileInfo = null;
		Map<String, Object> ret = new HashMap<>();
		try {
			fileInfo = AliyunOSSClientUtil.uploadImage(file.getBytes(), extName,filename.replace(extName,""));
			if(StringUtils.isNotBlank(fileInfo)){
				ret.put("path", StringUtil.convertBackSlant(fileInfo));
				ret.put("extName", extName);
				ret.put("filename", filename);
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		System.out.println("uploadFile:" + ret.toString());
		return ret;
    }

	//上传其他文件
	@RequestMapping(value = "uploadFile3", method = RequestMethod.POST)
	@ResponseBody
	public Object uploadFile3(MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
		String filename = file.getOriginalFilename();
		String extName = filename.substring(filename.lastIndexOf(".")).toLowerCase();
		String fileInfo = null;
		Map<String, Object> ret = new HashMap<>();
		try {
			fileInfo = AliyunOSSClientUtil.uploadImage(file.getBytes(), extName, filename);
			if (StringUtils.isNotBlank(fileInfo)) {
				ret.put("path", StringUtil.convertBackSlant(fileInfo));
				ret.put("extName", extName);
				ret.put("filename", filename);
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		System.out.println("uploadFile:" + ret.toString());
		return ret;
	}

	/*
  * 上传图片
 */
	@RequestMapping(value = "uploadDjyFileimg", method = RequestMethod.POST)
	@ResponseBody
	public Object uploadDjyFileimg(MultipartFile file,HttpServletRequest request, HttpServletResponse response) {
		String filename= file.getOriginalFilename();
		String extName = filename.substring(filename.lastIndexOf(".")).toLowerCase();
		String fileInfo = null;
		Map<String, Object> ret = new HashMap<>();
		Map<String, Object> retw = new HashMap<>();
		try {
			fileInfo = AliyunOSSClientUtil.uploadImage(file.getBytes(), extName,filename);
			if(StringUtils.isNotBlank(fileInfo)){
				retw.put("src", StringUtil.convertBackSlant(fileInfo));
				ret.put("data", retw);
				ret.put("code", "200");
				ret.put("msg", extName);
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		System.out.println("uploadFile:" + ret.toString());
		return ret;
	}


	@RequestMapping(value = "updateImgBankCard", method = { RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public Object updateImgBankCard(MultipartFile file,HttpServletRequest request, HttpServletResponse re) {
		Map<String, Object> ret = updateBankCardImg(file);
		logger.info("updateImgBankCard:" + ret.toString());
		return ret;
	}

	@RequestMapping(value = "uploadImgIdentify", method = { RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public Object uploadImgIdentify(MultipartFile file,HttpServletRequest request, HttpServletResponse re) {
		Map<String, Object> ret = new HashMap<>();
		ret = updateImgAll(file);
		logger.info("uploadFile:" + ret.toString());
		return ret;
	}

	@ResponseBody
	@RequestMapping(value = "/weChat/uploadImageIden", method = { RequestMethod.POST,RequestMethod.GET})
	public Object uploadImageIden(HttpServletRequest request, HttpServletResponse response) throws IOException {
		MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
		MultipartFile file = req.getFile("file");
		Map<String, Object> ret =  updateImgAll(file);
		logger.info("mapreq :{}",ret);
		return ret;
	}

	/**
	 * （实控人证件上传--获取图片的真实后缀）
	 */
	@ResponseBody
	@RequestMapping("/uploadSampleFile")
	public Object uploadSampleFile(MultipartFile file) {
		Map<String, Object> ret = new HashMap<>();
		String pathrul =null;
		String filename= file.getOriginalFilename();
		int filenameLeng = filename.lastIndexOf(".");
		try {
			byte[] bytes=file.getBytes();
			String picType= FileUtils.getPicType(bytes);
			logger.info(">>>>>>>uploadFile  picType:{}",picType);
			if(StringUtils.isBlank(picType) || !("jpg,png,bmp").contains(picType)){
				throw new BusinessException("身份证或者银行卡照片只能是 jpg,png,bmp 格式；");
			}
			filename=filename.substring(0,filenameLeng-1);
			pathrul = AliyunOSSClientUtil.uploadImage(file.getBytes(), picType, filename);

			if(StringUtils.isNotBlank(pathrul)){
				ret.put("path", StringUtil.convertBackSlant(pathrul));
				ret.put("filename", filename);
				ret.put("extName", picType);
			}
		} catch (Exception e) {
			e.printStackTrace();

		}
	 	return ret;
	}

	public Map<String,Object> updateImgAll(MultipartFile file){
		String filename= file.getOriginalFilename();
		int filenameLeng = filename.lastIndexOf(".");
		String extName = filename.substring(filenameLeng).toLowerCase();
		String pathrul =null;
		Map<String, Object> ret = new HashMap<>();
		try {
			if (".jpeg".equalsIgnoreCase(extName) || ".jpg".equalsIgnoreCase(extName)
					|| ".png".equalsIgnoreCase(extName)) {
				filename = CrmUtils.no();
			}else{
				filename=filename.substring(0,filenameLeng-1);
			}
			pathrul = AliyunOSSClientUtil.uploadImage(file.getBytes(), extName, filename);
		logger.info("图片地址----------：{}",pathrul);
			if(StringUtils.isNotBlank(pathrul)){
				String imgurl =StringUtil.convertBackSlant(pathrul);

				String data = OcrUtils.uploadImgIdentify(commonStaticImgPath + imgurl);
				Gson gson=new Gson();
				if (StringUtils.isNotBlank(data)) {
					Map<String, Object> map = gson.fromJson(data, Map.class);
					Map<String, Object> faceData =  gson.fromJson(gson.toJson(map.get("data")), Map.class);
					if (faceData.get("face") == null && faceData.get("back") == null) {
						ret.put("info", gson.toJson(Result.fail("身份证图片识别失败")));
					}
					else {
						ret.put("info", data);
					}
				}
				else {
					ret.put("info", gson.toJson(Result.fail("身份证图片识别失败")));
				}
				//识别-
				ret.put("path", imgurl);
				ret.put("filename", filename);
				ret.put("extName", extName);
			}
		}catch (Exception e1) {
			e1.printStackTrace();
			logger.error("webuploadImagesSite --------- > Exception :{}  ",e1);
		}
		System.out.println("uploadFile:" + ret.toString());
		return ret;
	}

	public Map<String,Object> updateBankCardImg(MultipartFile file){
		String filename= file.getOriginalFilename();
		int filenameLeng = filename.lastIndexOf(".");
		String extName = filename.substring(filenameLeng).toLowerCase();
		String pathrul =null;
		Map<String, Object> ret = new HashMap<>();
		try {
			if (".jpeg".equalsIgnoreCase(extName) || ".jpg".equalsIgnoreCase(extName)
					|| ".png".equalsIgnoreCase(extName)) {
				filename = CrmUtils.no();
			}else{
				filename=filename.substring(0,filenameLeng-1);
			}
			pathrul = AliyunOSSClientUtil.uploadImage(file.getBytes(), extName, filename);
			logger.info("图片地址----------：{}",pathrul);
			if(StringUtils.isNotBlank(pathrul)){
				String imgurl =StringUtil.convertBackSlant(pathrul);

				String data = OcrUtils.uploadImgBankCard(commonStaticImgPath + imgurl);
				if (StringUtils.isNotBlank(data)) {
					logger.info("info ----:{}",data);
					ret.put("info", data);
				}
				else {
					Gson gson=new Gson();
					ret.put("info", gson.toJson(Result.fail("银行卡号未识别成功，请手动添加!")));
				}
				//识别-
				ret.put("path", imgurl);
				ret.put("filename", filename);
				ret.put("extName", extName);
			}
		}catch (Exception e1) {
			e1.printStackTrace();
			logger.error("updateBankCardImg --------- > Exception :",e1);
		}
		System.out.println("uploadFile:" + ret);
		return ret;
	}

}
