package com.yifu.cloud.plus.v1.yifu.insurances.service.insurance.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.equator.HrEquator;
import com.yifu.cloud.plus.v1.yifu.insurances.entity.TBusinessOperate;
import com.yifu.cloud.plus.v1.yifu.insurances.mapper.insurances.TBusinessOperateMapper;
import com.yifu.cloud.plus.v1.yifu.insurances.service.insurance.TBusinessOperateService;
import org.springframework.stereotype.Service;

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

import static com.alibaba.fastjson.serializer.SerializerFeature.*;

/**
 * @author licancan
 * @description 针对表【t_business_operate(业务操作记录表)】的数据库操作Service实现
 * @date 2022-12-08 10:20:16
 */
@Service
public class TBusinessOperateServiceImpl extends ServiceImpl<TBusinessOperateMapper, TBusinessOperate> implements TBusinessOperateService {

	/**
	 * 保存修改记录
	 *
	 * @param businessId 业务表主键
	 * @param oldInfo    老的实体类
	 * @param newInfo    新的实体类
	 * @param remark 备注
	 * @return {@link TBusinessOperate}
	 * @author licancan
	 */
	@Override
	public <T> TBusinessOperate saveModificationRecord(String businessId, T oldInfo, T newInfo, String remark) {
		try{
			//比较记录不影响业务逻辑，用try套住
			//比较差异
			String differenceKey = HrEquator.comparisonValue(oldInfo, newInfo);
			//如果有差异保存差异
			if(!Common.isEmpty(differenceKey)){
				TBusinessOperate operate = new TBusinessOperate();
				operate.setBusinessId(businessId);
				operate.setCreateTime(LocalDateTime.now());
				operate.setOldInfo(JSON.toJSONString(oldInfo,features));
				operate.setNewInfo(JSON.toJSONString(newInfo,features));
				operate.setDifferenceInfo(differenceKey);
				operate.setRemark(remark);
				baseMapper.insert(operate);
				return operate;
			}
		}catch (Exception e){
			log.error(JSON.toJSON(oldInfo)+"插入修改记录报错>>>",e);
		}
		return null;
	}

	/**
	 * 根据业务主键获取操作记录
	 *
	 * @param businessId
	 * @return {@link List <TBusinessOperate>}
	 * @author licancan
	 */
	@Override
	public List<TBusinessOperate> getOperateListByBusinessId(String businessId) {
		List<TBusinessOperate> list = this.baseMapper.selectList(Wrappers.<TBusinessOperate>query().lambda()
				.eq(TBusinessOperate::getBusinessId,businessId));
		return list;
	}

	private SerializerFeature[] features = new SerializerFeature[] {
			WriteMapNullValue, WriteNullNumberAsZero, WriteNullListAsEmpty,
			WriteNullStringAsEmpty,WriteDateUseDateFormat
	};
}




