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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
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.springblade.common.constant.CommonConstant;
import org.springblade.community.entity.Building;
import org.springblade.community.entity.Residential;
import org.springblade.community.service.IBuildingService;
import org.springblade.community.service.IResidentialService;
import org.springblade.community.vo.AgencyInfoVO;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.enterprise.feign.IEnterpriseClient;
import org.springblade.enterprise.feign.IStaffClient;
import org.springblade.estate.feign.IServerUserClient;
import org.springblade.person.entity.HouseUser;
import org.springblade.person.feign.IHouseUserClient;
import org.springblade.system.expand.entity.TenantType;
import org.springblade.system.expand.feign.IConfClient;
import org.springblade.system.expand.feign.ITenantTypeClient;
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.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.community.entity.Agency;
import org.springblade.community.vo.AgencyVO;
import org.springblade.community.wrapper.AgencyWrapper;
import org.springblade.community.service.IAgencyService;
import org.springblade.core.boot.ctrl.BladeController;

import java.util.List;
import java.util.Map;

/**
 * 控制器
 *
 * @author BladeX
 * @since 2021-03-29
 */
@RestController
@AllArgsConstructor
@RequestMapping("/agency")
@Api(value = "", tags = "接口")
public class AgencyController extends BladeController {

	private final IAgencyService agencyService;
	private final IConfClient confClient;
	private final IBuildingService buildingService;
	private final IStaffClient staffClient;
	private final IServerUserClient serverUserClient;
	private final IEnterpriseClient enterpriseClient;
	private final ITenantTypeClient typeClient;
	private final IResidentialService residentialService;
	private final IHouseUserClient houseUserClient;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入agency")
	public R<AgencyVO> detail(Agency agency) {
		Agency detail = agencyService.getOne(Condition.getQueryWrapper(agency));
		return R.data(AgencyWrapper.build(confClient).entityVO(detail));
	}

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入agency")
	public R<IPage<AgencyVO>> list(@RequestParam Map<String, Object> agency, Query query, BladeUser bladeUser) {
//		LambdaQueryWrapper<Agency> basicQueryWrapper = new QueryWrapperUtil<Agency>().getBasicQueryWrapperByMap(Agency::getOrgPosition, agency,new Agency(), bladeUser, orgPositionClient);
//		basicQueryWrapper.ne(Agency::getTenantId, "000000");
		IPage<Agency> pages = agencyService.page(Condition.getPage(query), Condition.getQueryWrapper(agency, Agency.class));
		return R.data(AgencyWrapper.build(confClient).pageVO(pages));
	}


	/**
	 * 自定义分页
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入agency")
	public R<IPage<AgencyVO>> page(AgencyVO agency, Query query) {
		IPage<AgencyVO> pages = agencyService.selectAgencyPage(Condition.getPage(query), agency);
		return R.data(pages);
	}

	/**
	 * 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入agency")
	public R save(@Valid @RequestBody Agency agency) {
		return R.status(agencyService.save(agency));
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入agency")
	public R update(@Valid @RequestBody Agency agency) {
		return R.status(agencyService.updateById(agency));
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入agency")
	public R submit(@Valid @RequestBody Agency agency) {
		Assert.notNull(agency.getRegionProvince(), "园区所属省份不能为空");
		Assert.notNull(agency.getRegionCity(), "园区所属市不能为空");
		Assert.notNull(agency.getRegionArea(), "园区所属区不能为空");
		Assert.notNull(agency.getRegionStreet(), "园区所属街道不能为空");
		agency.setPic(confClient.removePrefix(agency.getPic()));
		return R.status(agencyService.saveOrUpdateAgency(agency));
	}


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


	/**
	 * 【web端】智能运营平台园区信息
	 */
	@GetMapping("/agencyInfo")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入agency")
	public R<AgencyInfoVO> info(BladeUser bladeUser) {
		String tenantId = bladeUser.getTenantId();
		List<Agency> agencyList = agencyService.list(Condition.getQueryWrapper(new Agency()).lambda().eq(Agency::getTenantId, tenantId).last("limit 1"));
		Assert.isFalse(CollUtil.isEmpty(agencyList), "找不到信息");
		//园区/社区
		Agency agency = agencyList.get(0);
		Long agencyId = agency.getId();
		AgencyInfoVO agencyInfoVO = new AgencyInfoVO();
		BeanUtil.copyProperties(agency, agencyInfoVO);
		//园区/社区统计楼栋数
		int buildingCount = buildingService.count(Condition.getQueryWrapper(new Building()).lambda().eq(Building::getAgencyId, agencyId));
		agencyInfoVO.setBuildingCount(buildingCount);
		//判断是园区还是社区
		TenantType tenantType = new TenantType();
		tenantType.setTenantId(tenantId);
		TenantTypeVO tenantTypeVO = typeClient.detail(tenantType);
		if (true) {
			//社区,统计入驻社区，居民数
			int residentialCount = residentialService.count(Condition.getQueryWrapper(new Residential()).lambda().eq(Residential::getAgencyId, agencyId));
			agencyInfoVO.setResidentialCount(residentialCount);
			HouseUser houseUser = new HouseUser();
			houseUser.setAgencyId(agencyId);
			int houseUseCount = houseUserClient.count(houseUser);
			agencyInfoVO.setHouseUserCount(houseUseCount);
			return R.data(agencyInfoVO);
		}
		//园区统计入驻企业，办公人数
		//办公人员=企业员工+服务人员
		Integer staffCount = staffClient.count(agency.getTenantId());
		Integer serverUserCount = serverUserClient.count(agency.getTenantId());
		Integer officeCount = staffCount + serverUserCount;
		//企业数量
		Integer companyCount = enterpriseClient.count(agency.getTenantId());

		agencyInfoVO.setOfficeCount(officeCount);
		agencyInfoVO.setCompanyCount(companyCount);

		return R.data(agencyInfoVO);
	}


}
