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

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
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.entity.DynamicFormColumn;
import com.yeejoin.amos.boot.module.common.api.entity.DynamicFormInstance;
import com.yeejoin.amos.boot.module.common.api.entity.Firefighters;
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;

	@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());
		insertPersonShift(instanceId, dutyCarDto.getDutyShift());
		// 修改操作动态表单的方法，修改人陈浩 -------------end 2021-09-28
		// 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());
		return dutyCarDto;
	}

	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) {
		List<Map<String, Object>> equipmentList = dutyPersonShiftMapper.getEquipmentForSpecifyDate(dutyDay,
				this.getGroupCode(), "carId", "carName", "teamName","result.carId");
		if(equipmentList==null || equipmentList.size()<1 || equipmentList.get(0)==null) {
			return null;
		}
		List<Object>	detailList = new ArrayList<Object>();
		for (Map<String, Object> map : equipmentList) {
			List<Map<String, Object>>	resultList = new ArrayList<Map<String, Object>>();
			LinkedHashMap<String, Object> titleMap_1 =new LinkedHashMap<String, Object>();
			titleMap_1.put("消防车辆", map.get("carName").toString());
			resultList.add(titleMap_1);
			LinkedHashMap<String, Object> titleMap_2 =new LinkedHashMap<String, Object>();
			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>>  dutyList = dutyPersonShiftMapper.getDutyForSpecifyDate(dutyDay);
				if(dutyList!=null && dutyList.size()>0) {
					for (Map<String, Object> dutyDetail : dutyList) {
						if(!dutyDetail.containsKey("name")) {
							continue;
						}
						// 获取当前装备ID下的排版数据
						List<Map<String, Object>> specifyDateList = dutyPersonShiftMapper.getPositionStaffDutyForSpecifyDate(dutyDay,
								this.getGroupCode(), instanceIds,dutyDetail.get("name").toString());
						if(specifyDateList==null || specifyDateList.size() < 1 || specifyDateList.get(0)==null) {
							continue;
						}
						LinkedHashMap<String, Object> infoMap_1 =new LinkedHashMap<String, Object>();
						infoMap_1.put(dutyDetail.get("name").toString(), "");
						resultList.add(infoMap_1);
						for (Map<String, Object> specify : specifyDateList) {
							LinkedHashMap<String, Object> infoMap_2 =new LinkedHashMap<String, Object>();
							infoMap_2.put(specify.get("postTypeName").toString(),specify.get("userName").toString());
							resultList.add(infoMap_2);
						}
					}
				}
				// 获取当前装备ID下的排版数据
//				List<Map<String, Object>> specifyDateList = dutyPersonShiftMapper.getSpecifyDateList(dutyDay,
//						this.getGroupCode(), instanceIds,null);
//				for (Map<String, Object> specify : specifyDateList) {
//					
//					if(!specify.containsKey("name") || specify.get("name").toString()==null) {
//						continue;
//					}
//					LinkedHashMap<String, Object> infoMap_1 =new LinkedHashMap<String, Object>();
//					infoMap_1.put(specify.get("name").toString(), "");
//					resultList.add(infoMap_1);
//					Map<String, Object> equipmentOperatorMap = dutyPersonShiftMapper.getEquipmentOperator(dutyDay,
//							this.getGroupCode(), instanceIds, "消防车驾驶员", specify.get("name").toString());
//					String operator =null;
//					if (equipmentOperatorMap!=null && equipmentOperatorMap.containsKey("userName")) {
//						 operator = equipmentOperatorMap.get("equipmentOperatorMap").toString();
//					}
//					LinkedHashMap<String, Object> infoMap_2 =new LinkedHashMap<String, Object>();
//					infoMap_2.put("驾驶员", operator!=null?operator:"");
//					resultList.add(infoMap_2);
//					LinkedHashMap<String, Object> infoMap_3 =new LinkedHashMap<String, Object>();
//					infoMap_3.put("战斗员",specify.get("value").toString());
//					resultList.add(infoMap_3);
//				}
			}
			detailList.add(resultList);
		}
		return detailList;
	}
    @Override
	public int getDutyCarCount(Long carId) {
		List<Map<String, Object>> equipmentList = dutyPersonShiftMapper.getEquipmentForSpecifyDate(DateUtils.getDateNowShortStr(),
				this.getGroupCode(), "carId", "carName", "teamName","result.carId");
		int count =0;
		for (Map<String, Object> map : equipmentList) {
			if(map.containsKey("carId") && map.get("carId").equals(carId)) {
				count++;
			}
		}
		return count;
	}

}
