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

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import com.alibaba.fastjson.JSONObject;
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.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.google.api.client.util.ArrayMap;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springblade.community.agency.dto.AgencyDTO;
import org.springblade.community.agency.entity.Agency;
import org.springblade.community.agency.service.IAgencyService;
import org.springblade.community.agency.vo.AgencyAppLoginVO;
import org.springblade.community.agency.vo.AgencyVO;
import org.springblade.community.agency.wrapper.AgencyWrapper;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.event.IEventFactory;
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.*;
import org.springblade.core.util.EventBusFactorys;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.entity.Role;
import org.springblade.modules.system.entity.Tenant;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.IRoleService;
import org.springblade.modules.system.service.ITenantService;
import org.springblade.modules.system.service.IUserService;
import org.springblade.openinterface.carbarrier.utils.MD5Util;
import org.springblade.sysarea.service.ISysAreaService;
import org.springblade.system.orgposition.entity.OrgPosition;
import org.springblade.system.orgposition.service.IOrgPositionService;
import org.springblade.system.street.entity.Street;
import org.springblade.system.street.service.IStreetService;
import org.springblade.system.tenanttype.entity.TenantType;
import org.springblade.system.tenanttype.service.ITenantTypeService;
import org.springblade.utils.AESPlus;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 控制器
 *
 * @author BladeX
 * @since 2020-10-27
 */
@RestController
@AllArgsConstructor
@RequestMapping("agency/agency")
@Api(value = "", tags = "园区接口")
public class AgencyController extends BladeController {

	private IAgencyService agencyService;
	private IOrgPositionService orgPositionService;
	private IStreetService streetService;
	private IDeptService deptService;
	private ISysAreaService sysAreaService;

	private IRoleService roleService;
	private ITenantTypeService tenantTypeService;
	private ITenantService tenantService;
	private IUserService userService;

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

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入agency")
	public R<IPage<Agency>> list(@RequestParam Map<String, Object> agency, Query query, BladeUser bladeUser) {
//	public R<IPage<Agency>> list(Agency agency, Query query, BladeUser bladeUser) {
		String deptId = bladeUser.getDeptId();
		if(StringUtil.isBlank(deptId)){
			return R.data(new Page<>());
		}
		String[] deptIds = deptId.split(",");
		LambdaQueryWrapper<Agency> wrapper = Condition.getQueryWrapper(agency, Agency.class).lambda();

		//获取角色信息
		Role role = roleService.getById(bladeUser.getRoleId());
		//非超管，根据tenantId租户id过滤
		if (!role.getRoleAlias().equals("administrator")){
			wrapper.eq(Agency::getTenantId,bladeUser.getTenantId());
		}

		for (int i = 0; i < deptIds.length; i++) {
			Dept dept = deptService.getById(deptIds[i]);
			if(dept.getDeptCategory() == 1){
				return R.data(null);
			}
			OrgPosition orgPosition = orgPositionService.getBaseMapper().selectOne(new QueryWrapper<>(new OrgPosition()).lambda().eq(OrgPosition::getOrgId, deptIds[i]));
			if (orgPosition == null){
				continue;
			}
			if (i == 0) {
				wrapper.like(Agency::getOrgPosition,orgPosition.getOrgPosition());
			}else{
				wrapper.or().like(Agency::getOrgPosition,orgPosition.getOrgPosition());
			}
		}
//		LambdaQueryWrapper<Agency> wrapper = new QueryWrapperUtil<Agency>().getBasicQueryWrapper(Agency::getOrgPosition,agency,bladeUser,orgPositionService);

		query.setDescs("create_time");
		IPage<Agency> pages = agencyService.page(Condition.getPage(query), wrapper);
//		pages.getRecords().parallelStream().forEach(agency1->{
//			//统计该社区下的小区总数
//
//		});
//		IPage<Agency> pages = agencyService.page(Condition.getPage(query), Condition.getQueryWrapper(agency,Agency.class));
		return R.data(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) {
		if(agency.getRegionProvince()!=null&&agency.getRegionCity()!=null&&agency.getRegionArea()!=null&&agency.getRegionStreet()!=null){
			if(agencyService.save(agency)){
				agency.setOrgPosition("/" + agency.getRegionProvince()+"/"+agency.getRegionCity()+"/"+agency.getRegionArea()+"/"+agency.getRegionStreet()+"/"+agency.getId());
				agencyService.updateById(agency);
			}
		}

		return R.status(false);
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入agency")
	public R update(@Valid @RequestBody Agency agency) {
		if(agency.getRegionProvince()!=null&&agency.getRegionCity()!=null&&agency.getRegionArea()!=null&&agency.getRegionStreet()!=null){
			agency.setOrgPosition("/" + agency.getRegionProvince()+"/"+agency.getRegionCity()+"/"+agency.getRegionArea()+"/"+agency.getRegionStreet()+"/"+agency.getId());
			return R.data(agencyService.updateById(agency));
		}

		return R.status(false);
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入agency")
	public R submit(@Valid @RequestBody Agency agency) {
		Street street = streetService.getBaseMapper().selectOne(new QueryWrapper<>(new Street()).lambda().eq(Street::getCode,agency.getRegionStreet()));
		if(agency.getId() != null){

			agency.setOrgPosition(street.getOrgPosition()+"/"+agency.getId());
			return R.status(agencyService.updateById(agency));
		}else{
			agencyService.save(agency);
			/**
			 * 发送异步信息
			 */
			IEventFactory eventControllerFactory= EventBusFactorys.get();
			if (eventControllerFactory != null) {
				AgencyDTO agencyDTO = Objects.requireNonNull(BeanUtil.copyProperties(agency,AgencyDTO.class));
				agencyDTO.setWMethod(1);
				eventControllerFactory.getController("communitySubscriber").post(agencyDTO);
			}

			agency.setOrgPosition(street.getOrgPosition()+"/"+agency.getId());
			return R.status(agencyService.updateById(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)));
	}

	/**
	 * 下拉列表
	 */
	@GetMapping("/select")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "下拉列表", notes = "agency")
	public R<List<Agency>> select(@RequestParam Map<String,Object> agency,Integer size, BladeUser bladeUser) {
		String deptId = bladeUser.getDeptId();
		String[] deptIds = deptId.split(",");
		LambdaQueryWrapper<Agency> wrapper = Condition.getQueryWrapper(agency,Agency.class).lambda();

		//获取角色信息
		Role role = roleService.getById(bladeUser.getRoleId());
		//非超管，根据tenantId租户id过滤
		if (!role.getRoleAlias().equals("administrator")){
			wrapper.eq(Agency::getTenantId,bladeUser.getTenantId());
		}

		for (int i = 0; i < deptIds.length; i++) {
			OrgPosition orgPosition = orgPositionService.getBaseMapper().selectOne(new QueryWrapper<>(new OrgPosition()).lambda().eq(OrgPosition::getOrgId, deptIds[i]));
			if (orgPosition == null){
				continue;
			}
			if (i == 0) {
				wrapper.like(Agency::getOrgPosition,orgPosition.getOrgPosition());
			}else{
				wrapper.or().like(Agency::getOrgPosition,orgPosition.getOrgPosition());
			}
		}
		wrapper.last(size != null,"limit " + size);
		return R.data(this.agencyService.list(wrapper));
	}

	@GetMapping("/setOrgPosition")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "下拉列表", notes = "agency")
	public R setOrgPosition(){
		List<Agency> agencyList = agencyService.getBaseMapper().selectList(new QueryWrapper<>(new Agency()));

		agencyList.parallelStream().forEach(agency -> {
			agency.setOrgPosition("/"+agency.getRegionProvince()+"/"+agency.getRegionCity()+"/"+agency.getRegionArea()+"/"+agency.getRegionStreet()+"/"+agency.getId());
			agencyService.updateById(agency);
		});
		return new R();
	}


	/**
	 *获取园区列表
	 * 园区小程序获取社区列表第一版本：（弃用）
	 */
	@GetMapping("/getAgencyList")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "获取社区列表")
	public R getAgencyList(){
		List<Agency> tenantIdList = agencyService.getAgencyList();
		return R.data(AgencyWrapper.build(streetService,sysAreaService).listVO(tenantIdList));
	}

	/**
	 *获取社区列表:返回获取对应社区的token所需的账号密码
	 *
	 */
	@GetMapping("/getAgencyTenantList")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "获取社区租户列表")
	public R<List<AgencyAppLoginVO>> getAgencyTenantList(@RequestParam Map<String,Object> agency) {

		List<AgencyAppLoginVO> agencyAppLoginVOS = new ArrayList<>();
		List<TenantType> tenantTypes = tenantTypeService.getBaseMapper().selectList(new QueryWrapper<>(new TenantType()).lambda()
			.eq(TenantType::getTenantType, 1));
		List<String> tenantIds = tenantTypes.stream().map(TenantType::getTenantId).collect(Collectors.toList());

		for(String tenantId:tenantIds){
			AgencyAppLoginVO agencyAppLoginVO = new AgencyAppLoginVO();

			//获取该租户的园区信息
			List<Agency> agencyList = agencyService.getBaseMapper().selectList(Condition.getQueryWrapper(agency,Agency.class).lambda().eq(Agency::getTenantId, tenantId));
			if(agencyList.size()>0){
				agencyAppLoginVO = Objects.requireNonNull(BeanUtil.copy(agencyList.get(0), AgencyAppLoginVO.class));
				agencyAppLoginVO.setPassword(agencyList.get(0).getTenantPassword());
//				agencyAppLoginVO.setPassword(MD5Util.MD5(agencyAppLoginVO.getPassword()));
				//获取该租户管理员的账号密码用于小程序获取token
				List<User> admins = userService.getBaseMapper().selectList(new QueryWrapper<>(new User()).lambda()
					.eq(User::getTenantId, tenantId).eq(User::getName, "admin"));
				if(admins.size()>0){
					agencyAppLoginVO.setAccount(admins.get(0).getAccount());
					agencyAppLoginVOS.add(agencyAppLoginVO);
				}
			}

		}

		return R.data(agencyAppLoginVOS);
	}


	@PostMapping("set")
	public R set(){
		List<Agency> agencys = agencyService.list(new QueryWrapper<>(new Agency()));
		for (int i=0;i<agencys.size();i++){
			Agency agency = agencys.get(i);
			System.out.println("第"+i+"行数据");
			Street street = streetService.getById(agency.getRegionStreet());
			agency.setRegionStreet(street.getCode());
			agencyService.updateById(agency);
		}
		return new R();
	}

	@GetMapping("/getByStreet")
	public R<List<Agency>> agencyList(@RequestParam(value = "streetCode")String streetCode){
		List<Agency> agencies = this.agencyService.getBaseMapper().selectList(new QueryWrapper<>(new Agency()).lambda().eq(Agency::getRegionStreet, streetCode));
		return R.data(agencies);
	}


	public static void main(String[] args) throws Exception{
		JSONObject data = new JSONObject(true);
		data.put("aba", "aaa");
		data.put("aab", "bbb");
		data.put("ccc", "ccc");
		System.out.println(data.toJSONString());
//		String encrypt = AESPlus.encrypt("ad84afc60ddae8a8", "15622205184");
//		System.out.println("==========加密数据===============");
//		System.out.println(encrypt);
//		String decrypt = AESPlus.decrypt("ad84afc60ddae8a8", encrypt);
//		System.out.println("==========解密数据===============");
//		System.out.println(decrypt);

//		System.out.println(DigestUtil.hex("0cada86dac96c51ed39a0924176e6641"));
	}

}
