package com.yeejoin.amos.api.openapi.face.service;


import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.yeejoin.amos.api.openapi.face.orm.dao.ESCylinderFillingRecordRepository;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.module.cylinder.api.entity.ESCylinderFillingRecordDto;
import com.yeejoin.amos.boot.module.cylinder.flc.api.dto.CylinderFillingRecordDto;
import com.yeejoin.amos.boot.module.cylinder.flc.api.dto.CylinderUnitDto;
import com.yeejoin.amos.boot.module.cylinder.flc.api.entity.CylinderFillingRecord;
import com.yeejoin.amos.boot.module.cylinder.flc.api.mapper.CylinderFillingRecordMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.component.cache.Redis;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import com.yeejoin.amos.api.openapi.constant.Constant;
import com.yeejoin.amos.api.openapi.face.model.BizTokenModel;
import com.yeejoin.amos.api.openapi.face.model.TmCylinderFillingRecordModel;
import com.yeejoin.amos.api.openapi.face.orm.dao.TmCylinderFillingRecordMapper;
import com.yeejoin.amos.api.openapi.face.orm.entity.TmCylinderFillingRecord;


/**
 * 
 * <pre>
 * 液化气体气瓶充装信息-充装记录 服务类
 * </pre>
 *
 * @author gwb
 * @version $Id: ElevatorService.java, v 0.1 2021年9月30日 下午3:28:55 gwb Exp $
 */
@Component
public class TmCylinderFillingRecordService extends BaseService<TmCylinderFillingRecordModel, TmCylinderFillingRecord, TmCylinderFillingRecordMapper> {
    @Autowired
    private RedisTemplate redisTemplate;

	@Autowired
	CylinderFillingRecordMapper cylinderFillingRecordMapper;

	@Autowired
	ESCylinderFillingRecordRepository esCylinderFillingRecordRepository;
	@Autowired
	private SyncCylinderDataService syncCylinderDataService;

	@DSTransactional
	public String createCylinderFilling(List<TmCylinderFillingRecordModel> model) {
		// TODO Auto-generated method stub
//		if (ValidationUtil.isEmpty(model))
//			throw new BadRequest("气瓶标签信息为空.");
		syncCylinderFilling(model);

		ArrayList<ESCylinderFillingRecordDto> models = Bean.toModels(model, ESCylinderFillingRecordDto.class);
		createCylinderFillingRecord(models);

		for (TmCylinderFillingRecordModel cylinderFillingRecordModel : model) {
			cylinderFillingRecordModel.setRecDate(new Date());
			cylinderFillingRecordModel.setAppId(getAppId());
			this.createWithModel(cylinderFillingRecordModel);
		}
		return "OK";
	}

	@DS("tzs")
	private void syncCylinderFilling(List<TmCylinderFillingRecordModel> model) {
		syncCylinderDataService.syncCylinderFillingRecord(model);
	}

	private String getAppId() {
		String tokenKey = Redis.genKey(Constant.TOKEN_PREFIX,RequestContext.getToken());
    	BizTokenModel bizTokenModel = (BizTokenModel) redisTemplate.opsForValue().get(tokenKey);
    	return bizTokenModel.getAppId();
	}

	public List<String> getDateList() {
    	return baseMapper.getDateList();
	}



    @DS("tzs")
	public void createCylinderFillingRecord(List<ESCylinderFillingRecordDto> cylinderFillingRecord) {
		if (!ObjectUtils.isEmpty(cylinderFillingRecord)) {
			List<String> appIds = cylinderFillingRecord.stream().map(ESCylinderFillingRecordDto::getAppId).collect(Collectors.toList());
			List<String> sequenceCodeS = cylinderFillingRecord.stream().map(ESCylinderFillingRecordDto::getSequenceCode).collect(Collectors.toList());
			List<ESCylinderFillingRecordDto> cylinderFillingRecordInfo = cylinderFillingRecordMapper.getCylinderFillingRecordInfo(appIds, sequenceCodeS);
			cylinderFillingRecord.stream().map(item -> {
				List<ESCylinderFillingRecordDto> collect = cylinderFillingRecordInfo.stream().filter(e -> item.getAppIdAndSequenceCode().equals(e.getAppIdAndSequenceCode())).collect(Collectors.toList());
				if (!ObjectUtils.isEmpty(collect)) {
					item.setUnitName(collect.get(0).getUnitName());
					item.setFactoryNum(collect.get(0).getFactoryNum());
					item.setCylinderVariety(collect.get(0).getCylinderVariety());
					item.setCylinderVarietyName(collect.get(0).getCylinderVarietyName());
					item.setUnitInnerCode(collect.get(0).getUnitInnerCode());
					item.setSequenceCode(collect.get(0).getSequenceCode());
					item.setQrCode(collect.get(0).getQrCode());
					item.setElectronicLabelCode(collect.get(0).getElectronicLabelCode());
					item.setAppId(collect.get(0).getAppId());
					item.setCreditCode(collect.get(0).getCreditCode());
					item.setRegionCode(collect.get(0).getRegionCode());
					try {
						item.setInspectionDateMs(ObjectUtils.isEmpty(item.getFillingStartTime()) ? 0L : DateUtils.dateParseWithPattern(item.getFillingStartTime()).getTime());
						item.setInspectionDateAfterMS(ObjectUtils.isEmpty(item.getFillingEndTime()) ? 0L : DateUtils.dateParseWithPattern(item.getFillingEndTime()).getTime());
					} catch (ParseException e) {
						throw new RuntimeException(e);
					}
				}
				return item;
			}).collect(Collectors.toList());
			saveCylinderFillingRecord2ES(cylinderFillingRecord);
		}
	}

	public void saveCylinderFillingRecord2ES(List<ESCylinderFillingRecordDto> records) {
		List<String> ids = new ArrayList<>();
		for (ESCylinderFillingRecordDto record : records) {
			CylinderFillingRecord cylinderFillingRecord = new CylinderFillingRecord();
			BeanUtils.copyProperties(record, cylinderFillingRecord);
			ids.add(String.valueOf(record.getSequenceNbr()));
		}
		esCylinderFillingRecordRepository.saveAll(records);
		cylinderFillingRecordMapper.updateCylinderFillingToEsStatus(ids);
	}

}	
