package org.springblade.app.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
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.Query;
import org.springblade.estate.dto.ApplyUserDTO;
import org.springblade.estate.entity.ApplyUser;
import org.springblade.estate.feign.IApplyUserClient;
import org.springblade.estate.vo.ApplyUserVO;
import org.springblade.system.expand.entity.Conf;
import org.springblade.system.expand.feign.IConfClient;
import org.springblade.system.expand.vo.ConfVO;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

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

	private final IApplyUserClient applyUserClient;
	private final IConfClient confClient;

	/**
	 * 功能描述: 获取会员的申请认证的列表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 = "/getAllApplyUserByMemberId")
	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 applyUser{
	 *                 id : 1  记录id,
	 *                 checkState : 1  审核状态,
	 *                 checkOpinion :  审核意见--审核不通过时有值
	 *          }
	 * @return ModelAndView
	 *
	 *
	 */
	@PostMapping("/updateCheckState")
//    @Security(token = EstateSecurityToken.APPLY_USER_AUDIT,format = DataFormatEnum.JSON)
	public Map<String, Object> updateCheckState(@RequestBody ApplyUser applyUser){

		Map<String,Object> hashMap = new HashMap<>(3);
		hashMap.put("result_code", 0);
		hashMap.put("result_msg", "审核失败");
		//审核人类型：1-业主，2-后台
		applyUser.setOperatorType(1);
		if (applyUser.getAuditStatus().equals(CommonConstant.UserAuditStatus.pass.getValue())){
			//要审核通过的话，必须有时间和身份验证的限制
			boolean timeRange = false;
			try {
				timeRange = CommonUtil.isTimeRange("7:00", "22:00");
			}catch (Exception e){
				return hashMap;
			}
			Assert.isTrue(timeRange, "请在7:00-22:00时间内进行审核！");

			if(StringUtils.isNotBlank(applyUser.getIdCard()) && StringUtils.isNotBlank(applyUser.getName())){
				CustInfoVerify custInfoVerify = new CustInfoVerify();
				custInfoVerify.setCustName(applyUser.getName());
				custInfoVerify.setCertNumber(applyUser.getIdCard());
				custInfoVerify.setCertType("1");
//				Boolean resultCheck = CustInfoVerifyUtil.custInfoVerify(custInfoVerify);
//				Assert.isTrue(resultCheck, "身份证验证失败，请填写正确的身份证信息");
			}else{
				Assert.isTrue(false, "该住户没有身份证号，无法通过审核！");
			}
		}
		if(this.applyUserClient.updateCheckState(applyUser)){
			hashMap.put("result_code", 1);
			hashMap.put("result_msg", "审核成功");
		}
		return hashMap;
	}


}
