/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.estate.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.lettuce.core.models.role.RedisSentinelInstance;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;
import javax.validation.Valid;

import org.checkerframework.checker.units.qual.A;
import org.springblade.common.constant.CommonConstant;
import org.springblade.community.entity.Agency;
import org.springblade.community.entity.Residential;
import org.springblade.community.feign.IAgencyClient;
import org.springblade.community.feign.IResidentialClient;
import org.springblade.community.vo.ResidentialVO;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.enterprise.entity.Staff;
import org.springblade.enterprise.feign.IStaffClient;
import org.springblade.enterprise.vo.StaffVO;
import org.springblade.estate.entity.AccessRecord;
import org.springblade.person.entity.HouseUser;
import org.springblade.person.feign.IHouseUserClient;
import org.springblade.person.vo.HouseUserVO;
import org.springblade.system.expand.entity.TenantType;
import org.springblade.system.expand.feign.IOrgPositionClient;
import org.springblade.system.expand.feign.ITenantTypeClient;
import org.springblade.system.expand.util.QueryWrapperUtil;
import org.springblade.system.expand.vo.TenantTypeVO;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.estate.entity.Car;
import org.springblade.estate.vo.CarVO;
import org.springblade.estate.wrapper.CarWrapper;
import org.springblade.estate.service.ICarService;
import org.springblade.core.boot.ctrl.BladeController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 车辆信息 控制器
 *
 * @author BladeX
 * @since 2021-03-30
 */
@RestController
@AllArgsConstructor
@RequestMapping("/car")
@Api(value = "车辆信息", tags = "车辆信息接口")
public class CarController extends BladeController {

	private final ICarService carService;
	private final IOrgPositionClient orgPositionClient;
	private final IResidentialClient residentialClient;
	private final IStaffClient staffClient;
	private final ITenantTypeClient tenantTypeClient;
	private final IHouseUserClient houseUserClient;
	private final IAgencyClient agencyClient;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入car")
	public R<CarVO> detail(Car car) {
		Car detail = carService.getOne(Condition.getQueryWrapper(car));
		return R.data(CarWrapper.build().entityVO(detail));
	}

	/**
	 * 分页 车辆信息
	 * @param car
	 * @param query
	 * @param bladeUser
	 * @return
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入car")
	public R<IPage<CarVO>> list(@RequestParam Map<String, Object> car, Query query, BladeUser bladeUser) {
		Integer auditStatus = Convert.toInt(car.get("auditStatus"));
		if (auditStatus != null) {
			car.remove("auditStatus");
		}
		LambdaQueryWrapper<Car> carLambdaQueryWrapper = new QueryWrapperUtil<Car>().getBasicQueryWrapperByMap(Car::getOrgPosition, car, new Car(), bladeUser, orgPositionClient);
		IPage<Car> pages = carService.page(Condition.getPage(query), carLambdaQueryWrapper.eq(Car::getAuditStatus, auditStatus));
		return R.data(CarWrapper.build().pageVO(pages));
	}


	/**
	 * 自定义分页 车辆信息
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入car")
	public R<IPage<CarVO>> page(CarVO car, Query query) {
		IPage<CarVO> pages = carService.selectCarPage(Condition.getPage(query), car);
		return R.data(pages);
	}

	/**
	 * 新增 车辆信息
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入car")
	public R save(@Valid @RequestBody Car car) {
		return R.status(carService.save(car));
	}

	/**
	 * 修改 车辆信息
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入car")
	public R update(@Valid @RequestBody Car car) {
		return R.status(carService.updateById(car));
	}

	/**
	 * 新增或修改 车辆信息
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入car")
	public R submit(@Valid @RequestBody Car car) {
		int tenantType = 1;//租户类型：默认为1-园区                0是园区
		if (car.getResidentialId() != null) {
			Residential search = new Residential();
			search.setId(car.getResidentialId());
			Residential residential = residentialClient.detail(search);
			Assert.notNull(residential, "找不到车对应的小区");
			car.setOrgPosition(residential.getOrgPosition());
			car.setTenantId(residential.getTenantId());
			car.setAgencyId(residential.getAgencyId());


		} else {
			Assert.notNull(car.getAgencyId(), "车所属园区/园区必选");
			Agency search = new Agency();
			search.setId(car.getAgencyId());
			Agency agency = agencyClient.detail(search);
			Assert.notNull(agency, "找不到车对应的园区/园区");
			car.setOrgPosition(agency.getOrgPosition());
			car.setTenantId(agency.getTenantId());

		}
//		Assert.notNull(car.getPersonId(),"车主id不能为空");
		TenantType search = new TenantType();
		search.setTenantId(car.getTenantId());
		TenantTypeVO tenantTypeVO = tenantTypeClient.detail(search);
		tenantType = tenantTypeVO.getTenantType();
		if(tenantType == 1){//园区的车主为企业员工
			if (car.getPersonId()!=null){
				Staff searchEs = new Staff();
				searchEs.setId(car.getPersonId());
				Staff enterpriseStaff = staffClient.detail(searchEs);
				Assert.notNull(enterpriseStaff,"找不到该员工");
				car.setPersonName(enterpriseStaff.getRealName());
				car.setPersonPhone(enterpriseStaff.getPhone());
				car.setEnterpriseId(enterpriseStaff.getEnterpriseId());
			}
		}else{//园区的车主为住户
			if (car.getPersonId()!=null){
				HouseUser searchHU = new HouseUser();
				searchHU.setId(car.getPersonId());
				HouseUserVO houseUserVO = houseUserClient.detail(searchHU);
				car.setPersonName(houseUserVO.getName());
				car.setPersonPhone(houseUserVO.getPhone());
			}
		}
		return R.status(carService.saveOrUpdate(car));
	}


	/**
	 * 删除 车辆信息
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(carService.deleteLogic(Func.toLongList(ids)));
	}


	/**
	 * 园区小程序获取车辆列表
	 *
	 * @param car  车辆
	 *
	 *             {
	 *                 selectType 查询类型(必填)   1-园区管理查询   2-企业管理员查询 3-员工查询
	 *             		enterpriseId     企业id（企业管理员请求此接口必填）
	 *             		personId     车主id（员工请求此接口时传员工id）
	 *          	}
	 */
	@GetMapping("/parkapp/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = " 园区小程序获取车辆列表", notes = "传入car")
	public R<IPage<Car>> appList(@RequestParam Map<String, Object> car, Query query, BladeUser bladeUser) {
		Assert.notNull(car.get("selectType"),"selectType不能为空");
		Integer type = Integer.valueOf(car.get("selectType").toString());
		car.remove("selectType");
		Integer auditStatus = null;
		if(car.get("auditStatus") != null){//审核状态必须等值查询  避免 状态1查询-1
			auditStatus = Integer.valueOf(car.get("auditStatus").toString());
			car.remove("auditStatus");
		}

		LambdaQueryWrapper<Car> wrapper = null;
		if (type == 1) {//园区管理查询
			wrapper = new QueryWrapperUtil<Car>().getBasicQueryWrapperByMap(Car::getOrgPosition, car, new Car(), bladeUser, orgPositionClient);
			wrapper.eq(Car::getTenantId, bladeUser.getTenantId());
		}

		if (type == 2){//企业管理员查询
			//查询该企业的所有员工
			Assert.notNull(car.get("enterpriseId"),"enterpriseId不能为空");
			Staff search = new Staff();
			search.setEnterpriseId(Long.valueOf(car.get("enterpriseId").toString()));
			List<StaffVO> enterpriseStaffs = staffClient.list(search);
			List<Long> enterpriseStaffIds = enterpriseStaffs.stream().map(Staff::getId).collect(Collectors.toList());
			wrapper = Condition.getQueryWrapper(car,Car.class).lambda().in(Car::getPersonId, enterpriseStaffIds);
		}

		if(type == 3){//员工查询
			Assert.notNull(car.get("personId"),"员工id为空");
			wrapper = Condition.getQueryWrapper(car,Car.class).lambda();
		}

		if(auditStatus != null){
			wrapper.eq(Car::getAuditStatus,auditStatus);
		}
		IPage<Car> pages = carService.page(Condition.getPage(query), wrapper.orderByDesc(Car::getCreateTime));
		return R.data(pages);
	}


	/**
	 * 审核
	 * car
	 * {
	 *     id   车辆id
	 *     auditStatus: 审核状态：-1 审核不通过  0-待审核 1-审核通过
	 *     auditOpinion: 审核意见
	 * }
	 */
	@PostMapping("/audit")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "审核")
	public R audit(@RequestBody Car car) {
		Assert.notNull(car.getId(),"carId不能为空");
		Car oldEntity = carService.getById(car.getId());
		Assert.notNull(oldEntity,"找不到车辆记录");
		oldEntity.setAuditStatus(car.getAuditStatus());
		oldEntity.setAuditOpinion(car.getAuditOpinion());

		return R.status(carService.updateById(oldEntity));
	}

	/**
	 * 车辆记录初始化，关联新的小区和图片去除前缀
	 */
	@PostMapping("/initData")

	public R initData() {
		long beginTime = System.currentTimeMillis();
		List<Car> carList = this.carService.getBaseMapper().selectList(new QueryWrapper<>(new Car()));
		carList.forEach(car -> {
			if (car.getCarImg() != null)
				car.setCarImg(car.getCarImg().replace("http://139.9.103.171:1888/miniofile/", ""));
			if(car.getVehicleDrivingLicense1() != null){
				car.setVehicleDrivingLicense1(car.getVehicleDrivingLicense1().replace("http://139.9.103.171:1888/miniofile/", ""));
			}
			if(car.getVehicleDrivingLicense2() != null){
				car.setVehicleDrivingLicense2(car.getVehicleDrivingLicense2().replace("http://139.9.103.171:1888/miniofile/", ""));
			}
			if(car.getResidentialId() != null){
				Residential searchResidential = new Residential();
				searchResidential.setGridId(car.getResidentialId());

					ResidentialVO detail = residentialClient.detail(searchResidential);
					if (detail != null) {
						car.setResidentialId(detail.getId());
						car.setOrgPosition(detail.getOrgPosition());
						car.setAgencyId(detail.getAgencyId());

					}
			}

			carService.updateById(car);

		});
		long endTime = System.currentTimeMillis();
		return R.data("耗时：" + (endTime - beginTime) / 1000 + "秒");
	}


}
