/*
 *      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.estate.controller;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;
import javax.validation.Valid;

import org.springblade.common.constant.CommonConstant;
import org.springblade.common.constant.ConfConstant;
import org.springblade.community.entity.Residential;
import org.springblade.community.entity.Room;
import org.springblade.community.feign.IAgencyClient;
import org.springblade.community.feign.IResidentialClient;
import org.springblade.community.feign.IRoomClient;
import org.springblade.community.vo.ResidentialVO;
import org.springblade.community.vo.RoomVO;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.SecureUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.estate.dto.ApplyUserDTO;
import org.springblade.person.entity.HouseUser;
import org.springblade.person.feign.IHouseUserClient;
import org.springblade.person.vo.HouseUserVO;
import org.springblade.system.expand.entity.Conf;
import org.springblade.system.expand.feign.IConfClient;
import org.springblade.system.expand.feign.IOrgPositionClient;
import org.springblade.system.expand.util.QueryWrapperUtil;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.estate.entity.ApplyUser;
import org.springblade.estate.vo.ApplyUserVO;
import org.springblade.estate.wrapper.ApplyUserWrapper;
import org.springblade.estate.service.IApplyUserService;
import org.springblade.core.boot.ctrl.BladeController;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 申请用户表---房屋成员 控制器
 *
 * @author BladeX
 * @since 2021-04-23
 */
@RestController
@AllArgsConstructor
@RequestMapping("/applyuser")
@Api(value = "申请用户表---房屋成员", tags = "申请用户表---房屋成员接口")
public class ApplyUserController extends BladeController {

	private final IApplyUserService applyUserService;
	private final IResidentialClient residentialClient;
	private final IHouseUserClient houseUserClient;
	private final IRoomClient roomClient;
	private final IConfClient confClient;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入applyUser")
	public R<ApplyUserVO> detail(ApplyUser applyUser) {
		ApplyUser detail = applyUserService.getOne(Condition.getQueryWrapper(applyUser));
//		String filePrefix = confClient.getValueByToken(ConfConstant.FILE_SERVER_HOST);
		return R.data(ApplyUserWrapper.build().entityVO(detail));
	}

	/**
	 * 分页 申请用户表---房屋成员
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入applyUser")
	public R<IPage<ApplyUserVO>> list(@RequestParam Map<String, Object> applyUser, Query query, BladeUser bladeUser) {
		QueryWrapper<ApplyUser> queryWrapper = Condition.getQueryWrapper(applyUser, ApplyUser.class);
		queryWrapper.lambda().orderByDesc(ApplyUser::getCreateTime);
		IPage<ApplyUser> pages = applyUserService.page(Condition.getPage(query), queryWrapper);
//		String filePrefix = confClient.getValueByToken(ConfConstant.FILE_SERVER_HOST);
		return R.data(ApplyUserWrapper.build().pageVO(pages));
	}


	/**
	 * 自定义分页 申请用户表---房屋成员
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入applyUser")
	public R<IPage<ApplyUserVO>> page(ApplyUserVO applyUser, Query query) {
		IPage<ApplyUserVO> pages = applyUserService.selectApplyUserPage(Condition.getPage(query), applyUser);
		return R.data(pages);
	}

	/**
	 * 新增 申请用户表---房屋成员
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入applyUser")
	public R save(@Valid @RequestBody ApplyUser applyUser) {
		return R.status(applyUserService.save(applyUser));
	}

	/**
	 * 修改 申请用户表---房屋成员
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入applyUser")
	public R update(@Valid @RequestBody ApplyUserDTO applyUserDTO) {
		/*applyUser.setOperatorType(2);//后台审核类型
		BladeUser user = SecureUtil.getUser();
		applyUser.setOperatorName(user.getUserName());
		applyUser.setCheckDate(new Date());
		applyUser.setFaceUrl(confClient.removePrefix(applyUser.getFaceUrl()));
		applyUser.setPassportImgUri(confClient.removePrefix(applyUser.getPassportImgUri()));
		applyUser.setEntryImgUri(confClient.removePrefix(applyUser.getEntryImgUri()));
		if (applyUser.getAuditStatus() == CommonConstant.UserAuditStatus.pass.getValue()) {
			if (applyUserService.updateById(applyUser)) {
				Long userId = applyUser.getUserId();
				if(userId != null){ //属于针对住户重新编辑信息后审核，只需更改原住户信息即可，无需重新创建住户
					HouseUser houseUser = houseUserClient.getById(userId);
					if(houseUser != null){
						houseUser.setFaceUrl(confClient.removePrefix(applyUser.getFaceUrl()));
						houseUser.setPassportImgUri(confClient.removePrefix(applyUser.getPassportImgUri()));
						houseUser.setEntryImgUri(confClient.removePrefix(applyUser.getEntryImgUri()));
						houseUser.setPhone(applyUser.getPhone());
						boolean saveFlag = houseUserClient.submit(houseUser);
						return R.status(saveFlag);
					}
				}else{ //审核通过新增一个住户
					HouseUser houseUser = new HouseUser();
					houseUser.setResidentialId(applyUser.getResidentialId());
					houseUser.setResidentialName(applyUser.getResidentialName());

					Residential searchResidential  = new Residential();
					searchResidential.setId(applyUser.getResidentialId());
					ResidentialVO residentialVO = residentialClient.detail(searchResidential);
					Assert.notNull(residentialVO,"找不到对应的小区");
					houseUser.setAgencyId(residentialVO.getAgencyId());
					houseUser.setAgencyName(residentialVO.getAgencyName());
					houseUser.setBuildingId(applyUser.getBuildingId());
					houseUser.setBuildingName(applyUser.getBuildingName());
					houseUser.setUnitId(applyUser.getUnitId());
					houseUser.setUnitName(applyUser.getUnitName());

					Room searchRoom = new Room();
					searchRoom.setId(applyUser.getRoomId());
					RoomVO roomVO = roomClient.detail(searchRoom);
					Assert.notNull(roomVO,"找不到对应的房间");
					houseUser.setFloorId(roomVO.getFloorId());
					houseUser.setFloorName(roomVO.getFloorName());
					houseUser.setRoomId(applyUser.getRoomId());
					houseUser.setRoomName(applyUser.getRoomName());

					houseUser.setName(applyUser.getName());
					houseUser.setPhone(applyUser.getPhone());
					houseUser.setIdCard(applyUser.getIdCard());
					houseUser.setSex(applyUser.getSex());
					houseUser.setNationality(applyUser.getNationality());
					houseUser.setCreateType(applyUser.getCreateType());
					houseUser.setType(applyUser.getType());
					houseUser.setFaceUrl(applyUser.getFaceUrl());
					houseUser.setImageMd5(applyUser.getImageMd5());
					houseUser.setPassportImgUri(applyUser.getPassportImgUri());
					houseUser.setEntryImgUri(applyUser.getEntryImgUri());
					houseUser.setMemberId(applyUser.getMemberId());

					//新增房间住户数量
					roomVO.setUserCount(roomVO.getUserCount() == null? 1 : roomVO.getUserCount() + 1);
					roomClient.update(roomVO);

					boolean saveFlag = houseUserClient.submit(houseUser);
					if (saveFlag) {
						applyUser.setUserId(houseUserClient.detail(houseUser).getId());
						return R.status(applyUserService.updateById(applyUser));
					}
				}
			}
		}
		return R.status(applyUserService.updateById(applyUser));*/
		applyUserDTO.setOperatorType(2);
		return this.applyUserService.updateAuditStatus(applyUserDTO);
	}

	/**
	 * 新增或修改 申请用户表---房屋成员
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入applyUser")
	public R submit(@Valid @RequestBody ApplyUser applyUser) {
		return R.status(applyUserService.saveOrUpdate(applyUser));
	}


	/**
	 * 删除 申请用户表---房屋成员
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(applyUserService.deleteLogic(Func.toLongList(ids)));
	}


	/**
	 * 住户申请审核
	 */
	@PostMapping("/updateCheckState")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "住户申请审核", notes = "传入applyUser")
	@Transactional
	public R updateCheckState(@Valid @RequestBody ApplyUserDTO applyUserDTO) {

		return R.data(this.applyUserService.updateAuditStatus(applyUserDTO));
	}





}
