/*
 *    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.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TGzPushEntry;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TGzPushEntryMapper;
import com.yifu.cloud.plus.v1.yifu.archives.service.TGzPushEntryService;
import com.yifu.cloud.plus.v1.yifu.archives.utils.DoJointTask;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TGzPushEntrySearchVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 瓜子系统交互任务跟进表
 *
 * @author cyx
 * @date 2025-07-09 17:03:50
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class TGzPushEntryServiceImpl extends ServiceImpl<TGzPushEntryMapper, TGzPushEntry> implements TGzPushEntryService {

	@Autowired
	@Lazy
	private DoJointTask doJointTask;

	// 任务类型是改状态的: 4：待接受Offer，5：拒绝Offer，6：接受offer，9：候选人填写信息，10：取消offer，12：候选人信息审核，13：待签署
	private final String[] taskTypeArr = {"4", "5", "6", "9", "10", "12", "13", "97", "8", "99"};

	/**
	 * 瓜子系统交互任务跟进表简单分页查询
	 *
	 * @param tGzPushEntry 瓜子系统交互任务跟进表
	 * @return
	 */
	@Override
	public IPage<TGzPushEntrySearchVo> getTGzPushEntryPage(Page<TGzPushEntry> page, TGzPushEntrySearchVo tGzPushEntry) {
		return baseMapper.getTGzPushEntryPage(page, tGzPushEntry);
	}

	// 取消offer，同步取消任务
	@Override
	public String getTGzPushEntryListForStatus(String bizId) {
		List<String> taskInfoList = baseMapper.getTGzPushEntryListForStatus(bizId);
		StringBuilder taskTypeName = new StringBuilder();
		if (taskInfoList != null && !taskInfoList.isEmpty()) {
			Map<String, String> taskTypeNameMap = new HashMap<>();
			taskTypeNameMap.put("4", "待接受Offer");
			taskTypeNameMap.put("5", "拒绝Offer");
			taskTypeNameMap.put("6", "接受offer");
			taskTypeNameMap.put("8", "合同信息推送");
			taskTypeNameMap.put("9", "候选人填写信息");
			taskTypeNameMap.put("10", "取消offer");
			taskTypeNameMap.put("12", "候选人信息审核");
			taskTypeNameMap.put("13", "待签署");
			taskTypeNameMap.put("97", "档案信息推送");
			taskTypeNameMap.put("99", "合同附件推送");
			// 交互任务类型（4：待接受Offer，5：拒绝Offer，6：接受offer，
			// 8：合同信息推送，9：候选人填写信息，10：取消offer，12：候选人信息审核，13：待签署，
			// 97：档案信息推送，99：合同附件推送）
			String info;
			for (String taskInfo : taskInfoList) {
				info = taskTypeNameMap.get(taskInfo);
				if (info != null) {
					taskTypeName.append(info).append("、");
				} else {
					taskTypeName.append(taskInfo).append("、");
				}
			}
			if (taskTypeName.length() > 0) {
				taskTypeName.deleteCharAt(taskTypeName.length() - 1);
			}
			// 同步取消任务，非已完成的都取消 2025-10-21 18:20:06 倩倩同意
			baseMapper.deleteByBizId(bizId);
		}
		if (taskTypeName.length() > 0) {
			return "任务取消：" + taskTypeName + "；";
		} else {
			return null;
		}
	}

	/**
	 * 任务推送重试
	 *
	 * @param tGzPushEntry 瓜子系统交互任务跟进表
	 * @return R
	 */
	@Override
	public R<String> retryPushEntry(TGzPushEntry tGzPushEntry) {
		YifuUser user = SecurityUtils.getUser();
		if (user == null || Common.isEmpty(user.getId())) {
			return R.failed(CommonConstants.PLEASE_LOG_IN);
		}
		if (Common.isEmpty(tGzPushEntry.getId())) {
			return R.failed(CommonConstants.PARAM_IS_NOT_EMPTY);
		}
		// 获取推送失败的数据信息
		TGzPushEntry findInfo = this.getOne(Wrappers.<TGzPushEntry>query().lambda()
				.eq(TGzPushEntry::getId, tGzPushEntry.getId())
				.eq(TGzPushEntry::getPushStatus, CommonConstants.ONE_STRING)
				.eq(TGzPushEntry::getDelFlag, CommonConstants.ZERO_STRING)
				.last(CommonConstants.LAST_ONE_SQL));
		if (Common.isEmpty(findInfo)) {
			return R.failed(CommonConstants.ERROR_NO_DOMAIN);
		}

		// 先改为推送中
		findInfo.setPushTime(LocalDateTime.now());
		findInfo.setPushStatus(CommonConstants.THREE_STRING);
		findInfo.setFailReason("");
		findInfo.setUpdateBy(user.getId());
		findInfo.setUpdateTime(LocalDateTime.now());
		this.updateById(tGzPushEntry);

		// 改为异步处理
		doJointTask.handleGzPushEntry(findInfo);

		return R.ok("已发起重新推送，正在后台推送中...稍后请刷新页面查看结果");
	}

	/**
	 * 新增推送任务
	 *
	 * @param tGzPushEntry 瓜子系统交互任务跟进表
	 */
	@Override
	public void addPushEntry(TGzPushEntry tGzPushEntry) {
		// 流程是0的，不推送
		if(CommonConstants.ZERO_STRING.equals(tGzPushEntry.getBizId())){
			return;
		}

		// 仅存指定状态的任务
		if (!ArrayUtils.contains(taskTypeArr, tGzPushEntry.getTaskType())) {
			return;
		}

		// offer状态是 7 的，改为推送 6
		if(CommonConstants.SEVEN_STRING.equals(tGzPushEntry.getTaskType())){
			tGzPushEntry.setTaskType(CommonConstants.SIX_STRING);
		}
		// 新建任务，先存为"待推送"
		tGzPushEntry.setPushStatus(CommonConstants.TWO_STRING);
		tGzPushEntry.setCreateTime(LocalDateTime.now());
		tGzPushEntry.setDelFlag(CommonConstants.NOT_DELETE_FLAG);
		this.save(tGzPushEntry);

		// 除了本次任务，获取是否有【推送失败、待推送、推送中】的任务，有的话本次不推送，存为“待推送”就结束
		TGzPushEntry findBizFailInfo = this.getOne(Wrappers.<TGzPushEntry>query().lambda()
				.eq(TGzPushEntry::getBizId, tGzPushEntry.getBizId())
				.ne(TGzPushEntry::getId, tGzPushEntry.getId())
				.in(TGzPushEntry::getPushStatus, CommonConstants.ONE_STRING, CommonConstants.TWO_STRING, CommonConstants.THREE_STRING)
				.eq(TGzPushEntry::getDelFlag, CommonConstants.ZERO_STRING)
				.last(CommonConstants.LAST_ONE_SQL));
		if (Common.isNotNull(findBizFailInfo)) {
			return;
		}

		tGzPushEntry.setUpdateBy(tGzPushEntry.getCreateBy());
		// 改为异步处理
		doJointTask.handleGzPushEntry(tGzPushEntry);
	}

}
