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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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 javax.validation.Valid;

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.residential.entity.Residential;
import org.springblade.community.residential.service.IResidentialService;
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.party.branch.dto.BranchDTO;
import org.springblade.party.member.entity.Member;
import org.springblade.party.member.service.IMemberService;
import org.springblade.party.relation.entity.BranchRelation;
import org.springblade.party.relation.service.IBranchRelationService;
import org.springblade.system.orgposition.service.IOrgPositionService;
import org.springblade.utils.QueryWrapperUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.party.branch.entity.Branch;
import org.springblade.party.branch.vo.BranchVO;
import org.springblade.party.branch.wrapper.BranchWrapper;
import org.springblade.party.branch.service.IBranchService;
import org.springblade.core.boot.ctrl.BladeController;

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

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

	private IBranchService branchService;
	private IBranchRelationService branchRelationService;
	private IOrgPositionService orgPositionService;
	private IAgencyService agencyService;
	private IResidentialService residentialService;
	private IEnterpriseService enterpriseService;
	private IMemberService memberService;

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

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

		LambdaQueryWrapper<Agency> agencyLambdaQueryWrapper = new QueryWrapperUtil<Agency>().getBasicQueryWrapper(Agency::getOrgPosition, new Agency(), bladeUser, orgPositionService);
		List<Long> agencyIds = agencyService.getBaseMapper().selectList(agencyLambdaQueryWrapper).stream().map(Agency::getId).collect(Collectors.toList());

		LambdaQueryWrapper<Residential> residentialLambdaQueryWrapper = new QueryWrapperUtil<Residential>().getBasicQueryWrapper(Residential::getOrgPosition, new Residential(), bladeUser, orgPositionService);
		List<Long> residentialIds = residentialService.getBaseMapper().selectList(residentialLambdaQueryWrapper).stream().map(Residential::getId).collect(Collectors.toList());

		LambdaQueryWrapper<Enterprise> enterpriseLambdaQueryWrapper = new QueryWrapperUtil<Enterprise>().getBasicQueryWrapper(Enterprise::getOrgPosition, new Enterprise(), bladeUser, orgPositionService);
		List<Long> enterpriseIds = enterpriseService.getBaseMapper().selectList(enterpriseLambdaQueryWrapper).stream().map(Enterprise::getId).collect(Collectors.toList());

		List<BranchRelation> relationList = branchRelationService.getBaseMapper().selectList(new QueryWrapper<>(new BranchRelation()).lambda()
			.in(BranchRelation::getResourceId, agencyIds)
			.or().in(BranchRelation::getResourceId, residentialIds)
			.or().in(BranchRelation::getResourceId, enterpriseIds));

		if(relationList.size()>0){
			IPage<Branch> pages = branchService.page(Condition.getPage(query), Condition.getQueryWrapper(branch, Branch.class).lambda().in(Branch::getId, relationList.stream().map(BranchRelation::getBranchId).collect(Collectors.toList())));

			return R.data(BranchWrapper.build(agencyService,residentialService,enterpriseService).pageVO(pages));
		}else {
			IPage<BranchVO> page = new Page<>();
			page.setCurrent(1);
			page.setTotal(0);
			page.setSize(10);
			page.setRecords(new ArrayList<>());
			page.setPages(0);
			return R.data(page);
		}

	}


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

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

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

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入branch")
	public R submit(@Valid @RequestBody BranchDTO branch,BladeUser bladeUser) {
		if(branchService.saveOrUpdate(branch)){
			String[] resouceIds = branch.getResourceIds().split(",");
			for(String resouceId : resouceIds){
				BranchRelation branchRelation = new BranchRelation();
				branchRelation.setBranchId(branch.getId());
				branchRelation.setResourceId(Long.valueOf(resouceId));
				branchRelation.setResourceType(branch.getResourceType());
				branchRelation.setTenantId(bladeUser.getTenantId());
				branchRelationService.saveOrUpdate(branchRelation);
			}
			return R.status(true);
		}else{
			return R.status(false);
		}

	}


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


	/**
	 * 园区小程序员工获取党支部列表
	 *
	 */
	@GetMapping("/app/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入branch")
	public R<List<BranchVO>> appList(Long enterpriseStaffId) {

		List<Member> members = memberService.getBaseMapper().selectList(new QueryWrapper<>(new Member()).lambda().eq(Member::getPersonType, 2).eq(Member::getPersonId, enterpriseStaffId));
		if(members.size()>0){
			List<Branch> branches = branchService.getBaseMapper().selectList(new QueryWrapper<>(new Branch()).lambda().in(Branch::getId, members.stream().map(Member::getBranchId).collect(Collectors.toList())));
			return R.data(BranchWrapper.build(agencyService,residentialService,enterpriseService).listVO(branches));
		}

		return R.data(new ArrayList<>());
	}

	/**
	 * 园区小程序获取园区内的党支部列表
	 *
	 */
	@GetMapping("/app/getListForAgency")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入branch")
	public R<List<Branch>> getListForAgency(BladeUser bladeUser) {

		LambdaQueryWrapper<Agency> agencyLambdaQueryWrapper = new QueryWrapperUtil<Agency>().getBasicQueryWrapper(Agency::getOrgPosition, new Agency(), bladeUser, orgPositionService);
		List<Long> agencyIds = agencyService.getBaseMapper().selectList(agencyLambdaQueryWrapper).stream().map(Agency::getId).collect(Collectors.toList());

		LambdaQueryWrapper<Residential> residentialLambdaQueryWrapper = new QueryWrapperUtil<Residential>().getBasicQueryWrapper(Residential::getOrgPosition, new Residential(), bladeUser, orgPositionService);
		List<Long> residentialIds = residentialService.getBaseMapper().selectList(residentialLambdaQueryWrapper).stream().map(Residential::getId).collect(Collectors.toList());

		LambdaQueryWrapper<Enterprise> enterpriseLambdaQueryWrapper = new QueryWrapperUtil<Enterprise>().getBasicQueryWrapper(Enterprise::getOrgPosition, new Enterprise(), bladeUser, orgPositionService);
		List<Long> enterpriseIds = enterpriseService.getBaseMapper().selectList(enterpriseLambdaQueryWrapper).stream().map(Enterprise::getId).collect(Collectors.toList());

		List<BranchRelation> relationList = branchRelationService.getBaseMapper().selectList(new QueryWrapper<>(new BranchRelation()).lambda()
			.in(BranchRelation::getResourceId, agencyIds)
			.or().in(BranchRelation::getResourceId, residentialIds)
			.or().in(BranchRelation::getResourceId, enterpriseIds));

		if(relationList.size()>0){
			List<Branch> branches = branchService.list(new QueryWrapper<>(new Branch()).lambda().in(Branch::getId, relationList.stream().map(BranchRelation::getBranchId).collect(Collectors.toList())));
			return R.data(branches);
		}

		return R.data(new ArrayList<>());

	}


}
