	package com.yeejoin.amos.boot.module.common.biz.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yeejoin.amos.boot.biz.common.dao.mapper.DataDictionaryMapper;
import com.yeejoin.amos.boot.module.common.api.dto.DutyPersonShiftDto;
import com.yeejoin.amos.boot.module.common.api.entity.*;
import com.yeejoin.amos.boot.module.common.api.mapper.OrgUsrMapper;
import com.yeejoin.amos.boot.module.common.biz.enums.ActionStatus;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.module.common.api.dto.DutyCarDto;
import com.yeejoin.amos.boot.module.common.api.feign.EquipFeignClient;
import com.yeejoin.amos.boot.module.common.api.mapper.DutyPersonShiftMapper;
import com.yeejoin.amos.boot.module.common.api.mapper.FirefightersMapper;
import com.yeejoin.amos.boot.module.common.api.service.IDutyCarService;

/**
 * @author DELL
 */
@Service
public class DutyCarServiceImpl extends DutyCommonServiceImpl implements IDutyCarService {

	@Autowired
	DynamicFormInstanceServiceImpl dynamicFormInstanceService;

	@Autowired
	FirefightersMapper firefightersMapper;

	@Autowired
	EquipFeignClient equipFeignClient;

	String driverPostTypeCode = "5";

	@Autowired
	EquipFeignClient equipFeign;

	@Autowired
	DutyPersonShiftMapper dutyPersonShiftMapper;

	@Autowired
	DataDictionaryMapper dataDictionaryMapper;

	@Autowired
	OrgUsrMapper orgUsrMapper;

	@Override
	public String getGroupCode() {
		return "dutyCar";
	}

	@Override
	public DutyCarDto save(DutyCarDto dutyCarDto) {
		// BUG 2807 更新人员车辆排版值班的保存逻辑 如果没有填写数据则保存空数据 。 同步修改 查询 导出相关逻辑 by kongfm 2021-09-14
		// 1.保存行数据
		if (StringUtils.isNotEmpty(dutyCarDto.getDutyAreaId())) {
			// 根据建筑id 查找建筑
			ResponseModel<Map<String, Object>> response = null;
			try {
				response = equipFeign.getFormInstanceById(Long.parseLong(dutyCarDto.getDutyAreaId()));
			} catch (NumberFormatException e) {
				throw new BadRequest("值班区域id异常！");
			}
			Map<String, Object> result = response.getResult();
			dutyCarDto.setDutyArea(result.get("name").toString());
		}
		Map<String, Object> map = Bean.BeantoMap(dutyCarDto);

		// 修改操作动态表单的方法，修改人陈浩 -------------start 2021-09-28
		Long instanceId = excuteDynamicFormInstance(dutyCarDto.getUserId(), map, this.getGroupCode());
		saveDutyPersonShiftDetail(instanceId, dutyCarDto.getDutyShift(), dutyCarDto.getStartTime());
		TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
			  @Override
			  public void afterCommit() {
				  insertPersonShift(instanceId, dutyCarDto.getDutyShift(), ActionStatus.METHOD_ADD.getCode());
			  }
		  });
		// 修改操作动态表单的方法，修改人陈浩 -------------end 2021-09-28
		// 生成变更日志
		createDutyPersonShiftLog(dutyCarDto, false, ActionStatus.METHOD_ADD.getCode());
		// 3.返回保存后的数据
		return dutyCarDto;

	}

	@Override
	public DutyCarDto update(Long instanceId, DutyCarDto dutyCarDto) {
		// 修改操作动态表单修改的逻辑方法，陈浩 start ----2021-09-28
		updateDynamicFormInstance(this.getGroupCode(), instanceId, Bean.BeantoMap(dutyCarDto));
		// 修改操作动态表单修改的逻辑方法，陈浩 end ----2021-09-28
		// 5.更新值班信息人日期数据
		insertPersonShift(instanceId, dutyCarDto.getDutyShift(), ActionStatus.METHOD_UPDATE.getCode());
		// 生成变更日志
		createDutyPersonShiftLog(dutyCarDto, false, ActionStatus.METHOD_UPDATE.getCode());
		return dutyCarDto;
	}

	public void insertPersonShift(Long instanceId, List<DutyPersonShiftDto> dutyShiftList, String type) {
        //1.查询已有数据
        List<DynamicFormInstance> instances = dynamicFormInstanceService.list(new LambdaQueryWrapper<DynamicFormInstance>().eq(DynamicFormInstance::getInstanceId, instanceId));
        Map<Object, DynamicFormInstance> instanceMap = Bean.listToMap(instances, "fieldCode", DynamicFormInstance.class);
		dutyPersonService.dataCheck(dutyShiftList,instanceId,type);
		Set<DutyPersonShift> personShiftList = dutyShiftList.stream().map(dto -> {
			// 根据instanceId 和 日期查找 如果有则更新
			DutyPersonShift dutyPersonShift = dutyPersonShiftService.getOne(new LambdaQueryWrapper<DutyPersonShift>().eq(DutyPersonShift::getInstanceId,instanceId).eq(DutyPersonShift::getDutyDate,dto.getDutyDate()));
			if(dutyPersonShift == null) {
				dutyPersonShift = new DutyPersonShift();
			}
			dto.setInstanceId(instanceId);
			Bean.copyExistPropertis(dto, dutyPersonShift);
			dutyPersonShift.setAppKey(RequestContext.getAppKey());
			return dutyPersonShift;
		}).collect(Collectors.toSet());
		if (!personShiftList.isEmpty()) {
			dutyPersonShiftService.saveOrUpdateBatch(personShiftList);
		}
	}

	@Override
	public Object getDutyPersonShiftLogData(String dutyDay, String fieldCode){
		List<Map<String, Object>> equipmentList = dutyPersonShiftMapper.getEquipmentForSpecifyDate(dutyDay,
				this.getGroupCode(), "carId", "carName", "teamName", "result.carId");
		if (equipmentList == null || equipmentList.isEmpty() || equipmentList.get(0) == null) {
			return null;
		}
		List<Object> detailList = new ArrayList<>();
		for (Map<String, Object> map : equipmentList) {
			List<Map<String, Object>> resultList = new ArrayList<>();
			LinkedHashMap<String, Object> titleMap_1 = new LinkedHashMap<>();
			if (map.containsKey("carName") && map.get("carName") != null) {
				titleMap_1.put("消防车辆", map.get("carName").toString());
			}
			resultList.add(titleMap_1);
			LinkedHashMap<String, Object> titleMap_2 = new LinkedHashMap<>();
			if (map.containsKey("teamName") && map.get("teamName") != null) {
				titleMap_2.put("单位/部门", map.get("teamName").toString());
			}
			resultList.add(titleMap_2);
			String carId = map.get("carId").toString();
			Map<String, Object> instanceMap = dutyPersonShiftMapper.getInstanceIdForSpecifyDateAndEquipment(
					dutyDay, this.getGroupCode(), carId
			);
			if (instanceMap == null) {
				continue;
			}
			String instanceId = instanceMap.get("instanceIds").toString();
			if (StringUtils.isNotBlank(instanceId)) {
				String[] instanceIds = instanceId.split(",");

				List<Map<String, Object>> specifyDateList = dutyPersonShiftMapper.getPositionStaffDutyForSpecifyDate(
						dutyDay, this.getGroupCode(), instanceIds, null, fieldCode
				);

				if (!specifyDateList.isEmpty()) {
					for (Map<String, Object> specify : specifyDateList) {
						LinkedHashMap<String, Object> infoMap_2 = new LinkedHashMap<>();
						if (specify.containsKey("postTypeName") && specify.get("postTypeName") != null && specify.containsKey("userName") && specify.get("userName") != null) {
							infoMap_2.put(specify.get("postTypeName").toString(), specify.get("userName").toString());
							resultList.add(infoMap_2);
						}
					}
				}
			}
			detailList.add(resultList);
		}
		return detailList;
	}

	private void buildFormInstanceData(Long instanceId, Map<String, Object> map, DynamicFormColumn column,
			DynamicFormInstance formInstance) {
		fillFormInstanceData(instanceId, map, column, formInstance, sequence.nextId());
	}

	@Override
	public JSONObject isFireCarDriver() {
		JSONObject result = new JSONObject();
		result.put("isDriver", false);
		result.put("carStatus", "");
		result.put("carId", "");

		String loginUserId = RequestContext.getExeUserId();
		// 根据登陆人id查询对应消防人员
		Firefighters firefighters = firefightersMapper
				.selectOne(new LambdaQueryWrapper<Firefighters>().eq(Firefighters::getSystemAccount, loginUserId));
		if (ValidationUtil.isEmpty(firefighters)) {
			return result;
		}
		// 消防人员id
		Long fighterId = firefighters.getSequenceNbr();

		// 当前值班班次id
		List<Long> shiftIdList = getDutyShiftIdList();
		if (ValidationUtil.isEmpty(shiftIdList)) {
			return result;
		}
		// 当前值班人员-车辆信息
		List<Map<String, Object>> personList = dayDutyPersonList(DateUtils.getDateNowShortStr(), shiftIdList.get(0),
				driverPostTypeCode);
		if (ValidationUtil.isEmpty(personList)) {
			return result;
		}

		personList = personList.stream().filter(m -> fighterId.equals(m.get("userId"))).collect(Collectors.toList());
		if (ValidationUtil.isEmpty(personList)) {
			return result;
		}

		result.put("isDriver", true);
		result.put("carId", personList.get(0).get("carId"));

		ResponseModel<Map<String, Object>> resultModel = equipFeignClient
				.queryCarSimpleInfoById((Long) personList.get(0).get("carId"));
		Map<String, Object> carInfo = resultModel.getResult();
		result.put("carStatus", carInfo.get("carStatus"));
		return result;
	}

	public Object getSchedulingDutyForSpecifyDate(String dutyDay, Long shiftId, String postType, String fieldCode) {
		List<List<Map<String, String>>> result = new ArrayList<>();
		List<Map<String, String>> dutyCarLogs = dutyPersonShiftLogMapper.selectSpecificDateLogForCar(dutyDay);
		// 按照车辆分组
		dutyCarLogs = dutyCarLogs.stream().filter(v -> Objects.nonNull(v.get("carName"))).collect(Collectors.toList());
		Map<String, List<Map<String, String>>> dutyCarLogGroups = dutyCarLogs.stream().collect(Collectors.groupingBy(v -> v.get("carName")));
		// 按照车辆排序
		// 1. 获取排序 BizOrgName: 部门名称，OrgExpandAttr1: 排序字段
		List<OrgUsr> orgUserSortRules = orgUsrMapper.selectList(
				Wrappers.<OrgUsr>lambdaQuery()
						.select(OrgUsr::getBizOrgName, OrgUsr::getOrgExpandAttr1)
						.isNotNull(OrgUsr::getOrgExpandAttr1)
						.ne(OrgUsr::getOrgExpandAttr1, "")
		);
		// 2. dutyCarLogGroups.keySet() 为车辆名称，根据车辆名称获取部门值班列表。获取车辆下第一个部门，按照此部门对dutyCarLogGroups进行排序，排序后的结果保存到一个有序的LinkedHashMap中.
		// sortNum为数字类型，数字越小越靠前 | 车辆对应的部门列表可能为空，注意判空，无法排序的车辆放到最后
		Map<String, List<Map<String, String>>> sortedDutyCarLogGroups = new LinkedHashMap<>();
		Map<String, Integer> dutyCarSortNumMap = new HashMap<>();
		for (String carName : dutyCarLogGroups.keySet()) {
			List<Map<String, String>> dutyCarLogGroup = dutyCarLogGroups.get(carName);
			Map<String, String> team = dutyCarLogGroup.get(0);
			if (Objects.isNull(team)) {
				continue;
			}
			String teamName = team.get("teamName");
			// 根据teamName从orgUserSortRules中获取排序号
			Optional<OrgUsr> orgUsrOptional = orgUserSortRules.stream().filter(v -> Objects.equals(v.getBizOrgName(), teamName)).findFirst();
			if (orgUsrOptional.isPresent()) {
				OrgUsr orgUsr = orgUsrOptional.get();
				String sortNum = orgUsr.getOrgExpandAttr1();
				dutyCarSortNumMap.put(carName, Integer.parseInt(sortNum));
			}
		}
		// 根据dutyCarSortNumMap对dutyCarLogGroups进行排序
		List<Map.Entry<String, List<Map<String, String>>>> dutyCarLogGroupEntries = new ArrayList<>(dutyCarLogGroups.entrySet());
		dutyCarLogGroupEntries.sort((o1, o2) -> {
			Integer sortNum1 = dutyCarSortNumMap.getOrDefault(o1.getKey(), Integer.MAX_VALUE);
			Integer sortNum2 = dutyCarSortNumMap.getOrDefault(o2.getKey(), Integer.MAX_VALUE);
			return sortNum1.compareTo(sortNum2);
		});
		for (Map.Entry<String, List<Map<String, String>>> entry : dutyCarLogGroupEntries) {
			sortedDutyCarLogGroups.put(entry.getKey(), entry.getValue());
		}
		// 3. 根据排序后的sortedDutyCarLogGroups生成返回结果
		Set<Map.Entry<String, List<Map<String, String>>>> entries = sortedDutyCarLogGroups.entrySet();
		for (Map.Entry<String, List<Map<String, String>>> entry : entries) {
			String key = entry.getKey();
			List<Map<String, String>> value = entry.getValue();

			List<Map<String, String>> list = new ArrayList<>();
			Map<String, String> item1 = new HashMap<String, String>() {{
				this.put("消防车辆", key);
			}};
			list.add(item1);
			Map<String, String> item2 = new HashMap<String, String>() {{
				this.put("单位/部门", value.get(0).getOrDefault("teamName", ""));
			}};
			list.add(item2);

			// value 是一个部门的值班列表，按照postTypeName的字符串排序
			List<Map<String, String>> posts = new LinkedList<>();
			for (Map<String, String> val : value) {
				Map<String, String> itemN = new HashMap<String, String>() {{
					this.put(val.getOrDefault("postTypeName", ""), val.getOrDefault("dutyUsers", ""));
				}};
				posts.add(itemN);
			}
			posts.sort((o1, o2) -> {
				String postTypeName1 = o1.keySet().iterator().next();
				String postTypeName2 = o2.keySet().iterator().next();
				return postTypeName1.compareTo(postTypeName2);
			});
			list.addAll(posts);
			result.add(list);
		}
		return result.isEmpty() ? this.getDutyPersonShiftLogData(dutyDay, fieldCode) : result;
	}

    @Override
	public int getDutyCarCount(Long carId) {
		List<Map<String, Object>> equipmentList = dutyPersonShiftMapper.getEquipmentForSpecifyDate(DateUtils.getDateNowShortStr(),
				this.getGroupCode(), "carId", "carName", "teamName","");
		int count =0;
		for (Map<String, Object> map : equipmentList) {
			if(map.containsKey("carId") && map.get("carId").equals(Long.toString(carId))) {
				count++;
			}
		}
		return count;
	}

	@Override
	public List<Map<String, Object>> getDutyCaruser(Long carId) {
		List<Map<String, Object>> equipmentList = dutyPersonShiftMapper.getEquipmentForSpecifyDate(DateUtils.getDateNowShortStr(),
				this.getGroupCode(), "carId", "carName", "teamName","");

		equipmentList = equipmentList.stream().filter((e) ->
				e.containsKey("carId") && e.get("carId").equals(Long.toString(carId))
		).collect(Collectors.toList());

		return equipmentList;
	}

	@Override
	public List<Map<String, Object>> theCarDutyPerson(Long carId) {
		List<Map<String, Object>> specifyDateList =null;
		  String dutyDay = DateUtils.getDateNowShortStr();
		  Map<String, Object> instanceMap = dutyPersonShiftMapper.getInstanceIdForSpecifyDateAndEquipment(dutyDay,
					this.getGroupCode(), carId.toString());
			if(instanceMap==null) {
				return null;
			}
			String instanceId = instanceMap.get("instanceIds").toString();
			if (StringUtils.isNotBlank(instanceId)) {
				String[] instanceIds = instanceId.split(",");
				 specifyDateList = dutyPersonShiftMapper.getPositionStaffDutyForSpecifyDate(dutyDay,
						this.getGroupCode(), instanceIds,null, null);
			}
		return specifyDateList;
	}
	@Override
	public List<Map<String, String>> getDutyCar() {

		List<Map<String, String>> instanceMap = dutyPersonShiftMapper.getDutyCar();

		return instanceMap;
	}

	@Override
	public void writeHistoryDutyLog() {
		List<Map<String, Object>> list;
		try {
			list = this.list(null, "1980-01-01", "9999-12-12");
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}
		for (Map<String, Object> map : list) {
			DutyCarDto dutyCarDto = (DutyCarDto) Bean.mapToBean(map, DutyCarDto.class);
			this.createDutyPersonShiftLog(dutyCarDto, true, null);
		}
	}

	public Map<String, List<DutyPersonShiftLog>> getDownloadData(String beginDate, String endDate) throws ParseException {
		Map<String, List<DutyPersonShiftLog>> resultSortedMap = new LinkedHashMap<>();
		List<DutyPersonShiftLog> dutyCarLogs = dutyPersonShiftLogMapper.selectList(
				Wrappers.<DutyPersonShiftLog>lambdaQuery()
						.ge(DutyPersonShiftLog::getDutyDate, beginDate)
						.le(DutyPersonShiftLog::getDutyDate, endDate)
						.eq(DutyPersonShiftLog::getGroupCode, "dutyCar")
						.eq(DutyPersonShiftLog::getIsDelete, false)
		);
		Map<String, List<DutyPersonShiftLog>> unsortedMap = dutyCarLogs.stream()
				.filter(v -> Objects.nonNull(v.getCarName()))
				.collect(Collectors.groupingBy(DutyPersonShiftLog::getCarName));
		// 获取排序 BizOrgName: 部门名称，OrgExpandAttr1: 排序字段
		List<OrgUsr> orgUserSortRules = orgUsrMapper.selectList(
				Wrappers.<OrgUsr>lambdaQuery()
						.select(OrgUsr::getBizOrgName, OrgUsr::getOrgExpandAttr1)
						.isNotNull(OrgUsr::getOrgExpandAttr1)
						.ne(OrgUsr::getOrgExpandAttr1, "")
		).stream().sorted(Comparator.comparing(v -> Integer.parseInt(v.getOrgExpandAttr1()))).collect(Collectors.toList());
		// map的key为车辆名称，根据车辆名称获取部门值班列表。获取车辆下第一个部门，按照此部门对map进行排序，排序后的结果保存到一个有序的LinkedHashMap中.
		// sortNum为数字类型，数字越小越靠前 | 车辆对应的部门列表可能为空，注意判空，无法排序的车辆放到最后
		Map<String, List<DutyPersonShiftLog>> sortedMap = new LinkedHashMap<>();
		Map<String, Integer> dutyCarSortNumMap = new HashMap<>();
		for (String carName : unsortedMap.keySet()) {
			List<DutyPersonShiftLog> dutyCarLogGroup = unsortedMap.get(carName);
			DutyPersonShiftLog dutyPersonShiftLog = dutyCarLogGroup.get(0);
			if (Objects.isNull(dutyPersonShiftLog)) {
				continue;
			}
			String teamName = dutyPersonShiftLog.getDeptName();
			// 根据teamName从orgUserSortRules中获取排序号
			Optional<OrgUsr> orgUsrOptional = orgUserSortRules.stream().filter(v -> Objects.equals(v.getBizOrgName(), teamName)).findFirst();
			if (orgUsrOptional.isPresent()) {
				OrgUsr orgUsr = orgUsrOptional.get();
				String sortNum = orgUsr.getOrgExpandAttr1();
				dutyCarSortNumMap.put(carName, Integer.parseInt(sortNum));
			}
		}
		// 根据dutyCarSortNumMap对map进行排序
		List<Map.Entry<String, List<DutyPersonShiftLog>>> dutyCarLogGroupEntries = new ArrayList<>(unsortedMap.entrySet());
		dutyCarLogGroupEntries.sort((o1, o2) -> {
			Integer sortNum1 = dutyCarSortNumMap.getOrDefault(o1.getKey(), Integer.MAX_VALUE);
			Integer sortNum2 = dutyCarSortNumMap.getOrDefault(o2.getKey(), Integer.MAX_VALUE);
			return sortNum1.compareTo(sortNum2);
		});
		for (Map.Entry<String, List<DutyPersonShiftLog>> entry : dutyCarLogGroupEntries) {
			sortedMap.put(entry.getKey(), entry.getValue());
		}
		// 根据排序后的sortedMap生成返回结果
		Set<Map.Entry<String, List<DutyPersonShiftLog>>> entries = sortedMap.entrySet();
		for (Map.Entry<String, List<DutyPersonShiftLog>> entry : entries) {
			String key = entry.getKey();
			List<DutyPersonShiftLog> value = entry.getValue();
			resultSortedMap.put(key, value);
		}
		return resultSortedMap;
	}

	@SuppressWarnings("Duplicates")
	public synchronized void createDutyPersonShiftLog(DutyCarDto dutyCarDto, boolean isInit, String actionCode) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		List<DutyPersonShiftDto> dutyPersonShift = dutyCarDto.getDutyShift();
		final String groupCode = "dutyCar";

		// 更新排班时处理
		if (!isInit && Objects.equals(actionCode, "update")) {
			TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
				@Override
				public void afterCommit() {
					if (Objects.nonNull(dutyPersonShift) && !dutyPersonShift.isEmpty()) {
						String month = dateFormat.format(dutyPersonShift.get(0).getDutyDate()).substring(0, 7);
						String startDate = month + "-01";
						String endDate = DateUtils.getLastDayOfMonth(month);
						String today = dateFormat.format(new Date());
						try {
							startDate = isAfterToday(dateFormat.parse(startDate)) ? startDate : today;
						} catch (ParseException e) {
							throw new RuntimeException(e);
						}
						dutyPersonShiftLogMapper.delete(
								Wrappers.<DutyPersonShiftLog>lambdaQuery()
										.eq(DutyPersonShiftLog::getGroupCode, groupCode)
										.eq(DutyPersonShiftLog::getDutyUserId, dutyCarDto.getUserId())
										.ge(DutyPersonShiftLog::getDutyDate, startDate)
										.le(DutyPersonShiftLog::getDutyDate, endDate)
										.eq(DutyPersonShiftLog::getIsDelete, false)
						);
					}
				}
			});
		}

		TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
			@Override
			public void afterCommit() {
				Set<String> dutyDates = dutyPersonShift.stream().map(v -> dateFormat.format(v.getDutyDate())).collect(Collectors.toSet());
				if (dutyDates.isEmpty()) {
					return;
				}
				Map<Date, List<DutyPersonShiftLog>> dutyLogGroups = dutyPersonShiftLogMapper.selectList(
						Wrappers.<DutyPersonShiftLog>lambdaQuery()
								.in(DutyPersonShiftLog::getDutyDate, dutyDates)
								.eq(DutyPersonShiftLog::getGroupCode, groupCode)
								.eq(DutyPersonShiftLog::getDutyUserId, dutyCarDto.getUserId())
								.eq(DutyPersonShiftLog::getIsDelete, false)
				).stream().collect(Collectors.groupingBy(DutyPersonShiftLog::getDutyDate));

				for (DutyPersonShiftDto dutyPersonShiftDto : dutyPersonShift) {
					// 非初始化非历史数据禁止修改
					if (!isAfterToday(dutyPersonShiftDto.getDutyDate()) && !isInit) {
						continue;
					}
					List<DutyPersonShiftLog> dutyPersonShiftLogs = dutyLogGroups.get(dutyPersonShiftDto.getDutyDate());
					DutyPersonShiftLog dutyPersonShiftLog = Objects.nonNull(dutyPersonShiftLogs) && !dutyPersonShiftLogs.isEmpty() ? dutyPersonShiftLogs.get(0) : null;

					// 日志不存在：新建
					if (Objects.isNull(dutyPersonShiftLog)) {
						dutyPersonShiftLog = new DutyPersonShiftLog();
						dutyPersonShiftLog.setInstanceId(dutyPersonShiftDto.getInstanceId());
						dutyPersonShiftLog.setDutyDate(dutyPersonShiftDto.getDutyDate());
						dutyPersonShiftLog.setGroupCode(groupCode);
						dutyPersonShiftLog.setDeptName(dutyCarDto.getTeamName());
						dutyPersonShiftLog.setDutyUserId(dutyCarDto.getUserId());
						dutyPersonShiftLog.setDutyUser(dutyCarDto.getUserName());
						dutyPersonShiftLog.setPostTypeName(dutyCarDto.getPostTypeName());
						dutyPersonShiftLog.setDutyArea(dutyCarDto.getDutyArea());
						dutyPersonShiftLog.setCarName(dutyCarDto.getCarName());
						String shiftName = dutyPersonShiftDto.getShiftName();
						if (StringUtils.isBlank(shiftName) && Objects.nonNull(dutyPersonShiftDto.getShiftId())) {
							DutyShift dutyShift = dutyShiftService.getById(dutyPersonShiftDto.getShiftId());
							dutyPersonShiftDto.setShiftName(dutyShift.getName());
						}
						dutyPersonShiftLog.setShiftName(dutyPersonShiftDto.getShiftName());
						dutyPersonShiftLogMapper.insert(dutyPersonShiftLog);
						continue;
					}
					// 日志存在：更新
					if (isAfterToday(dutyPersonShiftDto.getDutyDate())) {
						dutyPersonShiftLog.setInstanceId(dutyPersonShiftDto.getInstanceId());
						dutyPersonShiftLog.setDeptName(dutyCarDto.getTeamName());
						dutyPersonShiftLog.setPostTypeName(dutyCarDto.getPostTypeName());
						dutyPersonShiftLog.setDutyArea(dutyCarDto.getDutyArea());
						dutyPersonShiftLog.setCarName(dutyCarDto.getCarName());
						String shiftName = dutyPersonShiftDto.getShiftName();
						if (StringUtils.isBlank(shiftName) && Objects.nonNull(dutyPersonShiftDto.getShiftId())) {
							DutyShift dutyShift = dutyShiftService.getById(dutyPersonShiftDto.getShiftId());
							dutyPersonShiftDto.setShiftName(dutyShift.getName());
						}
						dutyPersonShiftLog.setShiftName(dutyPersonShiftDto.getShiftName());
						dutyPersonShiftLogMapper.update(
								dutyPersonShiftLog,
								Wrappers.<DutyPersonShiftLog>lambdaUpdate()
										.eq(DutyPersonShiftLog::getDutyDate, dutyPersonShiftDto.getDutyDate())
										.eq(DutyPersonShiftLog::getGroupCode, groupCode)
										.eq(DutyPersonShiftLog::getDutyUserId, dutyCarDto.getUserId())
										.eq(DutyPersonShiftLog::getIsDelete, false)
						);
					}
				}
			}
		});
	}

}
