/*
 *      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.person.service.impl;

import org.springblade.common.constant.CommonConstant;
import org.springblade.common.constant.OperationConstant;
import org.springblade.community.feign.ICommunityClient;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.device.dto.DispatchTask;
import org.springblade.device.dto.UserInfoDto;
import org.springblade.device.feign.IDoorDeviceClient;
import org.springblade.estate.entity.ApplyUser;
import org.springblade.estate.feign.IApplyUserClient;
import org.springblade.estate.vo.ApplyUserVO;
import org.springblade.person.dto.HouseUserDTO;
import org.springblade.person.entity.HouseUser;
import org.springblade.person.entity.Member;
import org.springblade.person.feign.IMemberClient;
import org.springblade.person.mapper.HouseUserMapper;
import org.springblade.person.service.HouseUserService;
import org.springblade.person.service.IUserService;
import org.springblade.person.vo.HouseUserVO;
import org.springblade.system.expand.feign.IConfClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 *  服务实现类
 *
 * @author BladeX
 * @since 2021-04-14
 */
@Service
public class HouseUserServiceImpl extends BaseServiceImpl<HouseUserMapper, HouseUser> implements HouseUserService, IUserService<HouseUser> {

	private final ICommunityClient communityClient;
	private final IApplyUserClient applyUserClient;
	private final IMemberClient memberClient;
	private final IDoorDeviceClient doorDeviceClient;
	private final IConfClient confClient;

	@Autowired
	public HouseUserServiceImpl(ICommunityClient communityClient,IApplyUserClient applyUserClient,IMemberClient memberClient, IDoorDeviceClient doorDeviceClient, IConfClient confClient){
		this.communityClient = communityClient;
		this.applyUserClient = applyUserClient;
		this.memberClient = memberClient;
		this.doorDeviceClient = doorDeviceClient;
		this.confClient = confClient;
	}

	@Override
	public IPage<HouseUserVO> selectBasicInfoPage(IPage<HouseUserVO> page, HouseUserVO basicInfo) {
		return page.setRecords(baseMapper.selectBasicInfoPage(page, basicInfo));
	}

	@Override
	@Transactional
	public boolean deleteUserAndRelationship(HouseUserDTO userDto) {
		HouseUser user = this.getById(userDto.getId());
		if (null == user) {
			return false;
		}
		//状态删除
		Boolean result = this.removeById(userDto.getId());
		if(result){
			//修改住户数量

			this.communityClient.subPersonNum(user.getAgencyId(),user.getResidentialId(),user.getBuildingId(),user.getUnitId()
			   ,user.getFloorId(),user.getRoomId());

			//处理删除user后，与之关联的会员状态
			result = this.dealMemberState(userDto.getId());
		}
		return  result;
	}

	/**
	 * 处理删除user后，与之关联的会员状态
	 *
	 */
	private boolean dealMemberState(Long userId){
		boolean result = false;
		//查询和user有关系的会员
		ApplyUser condition = new ApplyUser();
		condition.setUserId(userId);
		condition.setAuditStatus(CommonConstant.UserAuditStatus.pass.getValue());
		List<ApplyUserVO> list = this.applyUserClient.list(condition);
		if(list!=null && list.size()>0){
			//删除和user有关系的
			result = this.applyUserClient.remove(list.get(0).getId().toString());
			if(result){
				//修改与之关联的会员状态
				for (ApplyUser mau:list){
					//重新拼凑查询条件，查询与member关联的user个数
					condition.setUserId(null);
					condition.setMemberId(mau.getMemberId());
					condition.setAuditStatus(CommonConstant.UserAuditStatus.pass.getValue());
					//统计
					List<ApplyUserVO> applyUserList = this.applyUserClient.list(condition);
					//会员已经没有了关联的住户，会员状态改为未认证
					if(applyUserList!=null &&applyUserList.size()==0){
						Member update = new Member();
						update.setId(mau.getMemberId());
						//修改会员状态 ----未认证
						update.setState(OperationConstant.ZERO);
						result = this.memberClient.update(update);
					}
				}
			}
		}else {
			result = true;
		}
		return result;
	}

	@Override
	public R pushAddFace(HouseUser houseUser, Map<String, String> extendMap) {
		DispatchTask task = new DispatchTask();
		task.setXqId(houseUser.getResidentialId());
		task.setUnitId(houseUser.getUnitId());
		/**
		 * 待做
		 */
		String confValue = confClient.getValueByToken("file.server.host");
		UserInfoDto userInfoDto = new UserInfoDto();
		userInfoDto.setFaceUrl(houseUser.getFaceUrl());
		userInfoDto.setId(CommonConstant.UserFlag.HOUSE_USER_FLAG.getValue() + houseUser.getId());

		Date begin = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date end = null;
		try{
			end = format.parse("2050-12-31 23:59:59");
		}catch (ParseException e){
			e.printStackTrace();
		}

		userInfoDto.setBeginDate(begin);
		userInfoDto.setEndDate(end);
		userInfoDto.setIdCard(houseUser.getIdCard());
		task.setData(userInfoDto);
		R result = doorDeviceClient.pushUserFace(task, 1);
		if(result.isSuccess()){
			return R.success("人脸下发成功");
		}else{
			return result;
		}
	}

	@Override
	public R pushDelFace(List<HouseUser> userInfoList, Map<String, String> extendMap) {
		for(HouseUser houseUser : userInfoList){
			if(StringUtil.isNotBlank(houseUser.getFaceUrl())){
				UserInfoDto dto = new UserInfoDto();
				dto.setId(CommonConstant.UserFlag.HOUSE_USER_FLAG.getValue() + houseUser.getId());
				dto.setFaceCodeList(new ArrayList<>(0));
				DispatchTask task = new DispatchTask();
				task.setUnitId(houseUser.getUnitId());
				task.setXqId(houseUser.getResidentialId());
				task.setData(dto);
				doorDeviceClient.pushUserFace(task, 2);
			}
		}
		return R.success("删除人脸成功");
	}
}
