/*
 *      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.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 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.community.entity.Agency;
import org.springblade.community.entity.Residential;
import org.springblade.community.feign.IAgencyClient;
import org.springblade.community.feign.IResidentialClient;
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.Enterprise;
import org.springblade.enterprise.feign.IEnterpriseClient;
import org.springblade.party.dto.BranchDTO;
import org.springblade.party.entity.BranchRelation;
import org.springblade.party.entity.PartyMember;
import org.springblade.party.service.IBranchRelationService;
import org.springblade.party.service.IPartyMemberService;
import org.springblade.system.expand.feign.IOrgPositionClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.party.entity.Branch;
import org.springblade.party.vo.BranchVO;
import org.springblade.party.wrapper.BranchWrapper;
import org.springblade.party.service.IBranchService;
import org.springblade.core.boot.ctrl.BladeController;

import java.util.*;
import java.util.stream.Collectors;

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

	private IBranchService branchService;
	private IBranchRelationService branchRelationService;
	private IAgencyClient agencyClient;
	private IResidentialClient residentialClient;
	private IEnterpriseClient enterpriseClient;
	private IPartyMemberService memberService;
	private IOrgPositionClient orgPositionClient;

	/**
	 * 详情
	 */
	@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(branchRelationService,residentialClient,agencyClient,enterpriseClient).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<Residential> residentialLambdaQueryWrapper = new QueryWrapperUtil<Residential>().getBasicQueryWrapper(Residential::getOrgPosition, new Residential(), bladeUser,orgPositionClient);
//		List<Long> residentialIds = residentialClient.list(map).stream().map(Residential::getId).collect(Collectors.toList());

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

		//获取符合条件的园区、小区、企业id
		List<Long> agencyIds = agencyClient.listForOrg(new Object[]{new Agency(), bladeUser}).stream().map(Agency::getId).collect(Collectors.toList());
		List<Long> residentialIds = residentialClient.listForOrg(new Object[]{new Residential(), bladeUser}).stream().map(Residential::getId).collect(Collectors.toList());
		List<Long> enterpriseIds = enterpriseClient.listForOrg(Arrays.asList(new Object[]{new Enterprise(), bladeUser})).stream().map(Enterprise::getId).collect(Collectors.toList());
		//筛选与上面id关联的资源,enterpriseIds可能为空
		List<BranchRelation> relationList = null;
		if (enterpriseIds.size()!=0){
			 relationList = branchRelationService.getBaseMapper().selectList(new QueryWrapper<>(new BranchRelation()).lambda()
				.in(BranchRelation::getResourceId, agencyIds)
				.or().in(BranchRelation::getResourceId, residentialIds)
				.or().in(BranchRelation::getResourceId, enterpriseIds));
		}else {
			 relationList = branchRelationService.getBaseMapper().selectList(new QueryWrapper<>(new BranchRelation()).lambda()
				.in(BranchRelation::getResourceId, agencyIds)
				.or().in(BranchRelation::getResourceId, residentialIds));
		}

		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(branchRelationService,residentialClient,agencyClient,enterpriseClient).pageVO(pages));
		}else {
//			IPage<Branch> pages = branchService.page(Condition.getPage(query), Condition.getQueryWrapper(branch,Branch.class));
//			return R.data(BranchWrapper.build().pageVO(pages));
			IPage<BranchVO> page = new Page<>();
			page.setCurrent(query.getCurrent());
			page.setTotal(0);
			page.setSize(query.getSize());
			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(",");
//			String[] residentialIds = branch.getResidentialIds().split(",");
//			Residential residential = new Residential();
//			residential.setId(branch.setResidentialIds());
//			Residential residential = residentialClient.detail()
//			if ()
			if(resouceIds != null && resouceIds.length > 0){
				branchRelationService.deleteByBranchId(branch.getId());
			}
			for(String resourceId : resouceIds){
				BranchRelation branchRelation = new BranchRelation();
				branchRelation.setBranchId(branch.getId());
				branchRelation.setResourceId(Long.valueOf(resourceId));
				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<PartyMember> memberParties = memberService.getBaseMapper().selectList(new QueryWrapper<>(new PartyMember()).lambda().eq(PartyMember::getPersonType, 2).eq(PartyMember::getPersonId, enterpriseStaffId));
		if(memberParties.size()>0){
			List<Branch> branches = branchService.getBaseMapper().selectList(new QueryWrapper<>(new Branch()).lambda().in(Branch::getId, memberParties.stream().map(PartyMember::getBranchId).collect(Collectors.toList())));
			return R.data(BranchWrapper.build(branchRelationService,residentialClient,agencyClient,enterpriseClient).listVO(branches));
		}

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

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

		List<Long> agencyIds = agencyClient.listForOrg(new Object[]{new Agency(), bladeUser}).stream().map(Agency::getId).collect(Collectors.toList());
		List<Long> residentialIds = residentialClient.listForOrg(new Object[]{new Residential(), bladeUser}).stream().map(Residential::getId).collect(Collectors.toList());
		List<Long> enterpriseIds = enterpriseClient.listForOrg(Arrays.asList(new Object[]{new Enterprise(), bladeUser})).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<>());

	}


}
