package com.yifu.cloud.plus.v1.yifu.order.util;

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.ekp.util.EkpOrderUtil;
import com.yifu.cloud.plus.v1.yifu.order.constants.OrderConstants;
import com.yifu.cloud.plus.v1.yifu.order.entity.TOrderFileSyncLog;
import com.yifu.cloud.plus.v1.yifu.order.mapper.TOrderFileSyncLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * @Author fxj
 * @Date 2023/6/25
 * @Description
 * @Version 1.0
 */
@Slf4j
@Component
public class EkpOrderFileAsyncTask {
	@Resource
	private EkpOrderUtil ekpOrderUtil;

	@Resource
	private TOrderFileSyncLogMapper orderFileSyncLogMapper;

	/**
	 * @Author fxj
	 * @Description 同步项目订单附件 （EKP=>HRO）
	 * @Date 15:59 2024/11/15
	 * @Param
	 * @return
	 **/
	@Async
	public R<String> syncFileFromEkp(String orderNo, String attIds, String id) {
		if (StringUtils.isEmpty(orderNo)){
			return R.failed(OrderConstants.ORDER_NO_IS_EMPTY);
		}
		if (StringUtils.isEmpty(attIds)){
			return R.failed(OrderConstants.ENCLOSURE_ID_IS_EMPTY);
		}
		String res  = ekpOrderUtil.syncFileFromEkp(orderNo,attIds);
		if (!Common.isNotNull(res)){
			// 记录到数据库 失败的部分可在前端列表重试
			this.saveFileSyncLog(orderNo,attIds,null,id);
		}else {
			// 记录到数据库 失败的部分可在前端列表重试
			this.saveFileSyncLog(orderNo,attIds,res,id);
		}
		return R.ok(OrderConstants.OPERATE_SUCCESS);
	}

	/**
	 * @Author fxj
	 * @Description 记录及更新附件同步信息
	 * @Date 17:45 2024/11/15
	 * @Param
	 * @return
	 **/
	private  void saveFileSyncLog(String orderNo,String attIds,String msg,String id){
		TOrderFileSyncLog log = new TOrderFileSyncLog();
		if (Common.isNotNull(id)){
			log.setId(id);
			if (Common.isEmpty(msg)){
				log.setReason(CommonConstants.EMPTY_STRING);
				log.setFlag(CommonConstants.ZERO_STRING);
			}else {
				log.setReason(msg);
			}
			log.setUpdateTime(LocalDateTime.now());
			orderFileSyncLogMapper.updateById(log);
		}else {
			log.setOrderNo(orderNo);
			log.setAttIds(attIds);
			log.setCreateTime(LocalDateTime.now());
			log.setReason(msg);
			log.setFlag(CommonConstants.ONE_STRING);
			orderFileSyncLogMapper.insert(log);
		}


	}
}
