package com.gci.boot.modules.projects.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gci.boot.common.util.BeanUtilsCopy;
import com.gci.boot.constant.CommonConstant;
import com.gci.boot.exception.GciBootException;
import com.gci.boot.modules.basedata.entity.TbVehicle;
import com.gci.boot.modules.basedata.service.ITbVehicleService;
import com.gci.boot.modules.projects.entity.TbContract;
import com.gci.boot.modules.projects.entity.TbVehicleCheck;
import com.gci.boot.modules.projects.entity.TbVehicleCheckDetail;
import com.gci.boot.modules.projects.mapper.TbVehicleCheckDetailMapper;
import com.gci.boot.modules.projects.service.ITbVehicleCheckDetailService;

/**
 * <p>
 * 车辆验收车辆详情 服务实现类
 * </p>
 *
 * @author xushuhan
 * @since 2023-09-11
 */
@Service
public class TbVehicleCheckDetailServiceImpl extends ServiceImpl<TbVehicleCheckDetailMapper, TbVehicleCheckDetail> implements ITbVehicleCheckDetailService {

	@Autowired
	private ITbVehicleService tbVehicleService;
	
	@Override
	public void getVehiclesByCheckId(TbVehicleCheck check) {
		LambdaQueryWrapper<TbVehicleCheckDetail> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(TbVehicleCheckDetail::getCheckId, check.getId());
		queryWrapper.orderByAsc(TbVehicleCheckDetail::getCreateTime);
		List<TbVehicleCheckDetail> list = list(queryWrapper);
		check.setVehicleList(list);
		
		Set<String> con = new LinkedHashSet<>();
		Set<String> fras = new LinkedHashSet<>();
		for (TbVehicleCheckDetail pro : list) {
			if(StringUtils.hasLength(pro.getPlateNumber())) {
				con.add(pro.getPlateNumber());
			}
			if(StringUtils.hasLength(pro.getFrameNumber())) {
				fras.add(pro.getFrameNumber());
			}
		}
		String projectNames = String.join(",", con);
		String frameNumbers = String.join(",", fras);
		check.setPlateNumbers(projectNames);
		check.setFrameNumbers(frameNumbers);

	}
	
	@Override
	public void saveItem(TbVehicleCheck check) {

		QueryWrapper<TbVehicleCheckDetail> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("check_id", check.getId());
		remove(queryWrapper);

		Set<String> ids = check.getVehicleList().stream().map(t->t.getVehicleId()).collect(Collectors.toSet());
		Map<String,TbVehicle> map = new HashMap<>();
		if(ids.size()>0) {
			List<TbVehicle> busList = tbVehicleService.listByIds(ids);
			map = busList.stream().collect(Collectors.toMap(TbVehicle::getId,Function.identity()));
		}
		List<TbVehicle> updateCar = new ArrayList<>();
		List<TbVehicleCheckDetail> projects = new ArrayList<>();
		for(TbVehicleCheckDetail project:check.getVehicleList()) {
			if(map.containsKey(project.getVehicleId())) {
				TbVehicle car = map.get(project.getVehicleId());
				if(CommonConstant.INNER_PROJECT.equals(car.getProjectId())&&StringUtils.hasLength(check.getProjectId())) {
					car.setProjectId(check.getProjectId());
					updateCar.add(car);
				}
				BeanUtilsCopy.copyBeanPropFilterId(project, car);
			}
			project.setCheckId(check.getId());
			projects.add(project);
		}
		saveBatch(projects);
		
		//租赁交车，更新未分配项目车辆的项目id
		if("2".equals(check.getCheckType())&&updateCar.size()>0) {
			tbVehicleService.updateBatchById(updateCar);
		}
	}
	
	@Override
	public void checkVehicle(TbVehicleCheck check) {
		if(!"3".equals(check.getCheckType())&&check.getVehicleList()==null&&check.getVehicleList().size()<1) {
			throw new GciBootException("车辆信息不能为空");
		}
		if("1".equals(check.getCheckType())) {
			Set<String> vset = check.getVehicleList().stream().map(t->t.getFrameNumber()).collect(Collectors.toSet());
			if(vset.size()!=check.getVehicleList().size()) {
				throw new GciBootException("车架号不能重复");
			}
			QueryWrapper<TbVehicleCheckDetail> queryWrapper = new QueryWrapper<>();
			queryWrapper.ne("check_id", check.getId());
			queryWrapper.in("frame_number", vset);
			//查询其他项目
			String sql = "select 1 from tb_vehicle_check c where tb_vehicle_check_detail.check_id = c.id and c.id !='"+check.getId()+"' and c.project_id='"+check.getProjectId()+"'";
			queryWrapper.exists(sql);
			int exist = count(queryWrapper);
			if(exist>0) {
				throw new GciBootException("车架号不能重复!");
			}
		}
		if(StringUtils.hasLength(check.getCkeckUrl())) {
			if(check.getCkeckUrl().split(",").length>10) {
				throw new GciBootException("上传验收单不能超过10个！");
			}
		}
		if(StringUtils.hasLength(check.getEnsureUrl())) {
			if(check.getEnsureUrl().split(",").length>10) {
				throw new GciBootException("上传保函不能超过10个！");
			}
		}
		if(StringUtils.hasLength(check.getOtherUrl())) {
			if(check.getOtherUrl().split(",").length>10) {
				throw new GciBootException("上传其他文件不能超过10个！");
			}
		}
	}
	
	@Override
	public List<TbVehicleCheckDetail> getVehiclesByCheckIds(List<String> ids) {
		LambdaQueryWrapper<TbVehicleCheckDetail> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.in(TbVehicleCheckDetail::getCheckId, ids);
		queryWrapper.orderByDesc(TbVehicleCheckDetail::getCreateTime);
		List<TbVehicleCheckDetail> list = list(queryWrapper);
		return list;
	}

	public List<TbVehicleCheckDetail> getVehicleCheckDetails(String checkType,String contractId) {
		LambdaQueryWrapper<TbVehicleCheckDetail> queryWrapper = new LambdaQueryWrapper<>();
		String sql = "select 1 from tb_vehicle_check vc where vc.status='1' and tb_vehicle_check_detail.check_id = vc.id and vc.check_type='"
		+checkType+"' and vc.contract_id='"+contractId+"'";
		queryWrapper.exists(sql);
		queryWrapper.orderByDesc(TbVehicleCheckDetail::getCreateTime);
		List<TbVehicleCheckDetail> list = list(queryWrapper);
		
		return list;
	}
	
	//4采购合同、1租赁合同获取交接车车辆详情数据
	@Override
	public void initVehicleCheckDetail(TbContract contract) {
		String checkType = "";
		if("1".equals(contract.getContractType())) {
			checkType = "2";
		}else if("4".equals(contract.getContractType())) {
			checkType = "1";
		}
		if(!StringUtils.hasLength(checkType)) {
			return;
		}
		List<TbVehicleCheckDetail> details = getVehicleCheckDetails(checkType, contract.getId());
		contract.setVehicleList(details);
	}
	
}
