/*
 *      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.enterprise.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.springblade.community.agency.entity.Agency;
import org.springblade.community.agency.service.IAgencyService;
import org.springblade.community.enterprise.entity.Enterprise;
import org.springblade.community.enterprise.service.IEnterpriseService;
import org.springblade.community.enterprise.vo.EnterpriseVO;
import org.springblade.community.enterprise.wrapper.EnterpriseWrapper;
import org.springblade.community.residential.entity.Residential;
import org.springblade.community.residential.service.IResidentialService;
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.modules.system.entity.Dept;
import org.springblade.modules.system.entity.Role;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.IRoleService;
import org.springblade.system.orgposition.entity.OrgPosition;
import org.springblade.system.orgposition.service.IOrgPositionService;
import org.springframework.web.bind.annotation.*;

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

/**
 * 控制器
 *
 * @author BladeX
 * @since 2020-12-08
 */
@RestController
@AllArgsConstructor
@RequestMapping("enterprise/enterprise")
@Api(value = "企业管理", tags = "企业管理")
public class EnterpriseController extends BladeController {

	private IEnterpriseService enterpriseService;
	private IDeptService deptService;
	private IOrgPositionService orgPositionService;
	private IResidentialService residentialService;
	private IAgencyService agencyService;
	private IRoleService roleService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入enterprise")
	public R<EnterpriseVO> detail(Enterprise enterprise) {
		Enterprise detail = enterpriseService.getOne(Condition.getQueryWrapper(enterprise));
		return R.data(EnterpriseWrapper.build(agencyService,residentialService).entityVO(detail));
	}


	/**
	 * 自定义分页
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入enterprise")
	public R<IPage<EnterpriseVO>> page(@RequestParam Map<String, Object> enterprise, Query query, BladeUser bladeUser) {
		String deptId = bladeUser.getDeptId();
		String[] deptIds = deptId.split(",");

		Dept dept = deptService.getById(deptIds[0]);
		if (dept == null){
			return null;
		}
		if (dept.getDeptCategory() == 1){
			String creditCode = null, password = null;
			if (enterprise.get("creditCode") != null) {
				creditCode = enterprise.get("creditCode").toString();
				enterprise.remove("creditCode");
			}
			if (enterprise.get("password") != null) {
				password = enterprise.get("password").toString();
				enterprise.remove("password");
			}
			LambdaQueryWrapper<Enterprise> wrapper = Condition.getQueryWrapper(enterprise, Enterprise.class).lambda();

			OrgPosition orgPosition = orgPositionService.getBaseMapper().selectOne(new QueryWrapper<>(new OrgPosition()).lambda().eq(OrgPosition::getOrgId, dept.getId()));
			if (orgPosition == null){
				return null;
			}
			String[] enterpriseIds = orgPosition.getEnterpriseIds().split(",");
			if (creditCode != null) {
				wrapper.eq(Enterprise::getCreditCode, creditCode);
			}
			if (password != null) {
				wrapper.eq(Enterprise::getPassword, password);
			}
			wrapper.in(Enterprise::getId, enterpriseIds);
			IPage<Enterprise> page = enterpriseService.page(Condition.getPage(query), wrapper);
			return R.data(EnterpriseWrapper.build(agencyService,residentialService).pageVO(page));
		}else {
			LambdaQueryWrapper<Enterprise> wrapper = Condition.getQueryWrapper(enterprise, Enterprise.class).lambda();
			//获取角色信息
			Role role = roleService.getById(bladeUser.getRoleId());
			//非超管，根据tenantId租户id过滤
			if (!role.getRoleAlias().equals("administrator")){
				wrapper.eq(Enterprise::getTenantId,bladeUser.getTenantId());
			}
			IPage<Enterprise> page = enterpriseService.page(Condition.getPage(query), wrapper);
			return R.data(EnterpriseWrapper.build(agencyService,residentialService).pageVO(page));
		}
	}

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入enterprise")
	public R<IPage<EnterpriseVO>> list(@RequestParam Map<String, Object> enterprise, Query query, BladeUser bladeUser) {
		/*临时应急处理，为了避免园区小程序要重新发布版本，暂时获取所有的企业信息， 后台接口改为page接口*/
//		LambdaQueryWrapper<Enterprise> wrapper = Condition.getQueryWrapper(enterprise, Enterprise.class).lambda();
//		IPage<Enterprise> page = enterpriseService.page(Condition.getPage(query), wrapper);
//		return R.data(EnterpriseWrapper.build(agencyService,residentialService).pageVO(page));

		String deptId = bladeUser.getDeptId();
		String[] deptIds = deptId.split(",");

		Dept dept = deptService.getById(deptIds[0]);
		if (dept == null){
			return null;
		}
		if (dept.getDeptCategory() == 1){
			String creditCode = null, password = null;
			if (enterprise.get("creditCode") != null) {
				creditCode = enterprise.get("creditCode").toString();
				enterprise.remove("creditCode");
			}
			if (enterprise.get("password") != null) {
				password = enterprise.get("password").toString();
				enterprise.remove("password");
			}
			LambdaQueryWrapper<Enterprise> wrapper = Condition.getQueryWrapper(enterprise, Enterprise.class).lambda();

			OrgPosition orgPosition = orgPositionService.getBaseMapper().selectOne(new QueryWrapper<>(new OrgPosition()).lambda().eq(OrgPosition::getOrgId, dept.getId()));
			if (orgPosition == null){
				return null;
			}
			String[] enterpriseIds = orgPosition.getEnterpriseIds().split(",");
			if (creditCode != null) {
				wrapper.eq(Enterprise::getCreditCode, creditCode);
			}
			if (password != null) {
				wrapper.eq(Enterprise::getPassword, password);
			}
			wrapper.in(Enterprise::getId, enterpriseIds);
			IPage<Enterprise> page = enterpriseService.page(Condition.getPage(query), wrapper);
			return R.data(EnterpriseWrapper.build(agencyService,residentialService).pageVO(page));
		}else {
			LambdaQueryWrapper<Enterprise> wrapper = Condition.getQueryWrapper(enterprise, Enterprise.class).lambda();
			IPage<Enterprise> page = enterpriseService.page(Condition.getPage(query), wrapper.eq(Enterprise::getTenantId, bladeUser.getTenantId()));
			return R.data(EnterpriseWrapper.build(agencyService,residentialService).pageVO(page));
		}
	}

	/**
	 * 园区企业列表
	 */
	@GetMapping("/enterpriseList")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "园区企业列表", notes = "传入enterprise")
	public R<IPage<EnterpriseVO>> enterpriseList(@RequestParam Map<String, Object> enterprise, Query query, BladeUser bladeUser) {
		String deptId = bladeUser.getDeptId();
		String[] deptIds = deptId.split(",");
		LambdaQueryWrapper<Enterprise> wrapper = Condition.getQueryWrapper(enterprise, Enterprise.class).lambda();
		for (int i = 0; i < deptIds.length; i++) {
			//是否公司
			Dept dept = deptService.getById(deptIds[i]);
			if (dept.getDeptCategory() == 1) {
				OrgPosition orgPosition = orgPositionService.getBaseMapper().selectOne(new QueryWrapper<>(new OrgPosition()).lambda().eq(OrgPosition::getOrgId, deptIds[i]));
				String[] enterpriseIds = orgPosition.getEnterpriseIds().split(",");

				wrapper.in(Enterprise::getId, enterpriseIds);
				IPage<Enterprise> page = enterpriseService.page(Condition.getPage(query), wrapper);
				return R.data(EnterpriseWrapper.build(agencyService,residentialService).pageVO(page));
			}else{
				IPage<Enterprise> page = enterpriseService.page(Condition.getPage(query), wrapper.eq(Enterprise::getTenantId, bladeUser.getTenantId()));
				return R.data(EnterpriseWrapper.build().pageVO(page));
			}
			//园区企业列表
		}
		return R.data(null);
	}

	/**
	 * 分页
	 */
	@GetMapping("/getList")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "getList分页", notes = "传入enterprise")
	public R getList() {
		List<Enterprise> list = enterpriseService.list();
		return R.data(list);
	}


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

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

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入enterprise")
	public R submit(@Valid @RequestBody Enterprise enterprise) {
		Assert.notNull(enterprise.getResidentialId(), "分区归属为空，请先选择归属分区！！");

		Residential residential = residentialService.getById(enterprise.getResidentialId());
		Assert.notNull(residential, "找不到对应的分区归属");
		enterprise.setAgencyId(residential.getAgencyId());

		if (enterprise.getId() == null){
			enterpriseService.save(enterprise);
		}
		enterprise.setOrgPosition(residential.getOrgPosition() + "/" + enterprise.getId());

		return R.status(enterpriseService.updateById(enterprise));
	}


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


}
