package org.springblade.openinterface.estate;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.springblade.community.agency.controller.AgencyController;
import org.springblade.community.agency.entity.Agency;
import org.springblade.community.agency.service.IAgencyService;
import org.springblade.community.building.entity.Building;
import org.springblade.community.building.service.IBuildingService;
import org.springblade.community.floor.entity.Floor;
import org.springblade.community.floor.service.IFloorService;
import org.springblade.community.houseuser.entity.Houseuser;
import org.springblade.community.houseuser.service.IHouseuserService;
import org.springblade.community.residential.entity.Residential;
import org.springblade.community.residential.service.IResidentialService;
import org.springblade.community.room.entity.Room;
import org.springblade.community.room.service.IRoomService;
import org.springblade.community.unit.entity.Unit;
import org.springblade.community.unit.service.IUnitService;
import org.springblade.core.tool.api.R;
import org.springblade.jobs.reportjob.entity.ReportJob;
import org.springblade.jobs.reportjob.service.IReportJobService;
import org.springblade.openinterface.dto.estate.*;
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.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

@RestController
@AllArgsConstructor
@RequestMapping("openinterface/listen/estate")
@Api(value = "物业开放接口", tags = "开放接口")
public class EstateOpenController {

	private IAgencyService agencyService;
	private IResidentialService residentialService;
	private IBuildingService buildingService;
	private IUnitService unitService;
	private IFloorService floorService;
	private IRoomService roomService;
	private IHouseuserService houseuserService;
	private IReportJobService reportJobService;

	@PostMapping("/agencySync")
	public R agencySync(@RequestBody AgencyPushDto agencyPushDto){
		//判断社区是否已存在网格系统
		Long agencyOldId = agencyPushDto.getId();
		Agency isExist = this.agencyService.getBaseMapper().selectOne(new QueryWrapper<>(new Agency()).lambda().eq(Agency::getOldId, agencyOldId.toString()));
		if(null != isExist){//数据已经存在
			boolean flag = false;//是否修改标志
			//判断可修改的字段是否修改
			if(isExist.getPersonName().equals(agencyPushDto.getPersonName())){//负责人姓名
				isExist.setPersonName(agencyPushDto.getPersonName());
				flag = true;
			}

			if(isExist.getPersonPhone().equals(agencyPushDto.getPersonPhone())){
				isExist.setPersonPhone(agencyPushDto.getPersonPhone());
				flag = true;
			}
			if(flag){
				boolean b = this.agencyService.updateById(isExist);
				return R.status(b);
			}

		}else{//数据不存在
			Agency agency = this.buildNewAgency(agencyPushDto);
			boolean save = this.agencyService.save(agency);
			if(save){
				agency.setOrgPosition("/"+agency.getRegionProvince()+"/"+agency.getRegionCity()+"/"+agency.getRegionArea()+"/"+agency.getRegionStreet()+"/"+agency.getId());
				this.agencyService.updateById(agency);
			}
			return R.status(save);

		}

		return R.status(true);
	}

	@PostMapping("/residentialSync")
	public R residentialSync(@RequestBody ResidentialPushDto residentialPushDto){
		System.out.println(residentialPushDto);
		//判断该小区是否存在在网格系统中
		Long residentialOldId = residentialPushDto.getId();
		Residential isExist = this.residentialService.getBaseMapper().selectOne(new QueryWrapper<>(new Residential()).lambda().eq(Residential::getOldId, residentialOldId));
		if(null != isExist){//已存在-更新

		}else{//不存在-新增
			Residential residential = this.buildNewResidential(residentialPushDto);
			//绑定网格系统的所属社区
			Agency agency = this.agencyService.getOne(new QueryWrapper<>(new Agency()).lambda().eq(Agency::getOldId, residentialPushDto.getAgencyId().toString()));
			if(agency == null){
				return R.status(false);
			}
			residential.setAgencyId(agency.getId());

			boolean save = this.residentialService.save(residential);
			if(save){
				//设置orgPosition
				residential.setOrgPosition(agency.getOrgPosition()+"/"+residential.getId());
				this.residentialService.updateById(residential);
				return R.status(true);
			}else {
				return R.status(false);
			}
		}


		return R.status(true);
	}

	@PostMapping("/buildingSync")
	public R buildingSync(@RequestBody BuildingPushDto buildingPushDto){

		System.out.println(buildingPushDto);
		Long buildOldId = buildingPushDto.getId();
		Building isExist = this.buildingService.getOne(new QueryWrapper<>(new Building()).lambda().eq(Building::getOldId, buildOldId));
		if(null != isExist){//更新

		}else{
			Building building = this.buildNewBuilding(buildingPushDto);

			boolean save = this.buildingService.save(building);
			if(save){
				//设置orgPosition-在buildNewBuilding方法中已将其初始化为所属小区的orgPosition
				building.setOrgPosition(building.getOrgPosition()+"/"+building.getId());
				this.buildingService.updateById(building);
				return R.status(true);
			}else {
				return R.status(false);
			}
		}
		return R.status(true);
	}

	@PostMapping("/unitSync")
	public R unitSync(@RequestBody UnitPushDto unitPushDto){
		System.out.println(unitPushDto);
		Long unitOldId = unitPushDto.getId();
		Unit isExist = this.unitService.getOne(new QueryWrapper<>(new Unit()).lambda().eq(Unit::getOldId, unitOldId));
		if(null != isExist){//更新

		}else{//新增
			Unit unit = this.buildNewUnit(unitPushDto);
			boolean save = this.unitService.save(unit);
			if(save){
				unit.setOrgPosition(unit.getOrgPosition()+"/"+unit.getId());
				this.unitService.updateById(unit);
				return R.status(true);
			}else {
				return R.status(false);
			}

		}
		return R.status(true);
	}

	@PostMapping("/floorSync")
	public R floorSync(@RequestBody FloorPushDto floorPushDto){

		System.out.println(floorPushDto);
		Long floorOldId = floorPushDto.getId();
		Floor isExist = this.floorService.getOne(new QueryWrapper<>(new Floor()).lambda().eq(Floor::getOldId, floorOldId.toString()));
		if(null != isExist){//更新

		}else{//新增
			Floor floor = this.buildNewFloor(floorPushDto);
			boolean save = this.floorService.save(floor);
			if(save){
				floor.setOrgPosition(floor.getOrgPosition()+"/"+floor.getId());
				return R.status(floorService.updateById(floor));
			}else{
				return R.status(false);
			}
		}
		return R.status(true);
	}

	@PostMapping("/roomSync")
	public R roomSync(@RequestBody RoomPushDto roomPushDto){

		System.out.println(roomPushDto.toString());
		Long roomOldId = roomPushDto.getId();
		Room isExist = this.roomService.getOne(new QueryWrapper<>(new Room()).lambda().eq(Room::getOldId,roomOldId));
		if(null != isExist){//更新

		}else {//新增
			Room room = this.buildNewRoom(roomPushDto);
			boolean save = this.roomService.save(room);
			if(save){
				room.setOrgPosition(room.getOrgPosition()+"/"+room.getId());
				return R.status(this.roomService.updateById(room));
			}else {
				return R.status(false);
			}
		}
		return R.status(true);
	}

	@PostMapping("/userSync")
	public R userSync(@RequestBody ApplyUserPushDto applyUserPushDto){

		System.out.println(applyUserPushDto.toString());
		Long userOldId = applyUserPushDto.getUserId();
		Houseuser isExist = this.houseuserService.getOne(new QueryWrapper<>(new Houseuser()).lambda().eq(Houseuser::getOldId,userOldId.toString()));
		if(null != isExist){//更新

		}else {//新增
			Houseuser houseuser = this.buildNewHouseUser(applyUserPushDto);
			boolean save = this.houseuserService.save(houseuser);
			if(save){
				houseuser.setOrgPosition(houseuser.getOrgPosition()+"/"+houseuser.getId());
				return R.status(this.houseuserService.updateById(houseuser));
			}else {
				return R.status(false);
			}
		}
		return R.status(true);
	}



	private Agency buildNewAgency(AgencyPushDto agencyPushDto){
		Agency agency = new Agency();

		agency.setPersonPhone(agencyPushDto.getPersonName());
		agency.setPersonName(agencyPushDto.getPersonName());
		agency.setRegionStreet(agencyPushDto.getRegionStreet());
		agency.setRegionArea(agencyPushDto.getRegionArea());
		agency.setRegionCity(agencyPushDto.getRegionCity());
		agency.setRegionProvince(agencyPushDto.getRegionProvince());
		agency.setAgencyName(agencyPushDto.getAgencyName());
		agency.setResidentialCount(agencyPushDto.getResidentialCount());
		agency.setRoomCount(agencyPushDto.getRoomCount());
		agency.setAddress(agencyPushDto.getAddress());
		agency.setPersonCount(agencyPushDto.getPersonCount());
		agency.setAgencyArea(agencyPushDto.getAgencyArea());
		agency.setAgencyNo(agencyPushDto.getAgencyNo());
		agency.setCarCount(agencyPushDto.getCarCount());
		agency.setOldId(String.valueOf(agencyPushDto.getId()));
		agency.setRemark(agencyPushDto.getRemark());
		agency.setTenantId("000000");
		agency.setUnitCount(agencyPushDto.getUnitCount());
		agency.setLatitude(agencyPushDto.getLatitude());
		agency.setLongitude(agencyPushDto.getLongitude());

		return agency;
	}

	private Residential buildNewResidential(ResidentialPushDto residentialPushDto){
		Residential residential = new Residential();

		residential.setRoomNumber(residentialPushDto.getRoomNumber());
		residential.setFloorNumber(residentialPushDto.getFloorNumber());
		residential.setUnitNumber(residentialPushDto.getUnitNumber());
		residential.setBuildingNumber(residentialPushDto.getBuildingNumber());
		residential.setOldId(residentialPushDto.getId());
		residential.setUserNumber(residentialPushDto.getUserNumber());
		residential.setAddress(residentialPushDto.getAddress());
		residential.setRegionArea(residentialPushDto.getRegionArea());
		residential.setRegionCity(residentialPushDto.getRegionCity());
		residential.setRegionProvince(residentialPushDto.getRegionProvince());
		residential.setName(residentialPushDto.getName());
		residential.setPersonTel(residentialPushDto.getPersonTel());
		residential.setPersonName(residentialPushDto.getPersonName());
		residential.setRemark(residentialPushDto.getRemark());
		residential.setLatitude(residentialPushDto.getLatitude());
		residential.setLongitude(residentialPushDto.getLongitude());
		residential.setTenantId("000000");
		return residential;
	}

	private Building buildNewBuilding(BuildingPushDto buildingPushDto){
		Building building = new Building();
		building.setName(buildingPushDto.getName());

		//绑定网格的小区
		Residential residential = this.residentialService.getOne(new QueryWrapper<>(new Residential()).lambda().eq(Residential::getOldId, buildingPushDto.getResidentialId()));
		if(residential != null){
			building.setResidentialId(residential.getId());
			building.setResidentialName(residential.getName());
			building.setAgencyId(residential.getAgencyId());
			building.setOrgPosition(residential.getOrgPosition());
		}else {
			building.setResidentialName("物业系统所属小区id"+buildingPushDto.getId());
		}

		building.setOldId(buildingPushDto.getId());

		building.setTenantId("000000");
		building.setCreateTime(buildingPushDto.getCreateDate());


		return building;
	}

	private Unit buildNewUnit(UnitPushDto unitPushDto){
		Unit unit = new Unit();

		unit.setRoomNumber(unitPushDto.getRoomNumber());
		unit.setFloorNumber(unitPushDto.getFloorNumber());
		unit.setUnitNumber(unitPushDto.getUnitNumber());
		unit.setName(unitPushDto.getName());
		unit.setUserNumber(unitPushDto.getUserNumber());
		unit.setOldId(unitPushDto.getId());
		unit.setBuiltYear(unitPushDto.getBuiltYear());
		unit.setIncludingElevator(unitPushDto.getIncludingElevator());
		unit.setPersonName(unitPushDto.getPersonName());
		unit.setPersonTel(unitPushDto.getPersonTel());
		unit.setPropertyNature(unitPushDto.getPropertyNature());
		unit.setRemark(unitPushDto.getRemark());
		unit.setSerial(unitPushDto.getSerial());
		unit.setTenantId("000000");


		//绑定小区
		Long residentialOldId = unitPushDto.getResidentialId();
		Residential residential = this.residentialService.getOne(new QueryWrapper<>(new Residential()).lambda().eq(Residential::getOldId,residentialOldId));
		if(null != residential){
			unit.setResidentialId(residential.getId());
			unit.setResidentialName(residential.getName());
			unit.setAgencyId(residential.getAgencyId());
		}else{
			unit.setResidentialName("物业系统平台的小区id："+residentialOldId);
		}

		//绑定楼栋
		Long buildingOldId = unitPushDto.getBuildingId();
		Building building = this.buildingService.getOne(new QueryWrapper<>(new Building()).lambda().eq(Building::getOldId, buildingOldId));
		if(null != building){
			unit.setBuildingId(building.getId());
			unit.setBuildingName(building.getName());
			unit.setOrgPosition(building.getOrgPosition());
		}else {
			unit.setBuildingName("物业系统平台的楼栋id："+buildingOldId);
		}


		return unit;
	}

	private Floor buildNewFloor(FloorPushDto floorPushDto){
		Floor floor = new Floor();

		floor.setName(floorPushDto.getName());
		floor.setRoomNumber(floorPushDto.getRoomNumber());
		floor.setOldId(floorPushDto.getId().toString());
		floor.setUserNumber(floorPushDto.getUserNumber());
		floor.setPersonName(floorPushDto.getPersonName());
		floor.setPersonTel(floorPushDto.getPersonTel());
		floor.setRemark(floorPushDto.getRemark());
		floor.setTenantId("000000");

		//绑定小区
		Long residentialOldId = floorPushDto.getResidentialId();
		Residential residential = this.residentialService.getOne(new QueryWrapper<>(new Residential()).lambda().eq(Residential::getOldId, residentialOldId));
		if(null != residential){
			floor.setResidentialId(residential.getId());
			floor.setResidentialName(residential.getName());
			floor.setAgencyId(residential.getAgencyId());
		}else{
			floor.setResidentialName("物业系统小区id："+residentialOldId);
		}

		//绑定楼栋
		Long buildingOldId = floorPushDto.getBuildingId();
		Building building = this.buildingService.getOne(new QueryWrapper<>(new Building()).lambda().eq(Building::getOldId, buildingOldId));
		if(null != building){
			floor.setBuildingName(building.getName());
			floor.setBuildingId(building.getId());
		}else{
			floor.setBuildingName("物业系统的楼栋id："+buildingOldId);
		}

		//绑定单元
		Long unitOldId = floorPushDto.getUnitId();
		Unit unit = this.unitService.getOne(new QueryWrapper<>(new Unit()).lambda().eq(Unit::getOldId, unitOldId));
		if(null != unit){
			floor.setUnitName(unit.getName());
			floor.setUnitId(unit.getId());
			floor.setOrgPosition(unit.getOrgPosition());
		}else{
			floor.setUnitName("物业系统的单元id:"+unitOldId);
		}

		return floor;
	}

	private Room buildNewRoom(RoomPushDto roomPushDto){
		Room room = new Room();

		room.setUserNumber(roomPushDto.getUserNumber());
		room.setName(roomPushDto.getName());
		room.setOldId(roomPushDto.getId());
		room.setArea(roomPushDto.getArea());
		room.setHouseNumber(roomPushDto.getHouseNumber());
		room.setHouseType(roomPushDto.getHouseType());
		room.setOrientation(roomPushDto.getOrientation());
		room.setOrnament(roomPushDto.getOrnament());
		room.setRemark(roomPushDto.getRemark());

		//绑定小区
		Long residentialOldId = roomPushDto.getResidentialId();
		Residential residential = this.residentialService.getOne(new QueryWrapper<>(new Residential()).lambda().eq(Residential::getOldId, residentialOldId));
		if(null != residential){
			room.setAgencyId(residential.getAgencyId());
			room.setResidentialName(residential.getName());
			room.setResidentialId(residential.getId());
			room.setTenantId(residential.getTenantId());
		}else {
			room.setResidentialName("物业系统的小区id："+residentialOldId);
		}

		//绑定楼栋
		Long buildingOldId = roomPushDto.getBuildingId();
		Building building = this.buildingService.getOne(new QueryWrapper<>(new Building()).lambda().eq(Building::getOldId, buildingOldId));
		if(null != building){
			room.setBuildingId(building.getId());
			room.setBuildingName(building.getName());
		}else {
			room.setBuildingName("物业系统的楼栋id："+buildingOldId);
		}

		//绑定单元
		Long unitOldId = roomPushDto.getUnitId();
		Unit unit = this.unitService.getOne(new QueryWrapper<>(new Unit()).lambda().eq(Unit::getOldId, unitOldId));
		if(null != unit){
			room.setUnitName(unit.getName());
			room.setUnitId(unit.getId());
		}else {
			room.setUnitName("物业系统的单元id："+unitOldId);
		}

		//绑定楼层
		Long floorOldId = roomPushDto.getFloorId();
		Floor floor = this.floorService.getOne(new QueryWrapper<>(new Floor()).lambda().eq(Floor::getOldId, floorOldId.toString()));
		if(null != floor){
			room.setFloorName(floor.getName());
			room.setFloorId(floor.getId());
			room.setOrgPosition(floor.getOrgPosition());
		}

		return room;
	}

	private Houseuser buildNewHouseUser(ApplyUserPushDto applyUserPushDto){
		Houseuser houseuser = new Houseuser();

		houseuser.setOldId(applyUserPushDto.getUserId().toString());
		houseuser.setIdCard(applyUserPushDto.getIdCard());
		houseuser.setTel(applyUserPushDto.getTel());
		houseuser.setSex(applyUserPushDto.getSex());
		houseuser.setName(applyUserPushDto.getName());
		houseuser.setCreateDate(applyUserPushDto.getCreateDate());
		houseuser.setCheckState(applyUserPushDto.getCheckState());
		houseuser.setCheckOpinion(applyUserPushDto.getCheckOpinion());
		houseuser.setCreateType(applyUserPushDto.getCreateType());
		houseuser.setImageUri(applyUserPushDto.getImageUri());
		houseuser.setPersonType(1);
		houseuser.setNationality(applyUserPushDto.getNationality());
		//绑定小区
		Long residentialOldId = applyUserPushDto.getResidentialId();
		Residential residential = this.residentialService.getOne(new QueryWrapper<>(new Residential()).lambda().eq(Residential::getOldId, residentialOldId));
		if(null != residential){
			houseuser.setRegionCity(residential.getRegionCity());
			houseuser.setRegionArea(residential.getRegionArea());
			houseuser.setRegionProvince(residential.getRegionProvince());

			houseuser.setAgencyId(residential.getAgencyId());
			houseuser.setResidentialName(residential.getName());
			houseuser.setResidentialId(residential.getId());
//			houseuser.setTenantId(residential.getTenantId());
		}else {
			houseuser.setResidentialName("物业系统的小区id："+residentialOldId);
		}

		//绑定楼栋
		Long buildingOldId = applyUserPushDto.getBuildingId();
		Building building = this.buildingService.getOne(new QueryWrapper<>(new Building()).lambda().eq(Building::getOldId, buildingOldId));
		if(null != building){
			houseuser.setBuildingId(building.getId());
			houseuser.setBuildingName(building.getName());
		}else {
			houseuser.setBuildingName("物业系统的楼栋id："+buildingOldId);
		}

		//绑定单元
		Long unitOldId = applyUserPushDto.getUnitId();
		Unit unit = this.unitService.getOne(new QueryWrapper<>(new Unit()).lambda().eq(Unit::getOldId, unitOldId));
		if(null != unit){
			houseuser.setUnitName(unit.getName());
			houseuser.setUnitId(unit.getId());
		}else {
			houseuser.setUnitName("物业系统的单元id："+unitOldId);
		}

		//绑定房间
		Long roomOldId = applyUserPushDto.getRoomId();
		Room room = this.roomService.getOne(new QueryWrapper<>(new Room()).lambda().eq(Room::getOldId, roomOldId));
		if(null != room){
			houseuser.setRoomName(room.getName());
			houseuser.setRoomId(room.getId());
			houseuser.setFloorId(room.getFloorId());
			houseuser.setFloorName(room.getFloorName());
			houseuser.setOrgPosition(room.getOrgPosition());
		}



		return houseuser;
	}

	@PostMapping("/repairSync")
	public R repairSync(@RequestBody EstateRepairPushDto estateRepairPushDto){
		//判断报修是否已存在网格系统
		Long repairOldId = estateRepairPushDto.getId();
		ReportJob isExist = reportJobService.getBaseMapper().selectOne(new QueryWrapper<>(new ReportJob()).lambda().eq(ReportJob::getOldId, repairOldId));

		if(null != isExist){//数据已经存在
			boolean flag = false;//是否修改标志
			//判断可修改的字段是否修改
			if(isExist.getJobStatus().equals(estateRepairPushDto.getHandleStatus())){//处理状态
				isExist.setJobStatus(estateRepairPushDto.getHandleStatus());
				isExist.setHandleTime(estateRepairPushDto.getHandleTime());
				flag = true;
			}

			if(isExist.getEstimateStatus().equals(estateRepairPushDto.getEstimateStatus())){//评价状态
				isExist.setEstimateStatus(estateRepairPushDto.getEstimateStatus());
				isExist.setComment(estateRepairPushDto.getComment());
				flag = true;
			}

			if(flag){
				boolean b = this.reportJobService.updateById(isExist);
				return R.status(b);
			}

		}else{//数据不存在
			ReportJob reportJob = this.buildNewReportJob(estateRepairPushDto);

			Residential residential = residentialService.getById(reportJob.getResidentialId());
			reportJob.setHandler(residential.getPersonName());
			reportJob.setHandlerPhone(residential.getPersonTel());
			reportJob.setHandleTime(new Date());

			boolean save = this.reportJobService.save(reportJob);

			return R.status(save);

		}

		return R.status(true);
	}

	private ReportJob buildNewReportJob(EstateRepairPushDto estateRepairPushDto){
		ReportJob reportJob = new ReportJob();

		reportJob.setReportDetail(estateRepairPushDto.getReportDetail());
		reportJob.setOldId(estateRepairPushDto.getId());
		reportJob.setComment(estateRepairPushDto.getComment());
		reportJob.setHandleTime(estateRepairPushDto.getHandleTime());
		if(estateRepairPushDto.getHandleStatus() != -1){
			reportJob.setJobStatus(estateRepairPushDto.getHandleStatus()+1);
		}else{
			reportJob.setJobStatus(estateRepairPushDto.getHandleStatus());
		}


		//上报人
		Houseuser houseuser = houseuserService.getByOldId(estateRepairPushDto.getUserId().toString());
		if(houseuser != null){
			reportJob.setReportor(houseuser.getName());
	}else {

		reportJob.setReportor(estateRepairPushDto.getUserName());
	}

		reportJob.setReportPhone(estateRepairPushDto.getPhone());
		reportJob.setJobNo(estateRepairPushDto.getRepairNo());

		Residential residential = residentialService.getOne(new QueryWrapper<>(new Residential()).lambda().eq(Residential::getOldId, estateRepairPushDto.getResidentialId()));
		if(residential != null){
			reportJob.setResidentialId(residential.getId());
			reportJob.setResidentialName(residential.getName());
			reportJob.setOrgPosition(residential.getOrgPosition());
			reportJob.setTenantId(residential.getTenantId());
		}else{
			reportJob.setResidentialId(estateRepairPushDto.getResidentialId());
			//* ：标识数字社区找不到物业系统对应的小区数据
			reportJob.setResidentialName(estateRepairPushDto.getResidentialName()+"*");
			//物业系统都是社区没有园区
			residential.setTenantId("000000");
		}

		reportJob.setBeginTime(estateRepairPushDto.getBeginTime());
		reportJob.setEndTime(estateRepairPushDto.getEndTime());
		reportJob.setEstimateStatus(estateRepairPushDto.getEstimateStatus());
		reportJob.setReportPosition(estateRepairPushDto.getReportPosition());
		reportJob.setReportTime(estateRepairPushDto.getCreateTime());
		reportJob.setPic(estateRepairPushDto.getPic());

		return reportJob;
	}


}
