/*
 *      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.community.car.controller;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.apache.logging.log4j.util.Strings;
import org.springblade.community.agency.entity.Agency;
import org.springblade.community.agency.service.IAgencyService;
import org.springblade.community.car.entity.Car;
import org.springblade.community.car.service.ICarService;
import org.springblade.community.car.vo.CarVO;
import org.springblade.community.car.wrapper.CarWrapper;
import org.springblade.community.residential.entity.Residential;
import org.springblade.community.residential.service.IResidentialService;
import org.springblade.community.staff.entity.EnterpriseStaff;
import org.springblade.community.staff.service.IEnterpriseStaffService;
import org.springblade.core.boot.ctrl.BladeController;
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.system.orgposition.service.IOrgPositionService;
import org.springblade.system.tenanttype.entity.TenantType;
import org.springblade.system.tenanttype.service.ITenantTypeService;
import org.springblade.utils.QueryWrapperUtil;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

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

	private ICarService carService;
	private IOrgPositionService orgPositionService;
	private IResidentialService residentialService;
	private IAgencyService agencyService;
	private IEnterpriseStaffService enterpriseStaffService;
	private ITenantTypeService tenantTypeService;


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

	/**
	 * 分页 车辆信息
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入car")
	public R<IPage<CarVO>> list(@RequestParam Map<String, Object> car, Query query, BladeUser bladeUser) {

		LambdaQueryWrapper<Car> wrapper = new QueryWrapperUtil<Car>().getBasicQueryWrapperByMap(Car::getOrgPosition, car, new Car(), bladeUser, orgPositionService);
		IPage<Car> pages = carService.page(Condition.getPage(query), wrapper.eq(Car::getTenantId, bladeUser.getTenantId()));
		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) {
		int tenantType = 1;//租户类型： 0是社区
		if (car.getResidentialId() != null) {
			Residential residential = residentialService.getById(car.getResidentialId());
			Assert.notNull(residential, "找不到车对应的小区");
			car.setOrgPosition(residential.getOrgPosition());
			car.setTenantId(residential.getTenantId());
			TenantType type = tenantTypeService.getByTenantId(residential.getTenantId());
			Assert.notNull(type,"租户类型为空");
			tenantType = type.getTenantType();
		} else {
			Assert.notNull(car.getAgencyId(), "车所属社区必选");
			Agency agency = agencyService.getById(car.getAgencyId());
			Assert.notNull(agency, "找不到车对应的社区");
			car.setOrgPosition(agency.getOrgPosition());
			car.setTenantId(agency.getTenantId());
			TenantType type = tenantTypeService.getByTenantId(agency.getTenantId());
			Assert.notNull(type,"租户类型为空");
			tenantType = type.getTenantType();
		}

		Assert.notNull(car.getPersonId(),"车主id不能为空");

		if(tenantType == 1){//的车主为企业员工
			EnterpriseStaff enterpriseStaff = enterpriseStaffService.getById(car.getPersonId());
			Assert.notNull(enterpriseStaff,"找不到该员工");
			car.setPersonName(enterpriseStaff.getRealName());
			car.setPersonPhone(enterpriseStaff.getPhone());
			car.setEnterpriseId(enterpriseStaff.getEnterpriseId());
		}else{//社区的车主为住户

		}


		return R.status(carService.save(car));
	}

	/**
	 * 修改 车辆信息
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入car")
	public R update(@Valid @RequestBody Car car) {
		if (Strings.isNotBlank(car.getResidentialId().toString())) {
			Residential residential = residentialService.getById(car.getResidentialId());
			Assert.notNull(residential, "找不到车对应的小区");
			car.setOrgPosition(residential.getOrgPosition());
		} else {
			Assert.notNull(car.getAgencyId(), "车所属社区必选");
			Agency agency = agencyService.getById(car.getAgencyId());
			Assert.notNull(agency, "找不到车对应的社区");
			car.setOrgPosition(agency.getOrgPosition());
		}
		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;//租户类型：0是社区
		if (car.getResidentialId() != null) {
			Residential residential = residentialService.getById(car.getResidentialId());
			Assert.notNull(residential, "找不到车对应的小区");
			car.setOrgPosition(residential.getOrgPosition());
			car.setTenantId(residential.getTenantId());
			TenantType type = tenantTypeService.getByTenantId(residential.getTenantId());
			Assert.notNull(type,"租户类型为空");
			tenantType = type.getTenantType();
		} else {
			Assert.notNull(car.getAgencyId(), "车所属社区必选");
			Agency agency = agencyService.getById(car.getAgencyId());
			Assert.notNull(agency, "找不到车对应的社区");
			car.setOrgPosition(agency.getOrgPosition());
			car.setTenantId(agency.getTenantId());
			TenantType type = tenantTypeService.getByTenantId(agency.getTenantId());
			Assert.notNull(type,"租户类型为空");
			tenantType = type.getTenantType();
		}

		/*Assert.notNull(car.getPersonId(),"车主id不能为空");

		if(tenantType == 1){//车主为企业员工
			EnterpriseStaff enterpriseStaff = enterpriseStaffService.getById(car.getPersonId());
			Assert.notNull(enterpriseStaff,"找不到该员工");
			car.setPersonName(enterpriseStaff.getRealName());
			car.setPersonPhone(enterpriseStaff.getPhone());
			car.setEnterpriseId(enterpriseStaff.getEnterpriseId());
		}else{//社区的车主为住户

		}*/
		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)));
	}

	/**
	 * 获取车主车辆信息
	 */
	@GetMapping("/getCarByPersonId")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "分页", notes = "传入car")
	public R getCarByPersonId(Long personId) {
		List<Car> cars = carService.getCarByPersonId(personId);
		return R.data(cars);
	}

	/**
	 * 小程序获取车辆列表
	 *
	 * @param car  车辆
	 *
	 *             {
	 *                 selectType 查询类型(必填)   1-管理查询   2-企业管理员查询 3-员工查询
	 *             		enterpriseId     企业id（企业管理员请求此接口必填）
	 *             		personId     车主id（员工请求此接口时传员工id）
	 *          	}
	 */
	@GetMapping("/app/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, orgPositionService);
			wrapper.eq(Car::getTenantId, bladeUser.getTenantId());
		}

		if (type == 2){//企业管理员查询
			//查询该企业的所有员工
			Assert.notNull(car.get("enterpriseId"),"enterpriseId不能为空");
			List<EnterpriseStaff> enterpriseStaffs = enterpriseStaffService.getBaseMapper().selectList(new QueryWrapper<>(new EnterpriseStaff()).lambda().eq(EnterpriseStaff::getEnterpriseId, car.get("enterpriseId").toString()));
			List<Long> enterpriseStaffIds = enterpriseStaffs.stream().map(EnterpriseStaff::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));
	}

}
