package org.springblade.app.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springblade.common.constant.CommonConstant;
import org.springblade.common.constant.OperationConstant;
import org.springblade.estate.entity.ApplyUser;
import org.springblade.estate.entity.GuestAuthorize;
import org.springblade.estate.feign.IApplyUserClient;
import org.springblade.estate.feign.IGuestAuthorizeClient;
import org.springblade.estate.vo.ApplyUserVO;
import org.springblade.estate.vo.GuestAuthorizeVO;
import org.springblade.person.entity.HouseUser;
import org.springblade.person.feign.IHouseUserClient;
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.text.SimpleDateFormat;
import java.util.*;

/**
 * Created By lidexi in 2021/5/8
 **/
@RestController
@RequiredArgsConstructor
@RequestMapping("/app/guestAuthorize")
@Slf4j
public class GuestAuthorizeController {

	private final IApplyUserClient applyUserClient;
	private final IGuestAuthorizeClient guestAuthorizeClient;
	private final IHouseUserClient houseUserClient;

	/**
	 * 功能描述: 通过会员id获取访客授权密码列表
	 *
	 * @param map {
	 *            member_id     :   会员id,
	 *            org_id        :   机构授权org_id，机构id
	 *            token         :   对接令牌
	 *            }
	 * @return ResultBean<hashMap> 返回结果
	 */
	@PostMapping(value = "/getListByMemberId")
	public Map<String, Object> getListByMemberId(@RequestBody Map<String, String> map) {
		Map<String, Object> hashMap = new HashMap<>();
		//result_code:0-失败  1-成功
		hashMap.put("result_code", 0);
		hashMap.put("result_msg", "查询数据失败");
		try {
			String member_id = map.get("member_id");


			if (StringUtils.isBlank(member_id)) {
				hashMap.put("result_msg", "会员id不能为空");
				return hashMap;
			}
			ApplyUser searchEntity = new ApplyUser();
			searchEntity.setCheckState(CommonConstant.UserAuditStatus.pass.getValue());
			searchEntity.setMemberId(Long.valueOf(member_id));
			List<ApplyUserVO> list = this.applyUserClient.list(searchEntity);
			if (list == null || list.size() == 0) {
				hashMap.put("result_msg", "没有查询到与会员对应的住户信息");
			} else {
				List<Long> userIds = new ArrayList<>();
				for (ApplyUser mau : list) {
					userIds.add(mau.getUserId());
				}
				List<GuestAuthorizeVO> authorizeVOS = this.guestAuthorizeClient.getListByUsers(userIds);

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

	/**
	 * 功能描述: 新增访客授权记录
	 *
	 * @param map {
	 *            room_id       :   授权的房间id
	 *            guest_type    :   访客类型：0-朋友  1-外卖 2-快递 3-其他
	 *            begin_date    :   密码有效开始时间  --时间戳
	 *            end_date      :   密码有效结束时间  --时间戳
	 *            valid_count   :   密码有效次数
	 *            member_id     :   会员id,
	 *            }
	 * @return ResultBean<hashMap> 返回结果
	 */
	@PostMapping(value = "/addGuestAuthorize")
	public Map<String, Object> getGuestAuthorize(@RequestBody Map<String, String> map) {
		Map<String, Object> hashMap = new HashMap<>();
		//result_code:0-失败  1-成功
		hashMap.put("result_code", 0);
		hashMap.put("result_msg", "操作失败");
		try {
			String room_id = map.get("room_id");
			String guest_type = map.get("guest_type");
			String begin_date = map.get("begin_date");
			String end_date = map.get("end_date");
			String valid_count = map.get("valid_count");
			String member_id = map.get("member_id");
			String org_id = map.get("org_id");
			String token = map.get("token");

			if (StringUtils.isBlank(member_id)) {
				hashMap.put("result_msg", "会员id不能为空");
				return hashMap;
			}
			if (StringUtils.isBlank(room_id)) {
				hashMap.put("result_msg", "授权的房间（room_id）不能为空");
				return hashMap;
			}
			if (StringUtils.isBlank(guest_type)) {
				hashMap.put("result_msg", "授权的访客类型（guest_type）不能为空");
				return hashMap;
			}
			if (StringUtils.isBlank(begin_date)) {
				hashMap.put("result_msg", "授权的密码有效开始时间(begin_date)不能为空");
				return hashMap;
			}
			if (StringUtils.isBlank(end_date)) {
				hashMap.put("result_msg", "授权的密码有效结束时间(end_date)不能为空");
				return hashMap;
			}
//            if(StringUtils.isBlank(valid_count)){
//                hashMap.put("result_msg", "授权的密码有效次数(valid_count)不能为空");
//                return hashMap;
//            }
			ApplyUser searchEntity = new ApplyUser();
			searchEntity.setMemberId(Long.valueOf(member_id));
			searchEntity.setCheckState(CommonConstant.UserAuditStatus.pass.getValue());
			List<ApplyUserVO> list = this.applyUserClient.list(searchEntity);

			if (list == null || list.size() == 0) {
				hashMap.put("result_msg", "没有查询到与会员对应的住户信息");
				return hashMap;
			} else {
				//会员在授权的房间下的userId
				Long userId = null;
				for (ApplyUser mau : list) {
					if (mau.getRoomId().equals(Long.valueOf(room_id))) {
						userId = mau.getUserId();
					}
				}
				if (userId == null) {
					hashMap.put("result_msg", "会员没有该授权房间的权限");
					return hashMap;
				} else {
					HouseUser searchHouseUser = new HouseUser();
					searchHouseUser.setId(userId);
					HouseUser user = this.houseUserClient.detail(searchHouseUser);
					if (user == null) {
						hashMap.put("result_msg", "会员授权的房间下对应的住户不存在");
						return hashMap;
					} else {
						GuestAuthorize ga = new GuestAuthorize();
						ga.setGuestType(Integer.valueOf(guest_type));
						ga.setRoomId(user.getRoomId());
						ga.setRoomName(user.getRoomName());
						ga.setUnitId(user.getUnitId());
						ga.setUnitName(user.getUnitName());
						ga.setBuildingId(user.getBuildingId());
						ga.setBuildingName(user.getBuildingName());
						ga.setUserId(user.getId());
						ga.setUserName(user.getName());
//                        ga.setValidCount(Integer.valueOf(valid_count));
						ga.setResidentialId(user.getResidentialId());
						ga.setResidentialName(user.getResidentialName());
						ga.setEnableType(OperationConstant.ZERO);
						ga.setOrgPosition(user.getOrgPosition());

						ga.setBeginDate(new Date(Long.valueOf(begin_date)));
						ga.setEndDate(new Date(Long.valueOf(end_date)));
						//获取授权密码
						GuestAuthorize guestAuthorize = this.guestAuthorizeClient.save(ga);
						if (guestAuthorize != null) {
							hashMap.put("result_code",1);
							hashMap.put("guestAuthorize", guestAuthorize);
							hashMap.put("result_msg","操作成功");
						}
					}
				}
			}
		} catch (Exception e) {
			log.error("异常", e);
			hashMap.put("result_msg", "后台程序异常");
		}
		return hashMap;
	}

	/**
	 * 功能描述: 撤销密码
	 *
	 * @param map {
	 *            guest_authorize_id       :   要撤销的密码id
	 *            org_id                   :   机构授权org_id，机构id
	 *            member_id                :   会员id,
	 *            token                     :   对接令牌
	 *            }
	 * @return ResultBean<hashMap> 返回结果
	 */
	@PostMapping(value = "/cancel")
	public Map<String, Object> cancel(@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 guest_authorize_id = map.get("guest_authorize_id");
		String member_id = map.get("member_id");
		try {

			if (StringUtils.isBlank(member_id)) {
				hashMap.put("result_msg", "会员id不能为空");
				return hashMap;
			}
			if (StringUtils.isBlank(guest_authorize_id)) {
				hashMap.put("result_msg", "要撤销（guest_authorize_id）不能为空");
				return hashMap;
			}

			GuestAuthorize searchEntity = new GuestAuthorize();
			searchEntity.setId(Long.valueOf(guest_authorize_id));
			GuestAuthorize guestAuthorize = this.guestAuthorizeClient.detail(searchEntity);
			if (guestAuthorize == null) {
				hashMap.put("result_msg", "要撤销的授权记录不存在");
				return hashMap;
			}
			if (guestAuthorize.getEnableType() != 0) {
				hashMap.put("result_msg", "要撤销的授权记录状态不正常" + guestAuthorize.getEnableType());
				return hashMap;
			}
			ApplyUser applyUser = new ApplyUser();
			applyUser.setMemberId(Long.valueOf(member_id));
			applyUser.setCheckState(CommonConstant.UserAuditStatus.pass.getValue());
			List<ApplyUserVO> list = this.applyUserClient.list(applyUser);
			if (list == null || list.size() == 0) {
				hashMap.put("result_msg", "没有查询到与会员对应的住户信息");
				return hashMap;
			} else {
				//权限校验，校验会员关联的住户是否是创建该密码的住户
				boolean check = false;
				for (ApplyUser mua : list) {
					if (guestAuthorize.getUserId().equals(mua.getUserId())) {
						check = true;
						break;
					}
				}
				if (!check) {
					hashMap.put("result_msg", "会员没有删除该授权的权限");
					return hashMap;
				} else {

					guestAuthorize.setEnableType(OperationConstant.ONE);
					boolean update = this.guestAuthorizeClient.update(guestAuthorize);
					if (update) {

						hashMap.put("result_code", 1);
						hashMap.put("result_msg", "授权记录撤销成功");
					}
				}
			}
		} catch (Exception e) {
			log.error("异常", e);
			hashMap.put("result_msg", "后台程序异常");
		}
		return hashMap;
	}
}
