package org.springblade.openinterface.carbarrier.Controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.springblade.community.parkinglot.entity.ParkingLot;
import org.springblade.community.parkinglot.service.IParkingLotService;
import org.springblade.community.parkingveh.entity.ParkingVeh;
import org.springblade.community.parkingveh.service.IParkingVehService;
import org.springblade.core.log.logger.BladeLogger;
import org.springblade.core.tool.api.R;
import org.springblade.openinterface.carbarrier.entity.*;
import org.springblade.openinterface.carbarrier.utils.HttpUtil;
import org.springblade.openinterface.carbarrier.utils.MD5Util;
import org.springblade.smartapplication.carenterrecord.entity.CarEnterRecord;
import org.springblade.smartapplication.carenterrecord.service.ICarEnterRecordService;
import org.springblade.smartapplication.caroutrecord.entity.CarOutRecord;
import org.springblade.smartapplication.caroutrecord.service.ICarOutRecordService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.awt.geom.QuadCurve2D;
import java.util.List;

/**
 * Created By lidexi in 2021/1/4
 * 调用安快停车场管理系统api
 **/
@RestController
@AllArgsConstructor
@RequestMapping("ankuai")
@Api(value = "同步安快接口", tags = "同步安快接口")
public class AnKuaiController {

	private IParkingLotService parkingLotService;
	private ICarEnterRecordService carEnterRecordService;
	private ICarOutRecordService carOutRecordService;
	private IParkingVehService parkingVehService;
	private BladeLogger logger;

	/**
	 * 同步安快所有停车场信息
	 */
	@PostMapping("/getAllParkInfo")
	public R allParkInfoSync(@RequestBody ParkInfoQuery parkInfoQuery) {

		//请求
		List<ParkingLot> parkingLots = HttpUtil.getParkInfo(parkInfoQuery);

		//持久化到本地数据库
		for (int i = 0; i < parkingLots.size(); i++) {
			ParkingLot parkingLot = parkingLots.get(i);
			ParkingLot isExist = parkingLotService.getBaseMapper().selectOne(new QueryWrapper<>(new ParkingLot()).lambda().eq(ParkingLot::getParkKey, parkingLot.getParkKey()));
			if (null != isExist) {//更新
				parkingLot.setId(isExist.getId());
				if (parkingLotService.updateById(parkingLot)) {
					logger.info("parkingLotUpdateSuccess", "旧:" + isExist.toString() + ";新:" + parkingLot.toString());
				} else {
					logger.error("parkingLotUpdateFail", "旧:" + isExist.toString() + ";新:" + parkingLot.toString());
				}
			} else {//新增
				if (parkingLotService.save(parkingLot)) {
					logger.info("parkingLotAddSuccess", parkingLot.toString());
				} else {
					logger.error("parkingLotAddFail", parkingLot.toString());
				}
			}
		}

		return new R();
	}

	/**
	 * 同步安快停车场剩余车位信息
	 */
	@PostMapping("/parkSpaceRemain")
	public R parkSpaceRemainSync(@RequestBody ParkInfoQuery parkInfoQuery) {
		String parkKey = parkInfoQuery.getParkKey();
		if (null != parkKey) {
			ParkingLot parkingLot = parkingLotService.getBaseMapper().selectOne(new QueryWrapper<>(new ParkingLot()).lambda().eq(ParkingLot::getParkKey, parkKey));
			if (parkingLot != null) {
				//请求
				ParkRemainResult remainSpaceResult = HttpUtil.getRemainSpaceResult(parkInfoQuery);
				if (remainSpaceResult != null) {
					parkingLot.setSpaceTotal(remainSpaceResult.getTotalSpaces());
					parkingLot.setRemainSpace(remainSpaceResult.getRemaiSpaces());
					if (parkingLotService.updateById(parkingLot)) {
						return R.success("更新成功");
					} else {
						return R.fail("获取成功，更新失败");
					}
				}

				//持久化到本地数据库
			} else {
				return R.fail("车场不存在");
			}
		} else {
			return R.fail("车场唯一编号不能为空");
		}


		return new R();
	}

	/**
	 * 同步安快入场记录信息
	 */
	@PostMapping("/GetEnterCarRecord")
	public R getCarEnterRecord(@RequestBody RecordQuery recordQuery) {

		//请求
		List<CarEnterRecord> carEnterRecordList = HttpUtil.getEnterRecordResult(recordQuery);

		//持久化到本地数据库
		carEnterRecordList.forEach(carEnterRecord -> {
			List<CarEnterRecord> isExits = carEnterRecordService.getBaseMapper().selectList(new QueryWrapper<>(new CarEnterRecord()).lambda()
				.eq(CarEnterRecord::getCarNo, carEnterRecord.getCarNo())
				.eq(CarEnterRecord::getEnterTime, carEnterRecord.getEnterTime())
				.eq(CarEnterRecord::getParkKey, carEnterRecord.getParkKey()));
			if (isExits.size() == 0) {//新增记录
				if (carEnterRecordService.save(carEnterRecord)) {
					logger.info("carEnterRecordAddSuccess", carEnterRecord.toString());
				} else {
					logger.error("carEnterRecordAddFail", carEnterRecord.toString());
				}
			}
		});


		return new R();
	}

	/**
	 * 同步安快出场记录信息
	 */
	@PostMapping("/GetOutCarRecord")
	public R GetOutCarRecord(@RequestBody RecordQuery recordQuery) {

		//请求
		List<CarOutRecord> carOutRecordList = HttpUtil.getOutRecordResult(recordQuery);

		//持久化到本地数据库
		carOutRecordList.forEach(carOutRecord -> {
			List<CarOutRecord> isExits = carOutRecordService.getBaseMapper().selectList(new QueryWrapper<>(new CarOutRecord()).lambda()
				.eq(CarOutRecord::getCarNo, carOutRecord.getCarNo())
				.eq(CarOutRecord::getOutTime, carOutRecord.getOutTime())
				.eq(CarOutRecord::getParkKey, carOutRecord.getParkKey()));
			if (isExits.size() == 0) {//新增记录
				if (carOutRecordService.save(carOutRecord)) {
					logger.info("carOutRecordAddSuccess", carOutRecord.toString());
				} else {
					logger.error("carOutRecordAddFail", carOutRecord.toString());
				}
			}
		});

		return new R();
	}

	/**
	 * 同步安快停车场车道信息
	 */
	@PostMapping("/parkVehInfoSync")
	public R parkVehInfoSync(@RequestBody ParkInfoQuery parkInfoQuery) {
		String parkKey = parkInfoQuery.getParkKey();
		if (null != parkKey) {
			ParkingLot parkingLot = parkingLotService.getBaseMapper().selectOne(new QueryWrapper<>(new ParkingLot()).lambda().eq(ParkingLot::getParkKey, parkKey));
			if (parkingLot != null) {
				//请求
				List<ParkingVeh> parkingVehs = HttpUtil.getParkVehInfo(parkInfoQuery);

				//持久化到数据库
				parkingVehs.forEach(parkingVeh -> {
					ParkingVeh isExist = parkingVehService.getBaseMapper().selectOne(new QueryWrapper<>(new ParkingVeh()).lambda()
						.eq(ParkingVeh::getParkKey, parkingVeh.getParkKey()).eq(ParkingVeh::getVehNumber, parkingVeh.getVehNumber()));
					if (isExist != null) {//更新
						parkingVeh.setId(isExist.getId());
						if (parkingVehService.updateById(parkingVeh)) {
							logger.info("parkVehUpdateSuccess", "旧：" + isExist.toString() + ";新：" + parkingVeh.toString());
						} else {
							logger.error("parkVehUpdateFail", "旧：" + isExist.toString() + ";新：" + parkingVeh.toString());
						}
					} else {//新增
						if (parkingVehService.save(parkingVeh)) {
							logger.info("parkVehAddSuccess", parkingVeh.toString());
						} else {
							logger.error("parkVehAddFail", parkingVeh.toString());
						}
					}
				});


			} else {
				return R.fail("车场不存在");
			}
		} else {
			return R.fail("车场唯一编号不能为空");
		}


		return new R();
	}

	/**
	 * 远程开关闸
	 */
	@PostMapping("/openOrCloseGate")
	public R<String> openOrCloseGate(OpenOrCloseGateQuery openOrCloseGateQuery) {
		String parkKey = openOrCloseGateQuery.getParkKey();
		if (null != parkKey) {
			ParkingLot parkingLot = parkingLotService.getBaseMapper().selectOne(new QueryWrapper<>(new ParkingLot()).lambda().eq(ParkingLot::getParkKey, parkKey));
			if (parkingLot != null) {
				String vlCtrNo = openOrCloseGateQuery.getVlCtrNo();
				List<ParkingVeh> parkingVehs = parkingVehService.getBaseMapper().selectList(new QueryWrapper<>(new ParkingVeh()).lambda().eq(ParkingVeh::getParkKey, parkKey).eq(ParkingVeh::getVehCtrlNo, vlCtrNo));
				if (parkingVehs.size() > 0) {
					String result = HttpUtil.openOrClose(openOrCloseGateQuery);
					return R.data(result);
				} else {
					return R.fail("控制机不存在");
				}
			} else {
				return R.fail("车场不存在");
			}
		} else {
			return R.fail("车场唯一编号不能为空");
		}

	}


}
