package com.yeejoin.amos.boot.module.ymt.flc.biz.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.entity.DataDictionary;
import com.yeejoin.amos.boot.biz.common.service.impl.DataDictionaryServiceImpl;
import com.yeejoin.amos.boot.module.ymt.api.dto.CylinderFileUrlDto;
import com.yeejoin.amos.boot.module.ymt.api.entity.PageParam;
import com.yeejoin.amos.boot.module.ymt.flc.api.dto.*;
import com.yeejoin.amos.boot.module.ymt.flc.api.entity.CylinderInfo;
import com.yeejoin.amos.boot.module.ymt.flc.api.enums.CyclinderStatus;
import com.yeejoin.amos.boot.module.ymt.flc.api.mapper.TzCylinderMapper;
import com.yeejoin.amos.boot.module.ymt.flc.api.service.ITzCylinderService;
import com.yeejoin.amos.feign.privilege.Privilege;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.validation.ValidationUtils;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 气瓶基本信息 服务实现类
 *
 * @author duanwei
 * @date 2022-08-11
 */
@Service
public class TzCylinderServiceImpl extends BaseService<TzCylinderInfoDto, CylinderInfo, TzCylinderMapper>
		implements ITzCylinderService {

	@Autowired
	private TzCylinderMapper tzCylinderMapper;

	@Autowired
	DataDictionaryServiceImpl iDataDictionaryService;


	@Override
	public IPage<TzCylinderInfoDto> getCylinderInfoDtoList(PageParam pageParam, TzCylinderInfoDto tzCylinderInfoDto,
														   String key) {
		Page<TzCylinderInfoDto> page = new Page<>(pageParam.getCurrent(), pageParam.getSize());
		System.out.println("key有值：" + key);
		String superviseOrgCode = Privilege.companyClient.seleteOne(Long.valueOf(key)).getResult().getOrgCode();
		return tzCylinderMapper.getTzCylinderInfoList(page, tzCylinderInfoDto, superviseOrgCode);

	}

	@Override
	public TzCylinderTraceDto getCylinderTraceDto(String sequenceNbr) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String orgCode = tzCylinderMapper.getSequencCode(sequenceNbr);
		TzCylinderProduceDto tzCylinderProduceDto = tzCylinderMapper.getTzCylinderProduceDto(orgCode);
		if(!ValidationUtil.isEmpty(tzCylinderProduceDto.getManufacturingDate())) {
			if(tzCylinderProduceDto.getManufacturingDate().length()>10) {
				tzCylinderProduceDto.setManufacturingDate(tzCylinderProduceDto.getManufacturingDate().substring(0,10));
			}
		}
		if (!ValidationUtil.isEmpty(tzCylinderProduceDto.getProductQualified())) {

			tzCylinderProduceDto.setProductQualified(tzCylinderProduceDto.getProductQualified());
		}
		if (!ValidationUtil.isEmpty(tzCylinderProduceDto.getProofQuality())) {

			tzCylinderProduceDto.setProofQuality(tzCylinderProduceDto.getProofQuality());

		}
		if (!ValidationUtil.isEmpty(tzCylinderProduceDto.getSupervisionInspec())) {

			tzCylinderProduceDto.setSupervisionInspec(tzCylinderProduceDto.getSupervisionInspec());
		}
		if (!ValidationUtil.isEmpty(tzCylinderProduceDto.getTypeExperiments())) {

			tzCylinderProduceDto.setTypeExperiments(tzCylinderProduceDto.getTypeExperiments());
		}

		TzCylinderInfoDto tzCylinderInfoDto = tzCylinderMapper.getTzCylinderInfoDto(sequenceNbr);
		DataDictionary data1 = iDataDictionaryService.getOne(new LambdaQueryWrapper<DataDictionary>()
				.eq(DataDictionary::getSequenceNbr, tzCylinderInfoDto.getCylinderVariety()));
		tzCylinderInfoDto.setCylinderVariety(data1 != null ? data1.getName() : null);
		DataDictionary data2 = iDataDictionaryService.getOne(new LambdaQueryWrapper<DataDictionary>()
				.eq(DataDictionary::getCode, tzCylinderInfoDto.getFillingMedia())
				.eq(DataDictionary::getType, "mediumType"));
		tzCylinderInfoDto.setFillingMedia(data2 != null ? data2.getName() : null);
		DataDictionary data3 = iDataDictionaryService.getOne(new LambdaQueryWrapper<DataDictionary>()
				.eq(DataDictionary::getSequenceNbr, tzCylinderInfoDto.getCylinderStatus()));
		tzCylinderInfoDto.setCylinderStatus(data3 != null ? data3.getName() : null);
		TzCylinderTagsDto tzCylinderTagsDto = tzCylinderMapper.getTzCylinderTagsDto(orgCode);

		if ( !ValidationUtil.isEmpty(tzCylinderTagsDto) && !ValidationUtil.isEmpty(tzCylinderTagsDto.getGasCylinderStamp())) {

			tzCylinderTagsDto.setGasCylinderStamp(tzCylinderTagsDto.getGasCylinderStamp());
		}
		List<TzCylinderInspectionDto> tzCylinderInspectionDtoList = tzCylinderMapper
				.getTzCylinderInspectionDto(orgCode);
		List<TzCylinderFillingDto> tzCylinderFillingDtoList = tzCylinderMapper.getTzCylinderFillingDto(orgCode);

		/**
		 * 取气瓶追溯详情 充装前检查项 名称和结果列表
		 */
		List<TzCylinderCheckDto> tzCylinderCheckDtoList = tzCylinderMapper.getTzCylinderCheckItem();
		Map<String, String> map = new HashMap<>();
		for (TzCylinderCheckDto tzCylinderCheckDto : tzCylinderCheckDtoList) {
			map.put(tzCylinderCheckDto.getItem(), tzCylinderCheckDto.getExplain());
		}

		for (TzCylinderFillingDto tzCylinderFillingDto : tzCylinderFillingDtoList) {
			if (!ValidationUtil.isEmpty(tzCylinderFillingDto) && !ValidationUtil.isEmpty(tzCylinderFillingDto.getAbnormal())) {
				tzCylinderFillingDto.setAbnormal(CyclinderStatus.getName(String.valueOf(tzCylinderFillingDto.getAbnormal())));
			}
			List<TzCylinderCheckDto> tzCylinderCheckDtoListResult = new ArrayList<>();
			TzCylinderBeforeCheckDto tzcylinderBeforeCheckDto = tzCylinderMapper
					.getTzCylinderBeforeCheck(tzCylinderFillingDto.getFillingBeforeId());
			JSONObject obj = JSONObject.parseObject(JSONObject.toJSONString(tzcylinderBeforeCheckDto));
			for (String str : obj.keySet()) {
				String explain = map.get(str);
				String value = String.valueOf(obj.get(str));
				DataDictionary data = iDataDictionaryService
						.getOne(new LambdaQueryWrapper<DataDictionary>().eq(DataDictionary::getSequenceNbr, value));
				TzCylinderCheckDto tzcylinderCheckDto = new TzCylinderCheckDto(str, explain,
						data != null ? data.getCode() : null);
				tzCylinderCheckDtoListResult.add(tzcylinderCheckDto);
			}
			tzCylinderFillingDto.setTzCylinderCheckDtoList(tzCylinderCheckDtoListResult);
		}

		/**
		 * 取气瓶追溯详情 充装后检查项 名称和结果列表
		 */
		List<TzCylinderCheckDto> tzCylinderAfterCheckDtoList = tzCylinderMapper.getTzCylinderAfterCheckItem();
		Map<String, String> afterMap = new HashMap<>();
		for (TzCylinderCheckDto tzCylinderCheckDto : tzCylinderAfterCheckDtoList) {
			afterMap.put(tzCylinderCheckDto.getItem(), tzCylinderCheckDto.getExplain());
		}
		for (TzCylinderFillingDto tzCylinderFillingDto : tzCylinderFillingDtoList) {
			List<TzCylinderCheckDto> tzCylinderAfterCheckDtoListResult = new ArrayList<>();
			TzCylinderAfterCheckDto tzcylinderAfterCheckDto = tzCylinderMapper
					.getTzCylinderAfterCheck(tzCylinderFillingDto.getFillingCheckId());
			JSONObject obj = JSONObject.parseObject(JSONObject.toJSONString(tzcylinderAfterCheckDto));
			for (String str : obj.keySet()) {
				String explain = afterMap.get(str);
				String value = String.valueOf(obj.get(str));
				DataDictionary data = iDataDictionaryService
						.getOne(new LambdaQueryWrapper<DataDictionary>().eq(DataDictionary::getSequenceNbr, value));
				TzCylinderCheckDto tzcylinderCheckDto = new TzCylinderCheckDto(str, explain,
						data != null ? data.getCode() : null);
				tzCylinderAfterCheckDtoListResult.add(tzcylinderCheckDto);
			}
			tzCylinderFillingDto.setTzCylinderAfterCheckDtoList(tzCylinderAfterCheckDtoListResult);
		}

		if(!ValidationUtil.isEmpty(tzCylinderFillingDtoList)){
			String fillingEndTime = tzCylinderFillingDtoList.iterator().next().getFillingEndtime();
			if(!ValidationUtil.isEmpty(fillingEndTime)) {
				if(fillingEndTime.length()>10) {
					tzCylinderFillingDtoList.iterator().next().setFillingDate(fillingEndTime.substring(0,10));
				}
			}
		}

		for (TzCylinderFillingDto tzCylinderFillingDto : tzCylinderFillingDtoList) {
			List<TzCylinderCheckDto> collect = tzCylinderFillingDto.getTzCylinderAfterCheckDtoList().stream().filter(dto -> dto.getResult().equals("0")).collect(Collectors.toList());
		   if (collect.size() != 0) {
			   tzCylinderFillingDto.setCheckResultsAfter(CyclinderStatus.NOHEGE.getName());
		   }else {
			   tzCylinderFillingDto.setCheckResultsAfter(CyclinderStatus.HEGE.getName());
		   }

		}
		return new TzCylinderTraceDto(tzCylinderProduceDto, tzCylinderInfoDto, tzCylinderTagsDto,
				tzCylinderInspectionDtoList, tzCylinderFillingDtoList);
	}


	public CylinderFileUrlDto getFileUrlAndName(String sequenceNbr){
		String orgCode = tzCylinderMapper.getSequencCode(sequenceNbr);
		TzCylinderProduceDto tzCylinderProduceDto = tzCylinderMapper.getTzCylinderProduceDto(orgCode);
		TzCylinderTagsDto tzCylinderTagsDto = tzCylinderMapper.getTzCylinderTagsDto(orgCode);
		CylinderFileUrlDto dto =new CylinderFileUrlDto();
		if (!ValidationUtil.isEmpty(tzCylinderProduceDto)) {
			if (!ValidationUtil.isEmpty(tzCylinderProduceDto.getProductQualified())) {
				String productQualified = tzCylinderProduceDto.getProductQualified();
				List<Map> productQualifiedList = getMaps(productQualified);
				dto.setProductQualified(productQualifiedList);
			}
			if (!ValidationUtil.isEmpty(tzCylinderProduceDto.getProofQuality())) {
				String proofQuality = tzCylinderProduceDto.getProofQuality();
				List<Map> proofQualityList = getMaps(proofQuality);
				dto.setProofQuality(proofQualityList);
			}
			if (!ValidationUtil.isEmpty(tzCylinderProduceDto.getSupervisionInspec())) {
				String supervisionInspec = tzCylinderProduceDto.getSupervisionInspec();
				List<Map> supervisionInspecList = getMaps(supervisionInspec);
				dto.setSupervisionInspec(supervisionInspecList);
			}
			if (!ValidationUtil.isEmpty(tzCylinderProduceDto.getTypeExperiments())) {
				String typeExperiments = tzCylinderProduceDto.getTypeExperiments();
				List<Map> typeExperimentsList = getMaps(typeExperiments);
				dto.setTypeExperiments(typeExperimentsList);
			}
		}
		if (!ValidationUtil.isEmpty(tzCylinderTagsDto)&&!ValidationUtil.isEmpty(tzCylinderTagsDto.getGasCylinderStamp())) {
			String gasCylinderStamp = tzCylinderTagsDto.getGasCylinderStamp();
			List<Map> gasCylinderStampList = getMaps(gasCylinderStamp);
			dto.setGasCylinderStamp(gasCylinderStampList);
		}
		return dto;
	}

	public List<Map> getMaps(String o){
		List list=new ArrayList();
		if (!ValidationUtil.isEmpty(o)) {
			JSONArray jsonArray = JSONArray.parseArray(o);
			for (Object li : jsonArray) {
				JSONObject objects = JSONObject.parseObject(li.toString());
				HashMap<String, String> map= new HashMap<>();
				map.put("url",objects.getString("fileUrl"));
				map.put("name",objects.getString("fileName"));
				list.add(map);
			}
		}
		return list;
	}
}
