package org.springblade.app.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springblade.app.util.CommonUtil;
import org.springblade.common.constant.CommonConstant;
import org.springblade.common.entity.CustInfoVerify;
import org.springblade.core.mp.support.BladePage;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.device.vo.DoorDeviceVO;
import org.springblade.estate.dto.ApplyUserDTO;
import org.springblade.estate.dto.UserAccessPermissionsDTO;
import org.springblade.estate.entity.ApplyUser;
import org.springblade.estate.feign.IApplyUserClient;
import org.springblade.estate.vo.ApplyUserVO;
import org.springblade.person.entity.HouseUser;
import org.springblade.person.feign.IHouseUserClient;
import org.springblade.person.vo.HouseUserVO;
import org.springblade.system.expand.feign.IConfClient;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

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

/**
 * Created By lidexi in 2021/5/6
 **/
@RestController
@RequestMapping("/app/applyuser")
@RequiredArgsConstructor
@Slf4j
public class ApplyUserController {

	private final IHouseUserClient houseUserClient;
	private final IApplyUserClient applyUserClient;
	private final IConfClient confClient;


	@GetMapping(value = "/getAuditListByMemberId")
	public R getAuditListByMemberId(@RequestParam Long memberId,Query query){
		HouseUser houseUser = new HouseUser();
		houseUser.setType(0);
		houseUser.setMemberId(memberId);
		List<HouseUserVO> list = houseUserClient.list(houseUser);
		if (CollUtil.isEmpty(list)) {
			return R.data(new Page<>());
		}
		List<Long> roomIds = list.stream().map(HouseUser::getRoomId).collect(Collectors.toList());
		ApplyUserDTO applyUserDTO = new ApplyUserDTO();
		applyUserDTO.setQuery(query);
		applyUserDTO.setRoomIds(roomIds);
		BladePage<ApplyUserVO> bladePage = applyUserClient.pageCondition(applyUserDTO);
		return R.data(bladePage);
	}


	@GetMapping("list")
	public R list(ApplyUser applyUser, Query query) {
		ApplyUserDTO applyUserDTO = new ApplyUserDTO();
		BeanUtil.copyProperties(applyUser, applyUserDTO);
		applyUserDTO.setQuery(query);
		BladePage<ApplyUserVO> page = applyUserClient.page(applyUserDTO);
		return R.data(page);
	}
	/**
	 * 功能描述: 获取会员的申请认证的列表ApplyUser By  memberId
	 * @param map {
	 *            member_id     :   会员id
	 *            pageNum       :   分页页数
	 *            pageSize      :   分页大小
	 *            check_states  :   0,1,2  逗号隔开，申请记录审核状态：0-待审核 1-审核通过 2-审核不通过
	 *            org_id        :   机构授权org_id，机构id,
	 *            token        :   对接令牌
	 *            }
	 * @return ResultBean<hashMap> 返回结果
	 *
	 *
	 */
	@PostMapping(value = "/getAllApplyUserByMemberIdBak")
	public Map<String,Object> getAllApplyUserByMemberId(@RequestBody Map<String,String> map){

		Map<String,Object> hashMap = new HashMap<>();
		//result_code:0-失败  1-成功
		hashMap.put("result_code", 0);
		hashMap.put("result_msg", "获取列表失败");
		String check_states = map.get("check_states");
		String member_id = map.get("member_id");
		String pageNum = map.get("pageNum");
		String pageSize = map.get("pageSize");
		String roomId = map.get("roomId");
		try {

			if(StringUtils.isBlank(member_id)){
				hashMap.put("result_msg", "member_id不能为空");
				return hashMap;
			}
			if (StringUtils.isEmpty(pageNum)) {
				hashMap.put("result_msg", "分页页码不能为空");
				return hashMap;
			}
			if (StringUtils.isEmpty(pageSize)) {
				hashMap.put("result_msg", "分页大小不能为空");
				return hashMap;
			}
			ApplyUserDTO applyUserDto = new ApplyUserDTO();
			applyUserDto.setMemberId(Long.valueOf(member_id));
			if(StringUtils.isNotBlank(check_states)){
				//字符串数组
				List<String> checkStateStr = Arrays.asList(check_states.split(","));
				List<Integer> checkStateArray = Lists.newArrayList();
				for(String checkState : checkStateStr){
					checkStateArray.add(Integer.valueOf(checkState));
				}
				applyUserDto.setCheckStates(checkStateArray);
			}
			Query query = new Query();
			query.setCurrent(Integer.parseInt(pageNum));
			query.setSize(Integer.parseInt(pageSize));
			applyUserDto.setQuery(query);
			if(null != roomId){
				applyUserDto.setRoomId(Long.valueOf(roomId));
			}
			BladePage<ApplyUserVO> applyUserPage = this.applyUserClient.getAllApplyUserByCondition(applyUserDto);

			Long totalPageNum = (applyUserPage.getTotal() + applyUserPage.getSize() -1) / applyUserPage.getSize();
			List<ApplyUserVO> list = applyUserPage.getRecords();
			hashMap.put("result_code",1);
//			Conf searchConf = new Conf();
//			searchConf.setConfToken(CommonConstant.SystemConf.FILESERVER.getValue());
//			ConfVO detail = confClient.detail(searchConf);
//			if(detail != null){
//				String prefix = detail.getConfValue();
//				for(ApplyUser applyUser:list){
//					if(StringUtils.isNotBlank(applyUser.getImageUri())){
//						applyUser.setImageUri(prefix + applyUser.getImageUri());
//					}
//					if(StringUtils.isNotBlank(applyUser.getPassportImgUri())){
//						applyUser.setPassportImgUri(prefix + applyUser.getPassportImgUri());
//					}
//					if(StringUtils.isNotBlank(applyUser.getEntryImgUri())){
//						applyUser.setEntryImgUri(prefix + applyUser.getEntryImgUri());
//					}
//				}
//			}

			hashMap.put("list",list);
			hashMap.put("pages",totalPageNum);
			if(list.size()==0){
				hashMap.put("result_msg", "没有查询到相关数据");
			}else{
				hashMap.put("result_msg", "查询数据成功");
			}
		}catch (Exception e){
			log.error("异常", e);
			hashMap.put("result_msg", "后台程序异常");
		}
		return hashMap;
	}

	/**
	 * 功能描述: 获取会员的申请认证的列表ApplyUser By  RoomIds
	 * @param map {
	 *            room_ids     :   房间ids
	 *            check_states  :   0,1,2  逗号隔开，申请记录审核状态：0-待审核 1-审核通过 2-审核不通过
	 *            org_id        :   机构授权org_id，机构id,
	 *            token        :   对接令牌
	 *            }
	 * @return ResultBean<hashMap> 返回结果
	 *
	 *
	 */
	@PostMapping(value = "/getAllApplyUserByRoomIds")
	public Map<String,Object> getAllApplyUserByRoomIds(@RequestBody Map<String,Object> map){

		Map<String,Object> hashMap = new HashMap<>();
		//result_code:0-失败  1-成功
		hashMap.put("result_code", 0);
		hashMap.put("result_msg", "获取列表失败");
		String check_states = map.get("check_states").toString();
		List<String> room_ids = (List<String>) map.get("room_ids");
		String pageNum = (String) map.get("pageNum");
		String pageSize = (String) map.get("pageSize");
//        String roomId = map.get("roomId");
		try {

			if(room_ids.size() == 0){
				hashMap.put("result_msg", "room_id不能为空");
				return hashMap;
			}
			if (StringUtils.isEmpty(pageNum)) {
				hashMap.put("result_msg", "分页页码不能为空");
				return hashMap;
			}
			if (StringUtils.isEmpty(pageSize)) {
				hashMap.put("result_msg", "分页大小不能为空");
				return hashMap;
			}

			ApplyUserDTO applyUserDto = new ApplyUserDTO();
			if(StringUtils.isNotBlank(check_states)){
				//字符串数组
				List<String> checkStateStr = Arrays.asList(check_states.split(","));
				List<Integer> checkStateArray = Lists.newArrayList();
				for(String checkState : checkStateStr){
					checkStateArray.add(Integer.valueOf(checkState));
				}
				applyUserDto.setCheckStates(checkStateArray);
			}
			List<ApplyUser> list = new ArrayList<>();
			room_ids.forEach(item ->{
				applyUserDto.setRoomId(Long.valueOf(item));
				Query query = new Query();
				query.setCurrent(Integer.parseInt(pageNum));
				query.setSize(Integer.parseInt(pageSize));
				applyUserDto.setQuery(query);
				BladePage<ApplyUserVO> page = this.applyUserClient.getAllApplyUserByCondition(applyUserDto);
				List<ApplyUserVO> itemList = page.getRecords();
				list.addAll(itemList);
			});
//            List<ApplyUser> list = this.applyUserFeign.getAllApplyUserByRoomId(applyUserDto);
			hashMap.put("result_code",1);

//			String fileServer = this.confClient.getValueByToken(CommonConstant.SystemConf.FILESERVER.getValue());
//			for(ApplyUser applyUser:list){
//				if(StringUtils.isNotBlank(applyUser.getImageUri())){
//					applyUser.setImageUri(fileServer+ applyUser.getImageUri());
//				}
//				if(StringUtils.isNotBlank(applyUser.getPassportImgUri())){
//					applyUser.setPassportImgUri(fileServer + applyUser.getPassportImgUri());
//				}
//				if(StringUtils.isNotBlank(applyUser.getEntryImgUri())){
//					applyUser.setEntryImgUri(fileServer + applyUser.getEntryImgUri());
//				}
//			}
			hashMap.put("list",list);
			Long totalPageNum = (list.size() + Long.parseLong(pageSize) -1) / Long.parseLong(pageSize);
			hashMap.put("pages",totalPageNum);
			if(list.size()==0){
				hashMap.put("result_msg", "没有查询到相关数据");
			}else{
				hashMap.put("result_msg", "查询数据成功");
			}
		}catch (Exception e){
			log.error("异常", e);
			hashMap.put("result_msg", "后台程序异常");
		}
		return hashMap;
	}


	/**
	 * 功能描述:审核
	 * @param applyUserDTO{
	 *                 id : 1  记录id,
	 *                 checkState : 1  审核状态,
	 *                 checkOpinion :  审核意见--审核不通过时有值
	 *          }
	 * @return ModelAndView
	 *
	 *
	 */
	@PostMapping("/updateCheckState")
	public R updateCheckState(@RequestBody ApplyUserDTO applyUserDTO){
		//审核人类型：1-业主，2-后台
		applyUserDTO.setOperatorType(1);
		R result = this.applyUserClient.appUpdateAuditStatus(applyUserDTO);
		return result;
	}


}
