/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the yifu4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.yifu.cloud.plus.v1.yifu.archives.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yifu.cloud.plus.v1.yifu.archives.config.GzConfig;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TAttaInfo;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TEmpContactInfo;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TGzEmpInfo;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TGzOfferInfo;
import com.yifu.cloud.plus.v1.yifu.archives.service.TAttaInfoService;
import com.yifu.cloud.plus.v1.yifu.archives.service.TEmpContactInfoService;
import com.yifu.cloud.plus.v1.yifu.archives.service.TGzEmpInfoService;
import com.yifu.cloud.plus.v1.yifu.archives.service.TGzOfferInfoService;
import com.yifu.cloud.plus.v1.yifu.archives.utils.GZSign;
import com.yifu.cloud.plus.v1.yifu.archives.utils.ReturnGz;
import com.yifu.cloud.plus.v1.yifu.archives.vo.*;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.SecurityConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.OSSUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 瓜子交互控制器
 *
 * @author hgw
 * @date 2025-6-23 09:39:27
 */
@Log4j2
@RestController
@RequiredArgsConstructor
@RequestMapping("/gz/core")
@Tag(name = "瓜子交互控制器")
public class TGzController {

	@Autowired
	private GzConfig gzConfig;

	private final TGzOfferInfoService tGzOfferInfoService;
	private final TGzEmpInfoService tGzEmpInfoService;
	private final TAttaInfoService tAttaInfoService;
	private final TEmpContactInfoService tEmpContactInfoService;

	private RestTemplate restTemplate = new RestTemplate();

	@Autowired
	private OSSUtil ossUtil;

	/**
	 * @Description: 接收瓜子推送过来的取消Offer的信息
	 * @Author: hgw
	 * @Date: 2025-10-22 08:35:57
	 * @return: com.yifu.cloud.plus.v1.yifu.archives.utils.ReturnGz<java.lang.String>
	 **/
	@PostMapping("/doCancelOfferInfo")
	public ReturnGz<String> doCancelOfferInfo(@RequestBody TGzOfferInfoCancelVo vo) {

		if (Common.isEmpty(vo.getBizId())) {
			return ReturnGz.failed("BizId必传");
		}
		TGzOfferInfo nowGzOfferInfo = tGzOfferInfoService.getOne(Wrappers.<TGzOfferInfo>query().lambda()
				.eq(TGzOfferInfo::getBizId, vo.getBizId())
				.last(CommonConstants.LAST_ONE_SQL));
		if (nowGzOfferInfo == null || Common.isEmpty(nowGzOfferInfo.getId())) {
			return ReturnGz.failed("根据BizId，未找到瓜子offer信息");
		}
		Set<String> dbAuthsSet = new HashSet<>();
		Collection<? extends GrantedAuthority> authorities = AuthorityUtils
				.createAuthorityList(dbAuthsSet.toArray(new String[0]));
		YifuUser user = new YifuUser("2", 1L, "", "预入职扫码",
				"瓜子系统", "0", SecurityConstants.BCRYPT + "123456",
				"12345678911", true, true, true,
				true,
				"1", authorities, "1",
				null, null,
				null,null);
		// 10：取消offer
		nowGzOfferInfo.setOfferStatus(CommonConstants.TEN_STRING);
		// 5. 签名验证通过，处理业务逻辑
		R<String> r = tGzOfferInfoService.gzUpdateStatus(nowGzOfferInfo, user);
		if (R.isSuccess(r)) {
			return ReturnGz.ok();
		} else {
			return ReturnGz.failed(r.getMsg());
		}
	}

	/**
	 * @Description: 接收瓜子推送过来的Offer信息
	 * @Author: hgw
	 * @Date: 2025/6/23 15:27
	 * @return: com.yifu.cloud.plus.v1.yifu.archives.utils.ReturnGz<java.lang.String>
	 **/
	@PostMapping("/saveOfferInfo")
	public ReturnGz<String> saveOfferInfo(@RequestBody TGzOfferInfo gzOfferInfo
			, @RequestParam String expires, @RequestParam String signature, @RequestParam String requestId
			, @RequestParam String appkey, @RequestParam String nonce) {

		Map<String, Object> params = new HashMap<>();
		params.put("expires", expires);
		params.put("signature", signature);
		params.put("requestId", requestId);
		params.put("appkey", appkey);
		params.put("nonce", nonce);
		// 2. 计算期望的签名
		String expectedSignature = GZSign.getSignature(params, gzConfig.getAppsecret());
		// 3. 比较签名是否一致
		if (!params.get("signature").equals(expectedSignature)) {
			return ReturnGz.failed("签名验证失败");
		}
		// 5. 签名验证通过，处理业务逻辑
		return this.saveData(gzOfferInfo);
	}

	/**
	 * 处理推送的业务数据
	 *
	 * @return 处理结果
	 */
	private ReturnGz<String> saveData(TGzOfferInfo tGzOfferInfo) {
		// 这里实现你的业务逻辑
		// 例如：解析参数、保存数据、触发后续处理等
		tGzOfferInfo.setCreateBy("3");
		tGzOfferInfo.setCreateName("瓜子推送");
		tGzOfferInfo.setCreateTime(LocalDateTime.now());
		tGzOfferInfoService.save(tGzOfferInfo);
		return ReturnGz.ok();
	}

	/**
	 * @Description: 获取瓜子银行支行信息的接口
	 * @Author: hgw
	 * @Date: 2025/6/23 15:28
	 * @return: boolean
	 **/
	@GetMapping("/getGzBank")
	public boolean getGzBank(@RequestParam String pageNum, @RequestParam String pageSize
			, @RequestParam String startTime, @RequestParam String endTime) {
		Map<String, Object> params = new HashMap<>();
		params.put("pageNum", pageNum);
		params.put("pageSize", pageSize);
		params.put("startTime", startTime);
		params.put("endTime", endTime);
		params.put("appsecret", gzConfig.getAppsecret());
		params.put("tid", gzConfig.getTid());
		GZSign.addSignature(params, gzConfig.getAppkey(), gzConfig.getAppsecret());

		params.remove("startTime", startTime);
		params.remove("endTime", endTime);
		String sortedParams = GZSign.getEncodeString(params);
		sortedParams += "&startTime=" + startTime + "&endTime=" + endTime;
		return gzConfig.getGzBankInfo(restTemplate, sortedParams);
	}

	/**
	 * @Description: 1、offer状态更新接口；
	 * @Author: hgw
	 * @Date: 2025-7-11 11:11:11
	 * @return: boolean
	 **/
	@GetMapping("/updateGzOfferStatus")
	public Map<String,String> updateGzOfferStatus(@RequestParam String bizId, @RequestParam Integer status
			, @RequestParam(required = false) String phone, @RequestParam(required = false) String email
			, @RequestParam(required = false) String entryDate) {
		Map<String, Object> params = new HashMap<>();
		params.put("appsecret", gzConfig.getAppsecret());
		params.put("tid", gzConfig.getTid());
		GZSign.addSignature(params, gzConfig.getAppkey(), gzConfig.getAppsecret());
		String sortedParams = GZSign.getEncodeString(params);
		params = new HashMap<>();
		params.put("bizId", bizId);
		params.put("status", status);
		params.put("phone", phone);
		params.put("email", email);
		params.put("entryDate", entryDate);

		return gzConfig.updateGzOfferStatus(restTemplate, params);
	}

	/**
	 * @Description: 2、员工信息回推接口；
	 * @Author: hgw
	 * @Date: 2025-7-11 11:11:11
	 * @return: boolean
	 **/
	@GetMapping("/pushGzEmpInfo")
	public Map<String,String> pushGzEmpInfo(@RequestParam(required = false) String gzEmpId) {
		Map<String, Object> params = new HashMap<>();
		params.put("appsecret", gzConfig.getAppsecret());
		params.put("tid", gzConfig.getTid());
		GZSign.addSignature(params, gzConfig.getAppkey(), gzConfig.getAppsecret());
		String sortedParams = GZSign.getEncodeString(params);
		if (Common.isEmpty(gzEmpId)) {
			// 653497199507262524 李丽
			gzEmpId = "1942036120125800449";
		}
		TGzEmpInfoPushGzVo a = tGzEmpInfoService.getGzEmpInfoToPushGzById(gzEmpId);
		return gzConfig.pushGzEmpInfo(restTemplate, a);
	}
	/**
	 * @Description: 3、合同信息回推接口；
	 * @Author: hgw
	 * @Date: 2025-7-11 11:11:11
	 * @return: boolean
	 **/
	@GetMapping("/pushGzEmpContract")
	public Map<String,String> pushGzEmpContract(@RequestParam(required = false) String gzEmpId) {
		Map<String, Object> params = new HashMap<>();
		params.put("appsecret", gzConfig.getAppsecret());
		params.put("tid", gzConfig.getTid());
		GZSign.addSignature(params, gzConfig.getAppkey(), gzConfig.getAppsecret());
		String sortedParams = GZSign.getEncodeString(params);
		if (Common.isEmpty(gzEmpId)) {
			// 653497199507262524 李丽
			gzEmpId = "1942036120125800449";
		}
		TGzEmpInfoPushGzContractVo a = tGzEmpInfoService.getGzEmpInfoToPushGzByIdContract(gzEmpId);
		return gzConfig.pushGzEmpContract(restTemplate, a);
	}
	/**
	 * @Description: 4.2.3、员工文件信息上传接口
	 * @Author: hgw
	 * @Date: 2025-7-11 11:11:11
	 * @return: boolean
	 **/
	@GetMapping("/pushGzEmpInfoFile")
	public Map<String, String> pushGzEmpInfoFile(@RequestParam(required = false) String gzEmpId) {
		Map<String, Object> params = new HashMap<>();
		params.put("appsecret", gzConfig.getAppsecret());
		params.put("tid", gzConfig.getTid());
		GZSign.addSignature(params, gzConfig.getAppkey(), gzConfig.getAppsecret());
		String sortedParams = GZSign.getEncodeString(params);
		if (Common.isEmpty(gzEmpId)) {
			// 653497199507262524 李丽
			gzEmpId = "1942036120125800449";
		}
		List<TAttaInfo> aList = tAttaInfoService.getTAttaInfoListByDoMainId(gzEmpId);
		TGzEmpInfoPushGzFileVo vo;
		TGzEmpInfo tGzEmpInfo = tGzEmpInfoService.getById(gzEmpId);
		Map<String, String> returnMap = new HashMap<>();
		if (tGzEmpInfo != null && Common.isNotNull(tGzEmpInfo.getBizId())) {
			String bizId = tGzEmpInfo.getBizId();
			URL url;
			InputStream inStream = null;
			String base64String;
			for (TAttaInfo a : aList) {
				// 证件正面
				if (Common.isNotNull(a.getRelationType()) && "NID_A".equals(a.getRelationType()) && Common.isNotNull(a.getAttaSrc())) {
					url = ossUtil.getObjectUrl(null, a.getAttaSrc());
					try {
						inStream = url.openStream();
						base64String = Base64.getEncoder().encodeToString(IOUtils.toByteArray(inStream));
						vo = new TGzEmpInfoPushGzFileVo();
						vo.setBizId(bizId);
						vo.setFileName(a.getAttaName());
						// 文件数据 Base64
						vo.setFileData(base64String);
						returnMap.put(a.getId(), gzConfig.pushGzFile(restTemplate, vo));
					} catch (Exception e) {
						log.info("瓜子附件推送失败！");
					} finally {
						if (null != inStream) {
							try {
								inStream.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
					}
				}
			}
		}
		return returnMap;
	}
	/**
	 * @Description:  4.2.5、员工附件补充接口
	 * @Author: hgw
	 * @Date: 2025-7-11 11:11:11
	 * @return: boolean
	 **/
	@GetMapping("/pushGzEmpInfoAtta")
	public Map<String, String> pushGzEmpInfoAtta(@RequestParam(required = false) String gzEmpId) {
		Map<String, Object> params = new HashMap<>();
		params.put("appsecret", gzConfig.getAppsecret());
		params.put("tid", gzConfig.getTid());
		GZSign.addSignature(params, gzConfig.getAppkey(), gzConfig.getAppsecret());
		String sortedParams = GZSign.getEncodeString(params);
		if (Common.isEmpty(gzEmpId)) {
			// 653497199507262524 李丽
			gzEmpId = "1942036120125800449";
		}
		List<TAttaInfo> aList = tAttaInfoService.getTAttaInfoListByDoMainId(gzEmpId);
		TGzEmpInfoPushGzFileVo vo;
		TGzEmpInfoPushGzAttaVo attaVo;
		TGzEmpInfo tGzEmpInfo = tGzEmpInfoService.getById(gzEmpId);
		Map<String, String> returnMap = new HashMap<>();
		if (tGzEmpInfo != null && Common.isNotNull(tGzEmpInfo.getBizId())) {
			String bizId = tGzEmpInfo.getBizId();
			String fileId;
			URL url;
			InputStream inStream = null;
			String base64String;
			// 先上传附件，再推送atta与类型
			for (TAttaInfo a : aList) {
				// 获取合同附件
				if (Common.isNotNull(a.getRelationType()) && "CONTRACT".equals(a.getRelationType()) && Common.isNotNull(a.getAttaSrc())) {
					url = ossUtil.getObjectUrl(null, a.getAttaSrc());
					try {
						inStream = url.openStream();
						base64String = Base64.getEncoder().encodeToString(IOUtils.toByteArray(inStream));
						vo = new TGzEmpInfoPushGzFileVo();
						vo.setBizId(bizId);
						vo.setFileName(a.getAttaName());
						// 文件数据 Base64
						vo.setFileData(base64String);
						fileId = gzConfig.pushGzFile(restTemplate, vo);

						attaVo = new TGzEmpInfoPushGzAttaVo();
						attaVo.setBizId(bizId);
						attaVo.setFileId(fileId);
						attaVo.setAttachType(a.getRelationType());
						attaVo.setFileName(a.getAttaName());

						gzConfig.pushGzAttach(restTemplate, attaVo);

						//returnMap.put(a.getId(), gzConfig.pushGzAttach(restTemplate, attaVo));
					} catch (Exception e) {
						log.info("瓜子附件推送失败！");
					} finally {
						if (null != inStream) {
							try {
								inStream.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
					}
				}
			}
		}
		return returnMap;
	}


}
