package cn.timer.api.controller.dzht;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;

import cn.hutool.json.JSONObject;
import cn.timer.api.bean.dzht.DzhtAssoDkrz;
import cn.timer.api.bean.dzht.DzhtAssoGrrz;
import cn.timer.api.bean.dzht.DzhtAssoGrzc;
import cn.timer.api.bean.dzht.DzhtAssoHtmb;
import cn.timer.api.bean.dzht.DzhtAssoHtwj;
import cn.timer.api.bean.dzht.DzhtAssoQyrz;
import cn.timer.api.bean.qyzx.QyzxEmpEntAsso;
import cn.timer.api.bean.qyzx.QyzxEntInfoM;
import cn.timer.api.bean.yggl.YgglMainEmp;
import cn.timer.api.config.annotation.CurrentUser;
import cn.timer.api.config.annotation.UserBean;
import cn.timer.api.controller.dzht.cn.tign.hz.comm.FileHelper;
import cn.timer.api.controller.dzht.cn.tign.hz.comm.HttpHelper;
import cn.timer.api.controller.dzht.cn.tign.hz.constant.ConfigConstant;
import cn.timer.api.controller.dzht.cn.tign.hz.enums.RequestType;
import cn.timer.api.controller.dzht.cn.tign.hz.exception.DefineException;
import cn.timer.api.dto.dzht.DzhtRzDto;
import cn.timer.api.utils.Result;
import cn.timer.api.utils.ResultUtil;
import cn.timer.api.utils.query.QueryUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@Api(tags = "8.0电子合同")
@Transactional
@RequestMapping(value = "/dzht", produces = { "application/json" })
public class DzhtController {

	// @Autowired
	// private RestTemplate restTemplate;
	// //模拟get请求,第一个参数是链接和参数,第二个是期望的返回对象的类 如String.class
	// restTemplate.getForObject( urlAndArgs , Object.class);
	// //模拟post请求,第一个参数是url, 第二个参数是 传的参数的实体类,第三个是期望的返回类型。
	// restTemplate.postForObject(url, entity, Object.class);
	// //模拟delete请求
	// restTemplate.exchange(nodeUrl,HttpMethod.DELETE,new
	// HttpEntity<String[]>(ids),String.class);

	// @Autowired
	// private HttpServletRequest httpServletRequest;

	@Autowired
	private RestTemplate restTemplate;

	@Autowired
	private HttpSession session;

	/********** 个人证件 *********/
	private static final String CRED_PSN_CH_IDCARD = "CRED_PSN_CH_IDCARD";// 大陆身份证,默认值
	private static final String CRED_PSN_CH_TWCARD = "CRED_PSN_CH_TWCARD";// 台湾来往大陆通行证
	private static final String CRED_PSN_CH_MACAO = "CRED_PSN_CH_MACAO";// 澳门来往大陆通行证
	private static final String CRED_PSN_CH_HONGKONG = "CRED_PSN_CH_HONGKONG";// 香港来往大陆通行证
	private static final String CRED_PSN_FOREIGN = "CRED_PSN_FOREIGN";// 外籍证件
	private static final String CRED_PSN_PASSPORT = "CRED_PSN_PASSPORT";// 护照
	private static final String CRED_PSN_CH_SOLDIER_IDCARD = "CRED_PSN_CH_SOLDIER_IDCARD";// 军官证
	private static final String CRED_PSN_CH_SSCARD = "CRED_PSN_CH_SSCARD";// 社会保障卡
	private static final String CRED_PSN_CH_ARMED_POLICE_IDCARD = "CRED_PSN_CH_ARMED_POLICE_IDCARD";// 武装警察身份证件
	private static final String CRED_PSN_CH_RESIDENCE_BOOKLET = "CRED_PSN_CH_RESIDENCE_BOOKLET";// 户口簿
	private static final String CRED_PSN_CH_TEMPORARY_IDCARD = "CRED_PSN_CH_TEMPORARY_IDCARD";// 临时居民身份证
	private static final String CRED_PSN_CH_GREEN_CARD = "CRED_PSN_CH_GREEN_CARD";// 外国人永久居留证
	private static final String CRED_PSN_SHAREHOLDER_CODE = "CRED_PSN_SHAREHOLDER_CODE";// 股东代码证
	private static final String CRED_PSN_POLICE_ID_CARD = "CRED_PSN_POLICE_ID_CARD";// 警官证
	private static final String CRED_PSN_UNKNOWN = "CRED_PSN_UNKNOWN";// 未知类型

	@GetMapping("/getGrzj")
	@ApiOperation(value = "获取个人证件", httpMethod = "GET", notes = "接口发布说明")
	public Result<List<Map<String, String>>> getGrzj() {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		Map<String, String> map1 = new HashMap<String, String>();
		Map<String, String> map2 = new HashMap<String, String>();
		Map<String, String> map3 = new HashMap<String, String>();
		Map<String, String> map4 = new HashMap<String, String>();
		Map<String, String> map5 = new HashMap<String, String>();
		Map<String, String> map6 = new HashMap<String, String>();
		Map<String, String> map7 = new HashMap<String, String>();
		Map<String, String> map8 = new HashMap<String, String>();
		Map<String, String> map9 = new HashMap<String, String>();
		Map<String, String> map10 = new HashMap<String, String>();
		Map<String, String> map11 = new HashMap<String, String>();
		Map<String, String> map12 = new HashMap<String, String>();
		Map<String, String> map13 = new HashMap<String, String>();
		Map<String, String> map14 = new HashMap<String, String>();
		Map<String, String> map15 = new HashMap<String, String>();
		map1.put("label", "大陆身份证");
		map1.put("value", CRED_PSN_CH_IDCARD);
		map2.put("label", "台湾来往大陆通行证");
		map2.put("value", CRED_PSN_CH_TWCARD);
		map3.put("label", "澳门来往大陆通行证");
		map3.put("value", CRED_PSN_CH_MACAO);
		map4.put("label", "香港来往大陆通行证");
		map4.put("value", CRED_PSN_CH_HONGKONG);
		map5.put("label", "外籍证件");
		map5.put("value", CRED_PSN_FOREIGN);
		map6.put("label", "护照");
		map6.put("value", CRED_PSN_PASSPORT);
		map7.put("label", "军官证");
		map7.put("value", CRED_PSN_CH_SOLDIER_IDCARD);
		map8.put("label", "社会保障卡");
		map8.put("value", CRED_PSN_CH_SSCARD);
		map9.put("label", "武装警察身份证件");
		map9.put("value", CRED_PSN_CH_ARMED_POLICE_IDCARD);
		map10.put("label", "户口簿");
		map10.put("value", CRED_PSN_CH_RESIDENCE_BOOKLET);
		map11.put("label", "临时居民身份证");
		map11.put("value", CRED_PSN_CH_TEMPORARY_IDCARD);
		map12.put("label", "外国人永久居留证");
		map12.put("value", CRED_PSN_CH_GREEN_CARD);
		map13.put("label", "股东代码证");
		map13.put("value", CRED_PSN_SHAREHOLDER_CODE);
		map14.put("label", "警官证");
		map14.put("value", CRED_PSN_POLICE_ID_CARD);
		map15.put("label", "未知类型");
		map15.put("value", CRED_PSN_UNKNOWN);
		list.add(map1);
		list.add(map2);
		list.add(map3);
		list.add(map4);
		list.add(map5);
		list.add(map6);
		list.add(map7);
		list.add(map8);
		list.add(map9);
		list.add(map10);
		list.add(map11);
		list.add(map12);
		list.add(map13);
		list.add(map14);
		list.add(map15);
		return ResultUtil.data(list);
	}

	/********** 组织证件 *********/
	private static final String CRED_ORG_USCC = "CRED_ORG_USCC"; // 统一社会信用代码,默认值
	private static final String CRED_ORG_CODE = "CRED_ORG_CODE"; // 组织机构代码证
	private static final String CRED_ORG_REGCODE = "CRED_ORG_REGCODE"; // 工商注册号
	private static final String CRED_ORG_BUSINESS_REGISTTATION_CODE = "CRED_ORG_BUSINESS_REGISTTATION_CODE"; // 工商登记证
	private static final String CRED_ORG_TAX_REGISTTATION_CODE = "CRED_ORG_TAX_REGISTTATION_CODE"; // 税务登记证
	private static final String CRED_ORG_LEGAL_PERSON_CODE = "CRED_ORG_LEGAL_PERSON_CODE"; // 法人代码证
	private static final String CRED_ORG_ENT_LEGAL_PERSON_CODE = "CRED_ORG_ENT_LEGAL_PERSON_CODE"; // 事业单位法人证书
	private static final String CRED_ORG_SOCIAL_REG_CODE = "CRED_ORG_SOCIAL_REG_CODE"; // 社会团体登记证书
	private static final String CRED_ORG_PRIVATE_NON_ENT_REG_CODE = "CRED_ORG_PRIVATE_NON_ENT_REG_CODE"; // 民办非机构登记证书
	private static final String CRED_ORG_FOREIGN_ENT_REG_CODE = "CRED_ORG_FOREIGN_ENT_REG_CODE"; // 外国机构常驻代表机构登记证
	private static final String CRED_ORG_GOV_APPROVAL = "CRED_ORG_GOV_APPROVAL"; // 政府批文
	private static final String CODE_ORG_CUSTOM = "CODE_ORG_CUSTOM"; // 自定义
	private static final String CRED_ORG_UNKNOWN = "CRED_ORG_UNKNOWN"; // 未知证件类型

	@GetMapping("/getZzzj")
	@ApiOperation(value = "获取组织证件", httpMethod = "GET", notes = "接口发布说明")
	public Result<List<Map<String, String>>> getZzzj() {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		Map<String, String> map1 = new HashMap<String, String>();
		Map<String, String> map2 = new HashMap<String, String>();
		Map<String, String> map3 = new HashMap<String, String>();
		Map<String, String> map4 = new HashMap<String, String>();
		Map<String, String> map5 = new HashMap<String, String>();
		Map<String, String> map6 = new HashMap<String, String>();
		Map<String, String> map7 = new HashMap<String, String>();
		Map<String, String> map8 = new HashMap<String, String>();
		Map<String, String> map9 = new HashMap<String, String>();
		Map<String, String> map10 = new HashMap<String, String>();
		Map<String, String> map11 = new HashMap<String, String>();
		Map<String, String> map12 = new HashMap<String, String>();
		Map<String, String> map13 = new HashMap<String, String>();
		map1.put("label", "统一社会信用代码");
		map1.put("value", CRED_ORG_USCC);
		map2.put("label", "组织机构代码证");
		map2.put("value", CRED_ORG_CODE);
		map3.put("label", "工商注册号");
		map3.put("value", CRED_ORG_REGCODE);
		map4.put("label", "工商登记证");
		map4.put("value", CRED_ORG_BUSINESS_REGISTTATION_CODE);
		map5.put("label", "税务登记证");
		map5.put("value", CRED_ORG_TAX_REGISTTATION_CODE);
		map6.put("label", "法人代码证");
		map6.put("value", CRED_ORG_LEGAL_PERSON_CODE);
		map7.put("label", "事业单位法人证书");
		map7.put("value", CRED_ORG_ENT_LEGAL_PERSON_CODE);
		map8.put("label", "社会团体登记证书");
		map8.put("value", CRED_ORG_SOCIAL_REG_CODE);
		map9.put("label", "民办非机构登记证书");
		map9.put("value", CRED_ORG_PRIVATE_NON_ENT_REG_CODE);
		map10.put("label", "外国机构常驻代表机构登记证");
		map10.put("value", CRED_ORG_FOREIGN_ENT_REG_CODE);
		map11.put("label", "政府批文");
		map11.put("value", CRED_ORG_GOV_APPROVAL);
		map12.put("label", "自定义");
		map12.put("value", CODE_ORG_CUSTOM);
		map13.put("label", "未知证件类型");
		map13.put("value", CRED_ORG_UNKNOWN);
		list.add(map1);
		list.add(map2);
		list.add(map3);
		list.add(map4);
		list.add(map5);
		list.add(map6);
		list.add(map7);
		list.add(map8);
		list.add(map9);
		list.add(map10);
		list.add(map11);
		list.add(map12);
		list.add(map13);
		return ResultUtil.data(list);
	}

	public static String savePath() {
		String savePath = null;
		String name = System.getProperty("os.name");
		if (name.startsWith("Windows")) {
			savePath = "E:\\esignTemplate"; // Windows本地服务器文件保存路径包
		} else if (name.startsWith("Linux")) {
			savePath = "esignTemplate"; // Linux远程服务器文件保存路径包
		} else {
			savePath = "esignTemplate"; // 其他服务器文件保存路径包
		}
		return savePath;
	}

	final static String APP_ID = ConfigConstant.PROJECT_ID;// 项目id
	final static String APP_SECRET = ConfigConstant.PROJECT_SECRET;// 项目密码
//	final static String RE_TOKEN = "8b58973c290cc848b67ff0017cd424ff";

	/********** 接口地址 *********/
	// 获取鉴权
	private static final String ACCESS_TOKEN = ConfigConstant.getToken_URL(APP_ID, APP_SECRET);

//	// 刷新鉴权
//	private static final String REFRESH_TOKEN = ConfigConstant.refreshToken_URL(APP_ID, RE_TOKEN);

	// 创建个人账户接口
	private static final String ACCOUNTS = ConfigConstant.createPerAcc_URL();

	// 创建组织账户接口
//	private static final String ORGANIZATIONS = ConfigConstant.createOrgAcc_URL();

	// 企业认证
//	private static final String ENTERPRISE_AUTHENTICATION = ConfigConstant.getRz_URL(accountId);

	/********** 通用 *********/
	@GetMapping("/getToken")
	@ApiOperation(value = "获取鉴权", httpMethod = "GET", notes = "接口发布说明")
	public Result<Object> getToken() {
		JSONObject a = restTemplate.getForObject(ACCESS_TOKEN, JSONObject.class);
		return ResultUtil.data(a);
	}

//	@GetMapping("/getNewToken")
//	@ApiOperation(value = "刷新鉴权", httpMethod = "GET", notes = "接口发布说明")
//	public Result<Object> getNewToken() {
//		JSONObject a = restTemplate.getForObject(REFRESH_TOKEN, JSONObject.class);
//		JSONObject b = (JSONObject) a.get("data");
//		session.setAttribute("token", b.get("token"));
//		System.err.println(b.get("token"));
//		return ResultUtil.data(b);
//	}

	private Result<JSONObject> grzc(@CurrentUser UserBean userBean, DzhtAssoGrzc grzc) {
		HttpEntity<DzhtAssoGrzc> httpEntity = new HttpEntity<DzhtAssoGrzc>(grzc, headers());
		JSONObject a = restTemplate.postForObject(ACCOUNTS, httpEntity, JSONObject.class);
		if (a != null) {
			JSONObject b = (JSONObject) a.get("data");
			grzc.setAccountId(b.get("accountId").toString());
			String code = a.get("code").toString();
			if (code.equals("0")) {
				grzc.setEmpNum(userBean.getEmpNum());
				grzc.setOrgCode(userBean.getOrgCode());
				grzc.insert();
			}
		}
		return ResultUtil.data(a);
	}

	/************************ 企业认证流程 ************************/
	// 新增e签宝个人注册
	@PostMapping("/addGrzc")
	@ApiOperation(value = "e签宝个人注册", httpMethod = "POST", notes = "接口发布说明")
	public Result<JSONObject> addGrzc(@CurrentUser UserBean userBean, @RequestBody DzhtAssoGrzc grzc) {
		return grzc(userBean, grzc);
	}

	// @PutMapping("/modifyGrzh/{accounts}")
	// @ApiOperation(value = "e签宝个人账户修改", httpMethod = "PUT", notes = "接口发布说明")
	// public Result<Object> modifyGrzh(@CurrentUser UserBean userBean, @RequestBody
	// DzhtAssoGrzc grzc) {
	// HttpEntity<DzhtAssoGrzc> httpEntity = new HttpEntity<DzhtAssoGrzc>(grzc,
	// headers());
	// JSONObject a = restTemplate.postForObject(ACCOUNTS, httpEntity,
	// JSONObject.class);
	// return ResultUtil.data(a);
	// }

	// e签宝个人认证
	@PostMapping("/esignGrrz")
	@ApiOperation(value = "e签宝个人认证(三种类型)", httpMethod = "POST", notes = "接口发布说明")
	public Result<Object> esignGrrz(@CurrentUser UserBean userBean, @RequestBody DzhtAssoGrrz grrz) {
		return grrz(grrz, userBean.getEmpNum(), userBean.getOrgCode());
	}

	// 当前公司用户的e签宝个人帐户
	@PostMapping("/rzUserNow")
	@ApiOperation(value = "发起当前公司用户的e签宝个人帐户认证", httpMethod = "POST", notes = "接口发布说明")
	public Result<Object> rzUserNow(@CurrentUser UserBean userBean, Integer empNum) {
		if (empNum == null || empNum <= 0)
			return ResultUtil.error("请输入正确的员工信息");
		DzhtAssoGrrz grrz = new DzhtAssoGrrz();
		grrz.setType(0);
		YgglMainEmp yg = YgglMainEmp.builder().build().selectOne(new QueryWrapper<YgglMainEmp>().select("phone")
				.eq("org_code", userBean.getOrgCode()).eq("emp_num", empNum));
		if (yg == null)
			return ResultUtil.error("请确认员工是否存在");

		String phone = yg.getPhone();
		if (phone == null)
			return ResultUtil.error("请确认员工手机号是否存在");

		grrz.setMobileNo(yg.getPhone());

		DzhtAssoGrzc grzc = DzhtAssoGrzc.builder().build().selectOne(new QueryWrapper<DzhtAssoGrzc>()
				.select("account_id").eq("org_code", userBean.getOrgCode()).eq("emp_num", empNum));
		String accountId = null;
		if (grzc != null) {
			accountId = grzc.getAccountId();
		} else {
			DzhtController2 d = new DzhtController2();
			accountId = d.grzc(userBean, empNum);
			if (accountId.equals("IDCARD-ERROR"))
				return ResultUtil.error("请先完善身份证信息!");
		}
		grrz.setAccountId(accountId);

		return grrz(grrz, empNum, userBean.getOrgCode());
	}

	private Result<Object> grrz(@RequestBody DzhtAssoGrrz grrz, Integer empNum, Integer orgCode) {
		Integer type = grrz.getType();// 认证类型
		String url = null; // 不同类型不同请求地址
		String accountId = grrz.getAccountId();// 要认证的账户
		HttpEntity<DzhtAssoGrrz> httpEntity = new HttpEntity<DzhtAssoGrrz>(grrz, headers());
		if (type == 0) {
			url = ConfigConstant.getGrrz_URL0(accountId);
		} else if (type == 1) {
			url = ConfigConstant.getGrrz_URL1(accountId);
		} else if (type == 2) {
			url = ConfigConstant.getGrrz_URL2(accountId);
		}
		JSONObject a = restTemplate.postForObject(url, httpEntity, JSONObject.class);
		if (a != null) {
			JSONObject b = (JSONObject) a.get("data");
			String flowId = b.get("flowId").toString();
			session.setAttribute("flowId", flowId);
			grrz.setFlowId(flowId);
			grrz.setEmpNum(empNum);
			grrz.setOrgCode(orgCode);
			String code = a.get("code").toString();

//			grrz.setRepetition(false);// 是否允许重复认证

			if (code.equals("0")) {
				grrz.insert();
				return ResultUtil.data(a);
			} else {
				return ResultUtil.data(a, "发起认证失败");
			}
		}
		return ResultUtil.error();
	}

	// 个人认证校验
	@PostMapping("/telecom3Factors")
	@ApiOperation(value = "个人认证校验(0手机 1银行卡 2刷脸)", httpMethod = "POST", notes = "接口发布说明")
	public Result<Object> telecom3Factors(@CurrentUser UserBean userBean, @RequestBody DzhtRzDto rz) {
		String flowId = session.getAttribute("flowId").toString();
		String url = null;
		Integer type = rz.getType();
		if (type == 0) {
			url = ConfigConstant.getGrrzyz_URL0(flowId);
		} else if (type == 1) {
			url = ConfigConstant.getGrrzyz_URL1(flowId);
		} else if (type == 2) {
			url = ConfigConstant.getGrrzyz_URL2(flowId);
		}

		HttpEntity<DzhtRzDto> httpEntity = new HttpEntity<>(rz, headers());
		ResponseEntity<JSONObject> a = restTemplate.exchange(url, HttpMethod.PUT, httpEntity, JSONObject.class);

		String code = a.getBody().get("code").toString();
		if (code.equals("0")) {
			return ResultUtil.data(a.getBody());
		}
		return ResultUtil.data(a.getBody(), "认证失败");
	}

	// 获取当前用户所有公司
//	@GetMapping("/getAllCompany")
//	@ApiOperation(value = "获取当前用户所有公司", httpMethod = "GET", notes = "接口发布说明")
	private List<Integer> getAllCompany(@CurrentUser UserBean userBean) {
		List<QyzxEmpEntAsso> list = QyzxEmpEntAsso.builder().build()
				.selectList(new QueryWrapper<QyzxEmpEntAsso>().eq("emp_num", userBean.getEmpNum()));
		List<Integer> orgCodeList = Lists.transform(list, newList -> newList.getOrgCode());
		return orgCodeList;
	}

	// 获取公司名称
	@GetMapping("/getCompanyName")
	@ApiOperation(value = "获取公司名称", httpMethod = "GET", notes = "接口发布说明")
	public Result<Object> getCompanyName(@CurrentUser UserBean userBean) {
		List<Map<String, Object>> l = new ArrayList<Map<String, Object>>();
		List<Integer> orgCodeList = getAllCompany(userBean);
		for (Integer orgCode : orgCodeList) {
			Map<String, Object> map = new HashMap<String, Object>();
			QyzxEntInfoM list = QyzxEntInfoM.builder().build()
					.selectOne(new QueryWrapper<QyzxEntInfoM>().eq("id", orgCode));
			map.put("name", list.getName());
			map.put("orgCodeEight", orgCode);
			l.add(map);
		}
		return ResultUtil.data(l, "获取成功");
	}

	// e签宝企业认证
	@PostMapping("/esignQyrz")
	@ApiOperation(value = "e签宝企业认证", httpMethod = "POST", notes = "接口发布说明")
	public Result<Object> esignQyrz(@CurrentUser UserBean userBean, @RequestParam Integer empNum,
			@RequestParam String accountId) {
		DzhtAssoQyrz qyrz = new DzhtAssoQyrz();
		String agentAccountId = DzhtAssoGrzc.builder().build()
				.selectOne(new QueryWrapper<DzhtAssoGrzc>().select("account_id").eq("emp_num", empNum)).getAccountId();
		qyrz.setAccountId(accountId);
		qyrz.setAgentAccountId(agentAccountId);

		qyrz.setRepetition(false);// 是否允许重复认证
		HttpEntity<DzhtAssoQyrz> httpEntity = new HttpEntity<DzhtAssoQyrz>(qyrz, headers());
		JSONObject a = restTemplate.postForObject(ConfigConstant.getJgrz_URL(qyrz.getAccountId()), httpEntity,
				JSONObject.class);
		if (a != null) {
			JSONObject b = (JSONObject) a.get("data");
			if (b != null) {
				String flowId = b.get("flowId").toString();
				session.setAttribute("flowId", flowId);
				qyrz.setFlowId(flowId);
			}
			String code = a.get("code").toString();

//			DzhtAssoQyrz q = DzhtAssoQyrz.builder().build()
//					.selectOne(new QueryWrapper<DzhtAssoQyrz>().eq("org_code", qyrz.getOrgCode())
//							.eq("name", qyrz.getName()).eq("legal_rep_name", qyrz.getLegalRepName())
//							.eq("legal_rep_id_no", qyrz.getLegalRepIdNo()));

			if (code.equals("0")) {
				qyrz.insert();
				return ResultUtil.data(a);
			} else {
				return ResultUtil.data(a, "认证失败");
			}
		}
		return ResultUtil.error();
	}

	// 银行信息模糊查询
	@GetMapping("/getBank")
	@ApiOperation(value = "银行信息模糊查询", httpMethod = "GET", notes = "接口发布说明")
	public Result<Object> getBank(@RequestParam String bank) {
		String flowId = session.getAttribute("flowId").toString();
		/*
		 * JSONObject a = restTemplate.getForObject(
		 * "https://smlopenapi.esign.cn/v2/identity/auth/pub/organization/" + flowId +
		 * "/subbranch?keyWord={bank}", JSONObject.class, bank);
		 */

		HttpEntity<?> entity = new HttpEntity<>(headers());
		ResponseEntity<JSONObject> response = restTemplate.exchange(
				ConfigConstant.host + "/v2/identity/auth/pub/organization/" + flowId + "/subbranch?keyWord={bank}",
				HttpMethod.GET, entity, JSONObject.class, bank);
		// JSONObject a = (JSONObject) response.getBody().get("data");
		// JSONObject b = (JSONObject) a.get("data");
		return ResultUtil.data(response.getBody());
	}

	// 发起银行随机打款
	@PostMapping("/transferMoney")
	@ApiOperation(value = "发起银行随机打款", httpMethod = "POST", notes = "接口发布说明")
	public Result<Object> transferMoney(@RequestBody DzhtAssoDkrz dkrz) {
		String flowId = session.getAttribute("flowId").toString();

		HttpEntity<DzhtAssoDkrz> httpEntity = new HttpEntity<>(dkrz, headers());
		ResponseEntity<JSONObject> a = restTemplate.exchange(
				ConfigConstant.host + "/v2/identity/auth/pub/organization/" + flowId + "/transferRandomAmount",
				HttpMethod.PUT, httpEntity, JSONObject.class);

		dkrz.setFlowId(flowId);
		String code = a.getBody().get("code").toString();
		if (code.equals("0")) {
			dkrz.insert();
			return ResultUtil.data(a.getBody());
		} else {
			return ResultUtil.data(a.getBody(), "打款失败");
		}
	}

	// 打款进度查询
	@GetMapping("/transferProcess")
	@ApiOperation(value = "打款进度查询", httpMethod = "GET", notes = "接口发布说明")
	public Result<Object> transferProcess() {
		// String flowId = DzhtAssoQyrz.builder().build().selectOne(new
		// QueryWrapper<DzhtAssoQyrz>()
		// .eq("org_code", orgCode).select("flow_id").orderByDesc("id").last("limit
		// 1")).getFlowId();
		String flowId = session.getAttribute("flowId").toString();
		HttpEntity<?> entity = new HttpEntity<>(headers());
		ResponseEntity<JSONObject> a = restTemplate.exchange(
				ConfigConstant.host + "/v2/identity/auth/pub/organization/" + flowId + "/transferProcess",
				HttpMethod.GET, entity, JSONObject.class, flowId);
		String code = a.getBody().get("code").toString();
		if (code.equals("0")) {
			return ResultUtil.data(a.getBody());
		} else {
			return ResultUtil.data(a.getBody(), "查询失败");
		}
	}

	// 校验随机打款
	@PostMapping("/verifyMoney")
	@ApiOperation(value = "校验随机打款", httpMethod = "POST", notes = "接口发布说明")
	public Result<Object> verifyMoney(@RequestParam Double amount) {
		String flowId = session.getAttribute("flowId").toString();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("amount", amount);
		com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject(map);
		HttpEntity<com.alibaba.fastjson.JSONObject> httpEntity = new HttpEntity<>(json, headers());
		ResponseEntity<JSONObject> a = restTemplate.exchange(
				ConfigConstant.host + "/v2/identity/auth/pub/organization/" + flowId + "/verifyRandomAmount",
				HttpMethod.PUT, httpEntity, JSONObject.class);

		// JSONObject b = (JSONObject) a.get("data");

		String code = a.getBody().get("code").toString();

		if (code.equals("0")) {
			return ResultUtil.data(a.getBody());
		} else {
			return ResultUtil.data(a.getBody(), "验证失败");
		}
	}

//	// 查询认证信息(当前用户所有公司)
//	@GetMapping("/detail")
//	@ApiOperation(value = "查询最新认证信息", httpMethod = "GET", notes = "接口发布说明")
//	public Result<Object> detail(@CurrentUser UserBean userBean) {
//		ResponseEntity<JSONObject> a = null;
//		String code = null;
//		List<JSONObject> returnList = new ArrayList<JSONObject>();
//
//		List<QyzxEmpEntAsso> list = QyzxEmpEntAsso.builder().build()
//				.selectList(new QueryWrapper<QyzxEmpEntAsso>().eq("emp_num", userBean.getEmpNum()));
//
//		List<Integer> orgCodeList = Lists.transform(list, newList -> newList.getOrgCode());
//
//		for (Integer orgCode : orgCodeList) {
//			DzhtAssoQyrz qyrz = DzhtAssoQyrz.builder().build().selectOne(new QueryWrapper<DzhtAssoQyrz>()
//					.eq("org_code", orgCode).select("flow_id").orderByDesc("id").last("limit 1"));
//			if (qyrz != null) {
//				String flowId = qyrz.getFlowId();
//				HttpEntity<?> entity = new HttpEntity<>(headers());
//				a = restTemplate.exchange(ConfigConstant.host + "/v2/identity/auth/api/common/" + flowId + "/detail",
//						HttpMethod.GET, entity, JSONObject.class);
//
//				code = a.getBody().get("code").toString();
//				returnList.add(a.getBody());
//			}
//		}
//		if (code.equals("0")) {
//			return ResultUtil.data(returnList);
//		} else {
//			return ResultUtil.data(returnList, "查询失败");
//		}
//	}

	// 查询认证信息(当前公司)
	@GetMapping("/detail")
	@ApiOperation(value = "查询最新认证信息", httpMethod = "GET", notes = "接口发布说明")
	public Result<Object> detail(@CurrentUser UserBean userBean) {
		ResponseEntity<JSONObject> a = null;
		String code = null;
		List<JSONObject> returnList = new ArrayList<JSONObject>();
		DzhtAssoQyrz qyrz = DzhtAssoQyrz.builder().build().selectOne(new QueryWrapper<DzhtAssoQyrz>()
				.eq("org_code", userBean.getOrgCode()).select("flow_id").orderByDesc("id").last("limit 1"));
		if (qyrz != null) {
			String flowId = qyrz.getFlowId();
			HttpEntity<?> entity = new HttpEntity<>(headers());
			a = restTemplate.exchange(ConfigConstant.host + "/v2/identity/auth/api/common/" + flowId + "/detail",
					HttpMethod.GET, entity, JSONObject.class);

			code = a.getBody().get("code").toString();
			returnList.add(a.getBody());
		}
		if (code != null && code.equals("0")) {
			return ResultUtil.data(returnList);
		} else {
			return ResultUtil.data(returnList, "查询失败");
		}
	}

	/************************ 合同签署流程 ************************/

	// 创建合同模板文件
	@PostMapping("/createByUploadUrl")
	@ApiOperation(value = "创建合同模板文件", httpMethod = "POST", notes = "接口发布说明")
	public Result<Object> createByUploadUrl(@CurrentUser UserBean userBean, @RequestBody DzhtAssoHtmb htmb) {
		// 下载oss文件到服务器
		String ossUrl = htmb.getOssUrl();
		String fileName = System.currentTimeMillis() + UUID.randomUUID().toString()
				+ ossUrl.substring(ossUrl.lastIndexOf("."));
		String filePath = null;
		try {
			filePath = FileHelper.downLoadFromUrl(ossUrl, fileName, savePath());
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		String contentType = null;
		String contentMd5 = null;
		try {
			contentMd5 = FileHelper.getContentMD5(filePath);
			contentType = FileHelper.getContentType(filePath);
		} catch (Exception e) {
			e.printStackTrace();
		}

		htmb.setOrgCode(userBean.getOrgCode());// 机构id
		htmb.setEmpNum(userBean.getEmpNum());// 员工号
		htmb.setCreatedTime(new Date());// 当前时间
		htmb.setContentMd5(contentMd5);// md5值
		htmb.setContentType(contentType);// MIME类型
		htmb.setFilePath(filePath);// 服务器本地文件路径
		htmb.setFileName(fileName);// 文件名
		if (contentType.equals("application/pdf")) {
			htmb.setConvert2Pdf(false);// 是否转换
		} else if (contentType.equals("application/msword")
				|| contentType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) {
			htmb.setConvert2Pdf(true);
		} else {
			return ResultUtil.error("文件类型错误");
		}

		HttpEntity<DzhtAssoHtmb> httpEntity = new HttpEntity<>(htmb, headers());
		JSONObject a = restTemplate.postForObject(ConfigConstant.createTemplateByUpload_URL(), httpEntity,
				JSONObject.class);
		String code = a.get("code").toString();
		JSONObject b = (JSONObject) a.get("data");
		String templateId = b.get("templateId").toString();
		htmb.setTemplateId(templateId);// 模板id
		String uploadUrl = b.get("uploadUrl").toString();
		htmb.setUploadUrl(uploadUrl);// 直传url

		// 上传字节文件流
		com.alibaba.fastjson.JSONObject j = null;
		try {
			j = HttpHelper.doUploadHttp(RequestType.PUT, uploadUrl, FileHelper.getBytes(filePath), contentMd5,
					contentType);
		} catch (DefineException e) {
			e.printStackTrace();
		}

		if (code.equals("0") && j.get("errCode").toString().equals("0")) {
			htmb.insert();

			File file = new File(filePath);
			boolean delete = file.delete();
			System.err.println(delete);

			return ResultUtil.data(a);
		} else {
			return ResultUtil.data(a, "创建失败");
		}
	}

//	public static void main(String[] args) throws Exception {
//		String ossUrl = "https://8time-v2.oss-cn-shenzhen.aliyuncs.com/8timer2.0/117/test/7001.jpg";
//		String fileName = System.currentTimeMillis() + UUID.randomUUID().toString()
//				+ ossUrl.substring(ossUrl.lastIndexOf("."));
//		String filePath = FileHelper.downLoadFromUrl(ossUrl, fileName, savePath());
//		System.err.println(filePath);
//		File file = new File(filePath);
//		Thread.sleep(2000);
//		System.err.println(file.delete());
//	}

	// 通过模板创建文件
	@PostMapping("/createByTemplate")
	@ApiOperation(value = "创建文件", httpMethod = "POST", notes = "接口发布说明")
	public Result<Object> createByTemplate(@CurrentUser UserBean userBean, @RequestBody DzhtAssoHtwj mbwjDto) {
		String templateId = mbwjDto.getTemplateId();

		// 文件名称
		QueryWrapper<DzhtAssoHtmb> q1 = new QueryWrapper<DzhtAssoHtmb>();
		q1.eq("template_id", templateId);
		String fileName = DzhtAssoHtmb.builder().build().selectOne(q1).getFileName();
		mbwjDto.setName(fileName);
		JSONObject a = restTemplate.postForObject(ConfigConstant.createFileByTemplate_URL(),
				new HttpEntity<DzhtAssoHtwj>(mbwjDto, headers()), JSONObject.class);
		String code = a.getStr("code");
		String fileId = a.getJSONObject("data").getStr("fileId");
		mbwjDto.setFileId(fileId);
		if (code.equals("0")) {
			mbwjDto.insert();
			return ResultUtil.data(a);
		} else {
			return ResultUtil.data(a, "创建失败");
		}

	}

	@GetMapping("/queryName")
	@ApiOperation(value = "查名字", httpMethod = "GET", notes = "接口发布说明")
	public Result<Object> getName(@RequestParam(required = false) Integer empNum) {
		String name = QueryUtil.queryEmpName(empNum);
		Map<String, String> map = QueryUtil.queryVersionName();
		return ResultUtil.datas(map, name, "查询成功");
	}

	/*************************** 设置请求头 ***************************************/
	private HttpHeaders headers() {
		// 刷新鉴权
		JSONObject a = restTemplate.getForObject(ACCESS_TOKEN, JSONObject.class);
		JSONObject b = (JSONObject) a.get("data");
		String token = b.get("token").toString();

		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Type", "application/json");
		headers.add("X-Tsign-Open-App-Id", APP_ID);
		headers.add("X-Tsign-Open-Token", token);
		return headers;
	}

}