package org.springblade.party.feign;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiParam;
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.service.IEnterpriseService;
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 org.springblade.party.entity.Branch;
import org.springblade.party.vo.BranchVO;
import org.springblade.party.wrapper.BranchWrapper;
import org.springblade.party.service.IBranchService;

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

/**
 *  client
 *
 * @author lianghanqiang
 * @since 2021-03-30
 */

@AllArgsConstructor
@RestController
@RequestMapping("/feign/branch")

public class BranchClient implements IBranchClient {

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

        /**
     * 详情
     */
    @Override
    @GetMapping("/detail")
    public BranchVO detail(Branch branch) {
        Branch detail = branchService.getOne(Condition.getQueryWrapper(branch));
        return BranchWrapper.build(branchRelationService,residentialClient,agencyClient,enterpriseClient).entityVO(detail);
        }

    /**
     * 查询
     */
    @Override
    @GetMapping("/list")
    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,orgPositionClient);
		Agency agency = new Agency();
		agency.setTenantId(bladeUser.getTenantId());
		List<Long> agencyIds = agencyClient.list(agency).stream().map(Agency::getId).collect(Collectors.toList());

//		LambdaQueryWrapper<Residential> residentialLambdaQueryWrapper = new QueryWrapperUtil<Residential>().getBasicQueryWrapper(Residential::getOrgPosition, new Residential(), bladeUser,orgPositionClient);
		Residential residential = new Residential();
		Map<String,Object> map = new HashMap<>();
		map.put("residential",residential);
		residential.setTenantId(bladeUser.getTenantId());
		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());

		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(branchRelationService,residentialClient,agencyClient,enterpriseClient).pageVO(pages));
		}else {
			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);
		}
        }



    /**
     * 新增
     */
    @Override
    @PostMapping("/save")
    public boolean save(@Valid @RequestBody Branch branch) {
        return branchService.save(branch);
        }

    /**
     * 修改
     */
    @Override
    @PostMapping("/update")
    public boolean update(@Valid @RequestBody Branch branch) {
        return branchService.updateById(branch);
        }

//	@Override
//	public R submit(@Valid Branch branch) {
//		return null;
//	}

	/**
	 * 新增或修改
	 */
	@Override
	@PostMapping("/submit")
	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);
		}
	}




	/**
     * 删除
     */
    @Override
    @PostMapping("/remove")
    public boolean remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
        return branchService.deleteLogic(Func.toLongList(ids));
        }

	@Override
	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<>());
	}

	@Override
	public R<List<Branch>> getListForAgency(BladeUser bladeUser) {

//		LambdaQueryWrapper<Agency> agencyLambdaQueryWrapper = new QueryWrapperUtil<Agency>().getBasicQueryWrapper(Agency::getOrgPosition, new Agency(), bladeUser,orgPositionClient);
		Agency agency = new Agency();
		agency.setTenantId(bladeUser.getTenantId());
		List<Long> agencyIds = agencyClient.list(agency).stream().map(Agency::getId).collect(Collectors.toList());

//		LambdaQueryWrapper<Residential> residentialLambdaQueryWrapper = new QueryWrapperUtil<Residential>().getBasicQueryWrapper(Residential::getOrgPosition, new Residential(), bladeUser,orgPositionClient);
		Residential residential = new Residential();
		Map<String,Object> map = new HashMap<>();
		map.put("residential",residential);
		residential.setTenantId(bladeUser.getTenantId());
		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());

		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<>());
	}

}
