	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
	FirefightersMapper firefightersMapper;		

	@Autowired
	EquipFeignClient equipFeignClient;

	String driverPostTypeCode = "5";

	@Autowired
	EquipFeignClient equipFeign;



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


	private  static  final  String USERNAME="userName";
	private  static  final  String POSTTYPENAME="postTypeName";
	private  static  final  String TEAMNAME="teamName";
	private  static  final  String CARNAME="carName";
	private  static  final  String CARSTATUS="carStatus";
	private  static  final  String CARID="carId";

	@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;
	}



	@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<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());
			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<String, Object>();
			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(",");
				

						// 获取当前装备ID下的排版数据
						List<Map<String, Object>> specifyDateList = dutyPersonShiftMapper.getPositionStaffDutyForSpecifyDate(dutyDay,
								this.getGroupCode(), instanceIds,null, fieldCode);

						//取消掉班次的显示---2022-01-16 by chenhao ---start
						//取消掉班次的显示---2022-01-16 by chenhao ---end
						if (specifyDateList.size()>0 && specifyDateList != null) {
					for (Map<String, Object> specify : specifyDateList) {
						LinkedHashMap<String, Object> infoMap_2 = new LinkedHashMap<String, Object>();

						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;
	}
    @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 specifyDateList;
			}
			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;
	}

}
