package org.springblade.app.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
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.community.entity.Room;
import org.springblade.community.feign.IRoomClient;
import org.springblade.core.mp.support.BladePage;
import org.springblade.core.tool.api.R;
import org.springblade.estate.dto.GuestAuthorizeDTO;
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.*;

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;
	private final IRoomClient roomClient;

	/**
	 * 功能描述: 通过会员id获取访客授权密码列表
	 *
	 * @param map {
	 *            member_id     :   会员id,
	 *            org_id        :   机构授权org_id，机构id
	 *            token         :   对接令牌
	 *            }
	 * @return ResultBean<hashMap> 返回结果
	 */
	@PostMapping(value = "/getListByMemberId-bak")
	public Map<String, Object> getListByMemberIdBak(@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.setAuditStatus(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;
	}

	@PostMapping("pageOfMonth")
	public R pageOfMonth(@RequestBody GuestAuthorizeDTO guestAuthorizeDTO){
		BladePage<GuestAuthorize> bladePage = guestAuthorizeClient.pageOfMonth(guestAuthorizeDTO);
		return R.data(bladePage);
	}

	@PostMapping(value = "/addGuestAuthorize")
	public R addGuestAuthorize(@RequestBody GuestAuthorize guestAuthorize) {
		Long roomId = guestAuthorize.getRoomId();
		Date beginDate = guestAuthorize.getBeginDate();
		Date endDate = guestAuthorize.getEndDate();
		Long memberId = guestAuthorize.getMemberId();
		Integer guestType = guestAuthorize.getGuestType();
		Assert.notNull(roomId, "房间id不能为空");
		Assert.notNull(beginDate, "开始时间不能为空");
		Assert.notNull(endDate, "结束时间不能为空");
		Assert.notNull(memberId, "会员id不能为空");
		Assert.notNull(guestType, "访客类型不能为空");
		Room room = roomClient.getById(roomId);
		Assert.notNull(room, "找不到访问的房间");
		GuestAuthorize ga = new GuestAuthorize();
		ga.setGuestType(guestType);
		ga.setAgencyId(room.getAgencyId());
		ga.setAgencyName(room.getAgencyName());
		ga.setRoomId(roomId);
		ga.setRoomName(room.getName());
		ga.setUnitId(room.getUnitId());
		ga.setUnitName(room.getUnitName());
		ga.setBuildingId(room.getBuildingId());
		ga.setBuildingName(room.getBuildingName());
		ga.setMemberId(memberId);
		ga.setUserName(guestAuthorize.getUserName());
		ga.setResidentialId(room.getResidentialId());
		ga.setResidentialName(room.getResidentialName());
		ga.setEnableType(OperationConstant.ZERO);
		ga.setBeginDate(beginDate);
		ga.setEndDate(endDate);
		GuestAuthorize vo = this.guestAuthorizeClient.save(ga);
		return R.data(vo);
	}

	/**
	 * 功能描述: 新增访客授权记录
	 *
	 * @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-bak")
	public Map<String, Object> getGuestAuthorizeBak(@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.setAuditStatus(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;
	}

	/***
	 * 撤销密码
	 * @return
	 */
	@PostMapping(value = "/cancel")
	public R cancel(@RequestParam Long id) {
		GuestAuthorize guestAuthorize = this.getDetail(id);
		guestAuthorize.setEnableType(OperationConstant.ONE);
		boolean b = guestAuthorizeClient.update(guestAuthorize);
		return R.data(b);
	}


	/***
	 * 详情
	 * @return
	 */
	@GetMapping(value = "/detail")
	public R detail(@RequestParam Long id) {
		GuestAuthorize detail = this.getDetail(id);
		return R.data(detail);
	}

	private GuestAuthorize getDetail(Long id) {
		Assert.notNull(id, "主键不能为空");
		GuestAuthorize ga = new GuestAuthorize();
		ga.setId(id);
		GuestAuthorizeVO guestAuthorizeVO = guestAuthorizeClient.detail(ga);
		Assert.notNull(guestAuthorizeVO, "找不到授权记录");
		return guestAuthorizeVO;
	}
}
