package com.sptg.gateway.controller;

import cn.hutool.core.date.DateUtil;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.util.JsonUtils;
import com.sptg.estate.api.dto.BuildingDto;
import com.sptg.estate.api.dto.UnitDto;
import com.sptg.estate.api.entity.*;
import com.sptg.estate.api.feigns.*;
import com.sptg.gateway.entity.BuildingApi;
import com.sptg.gateway.entity.ResidentialApi;
import com.sptg.gateway.entity.RoomApi;
import com.sptg.gateway.entity.UnitApi;
import com.sptg.gateway.util.DataCheck;
import com.sptg.gateway.util.PojoToApi;
import com.sptg.permissions.api.entity.Conf;
import com.sptg.permissions.api.entity.Organization;
import com.sptg.permissions.api.feigns.ApiDockingConfFeign;
import com.sptg.permissions.api.feigns.ConfFeign;
import com.sptg.permissions.api.feigns.OrgFeign;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * title: EstateController
 * package: com.sptg.gateway.controller
 * description: 小区管理控制器--查询小区信息接口
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/app/estate")
public class EstateController {

    private final OrgFeign orgFeign;
    private final ResidentialFeign residentialFeign;
    private final UnitFeign unitFeign;
    private final RoomFeign roomFeign;
    private final MemberAndUserFeign memberAndUserFeign;
    private final UserFeign userFeign;
    private final ApiDockingConfFeign apiDockingConfFeign;
    private final ConfFeign confFeign;
    private final BuildingFeign buildingFeign;

    /**
     * 功能描述: 通过区编号获取小区列表--国家标准省市区编号
     *
     * @param map {
     *            region_area       :   区编号（国家统一省，市，区编号）,
     *            residential_name  :   小区名字--非必须
     *            org_id            :   机构授权org_id，机构id
     *            token             :    对接令牌
     *            }
     * @return ResultBean<hashMap> 返回结果
     */
    @PostMapping(value = "/getByRegionArea")
    public Map<String, Object> getByRegionArea(@RequestBody Map<String, String> map) {
//        log.warn("============================APP住户通过区域编码获取小区列表(/app/estate/getByRegionArea)请求数据===============================");
//        log.warn(JsonUtils.objectToJson(map));
        Map<String, Object> hashMap = new HashMap<>();
        //result_code:0-失败  1-成功
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "查询失败");
        try {
            String region_area = map.get("region_area");
            String org_id = map.get("org_id");
            String token = map.get("token");
            String residential_name = map.get("residential_name");
            Organization organization = null;
            if (org_id == null) {
                hashMap.put("result_msg", "org_id不能为空");
                return hashMap;
            } else {
                organization = orgFeign.getOrgById(Long.valueOf(org_id));
                if (organization == null) {
                    hashMap.put("result_msg", "org_id没有对应的机构，没有权限");
                    return hashMap;
                }
            }
            if (DataCheck.checkToken(hashMap, org_id, token, apiDockingConfFeign)) {
                return hashMap;
            }
            if (StringUtils.isBlank(region_area)) {
                hashMap.put("result_msg", "区编号不能为空");
                return hashMap;
            }
            Residential residential = new Residential();
            residential.setRegionArea(region_area);
            residential.setOrgPosition(organization.getPosition());
            residential.setName(residential_name);
            ResultBean<Residential> resultBean = this.residentialFeign.getByRegionArea(residential);
            if (resultBean.getCode().equals("200")) {
                hashMap.put("result_code", 1);
                List<Residential> residentials = resultBean.getList();
                List<ResidentialApi> list = new ArrayList<>();
                for (Residential re : residentials) {
                    list.add(PojoToApi.residentialToApi(re));
                }
                hashMap.put("list", list);
                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;
    }

    /**
     * 功能描述: 通过小区id获取楼栋列表
     *
     * @param map {
     *            residential_id : 小区id,
     *            org_id         : 机构授权org_id，机构id
     *            token           : 对接令牌
     *            }
     * @return ResultBean<hashMap> 返回结果
     */
    @PostMapping(value = "/getBuildingsByResidentialId")
    public Map<String, Object> getBuildingsByResidentialId(@RequestBody Map<String, String> map) {
        log.warn("============================APP住户通过小区ID获取楼栋列表(/app/estate/getBuildingsByResidentialId)请求数据===============================");
        log.warn(JsonUtils.objectToJson(map));
        Map<String, Object> hashMap = new HashMap<>();
        //result_code:0-失败  1-成功
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "查询失败");
        try {
            Long residential_id = Long.valueOf(map.get("residential_id"));
            String org_id = map.get("org_id");
            String token = map.get("token");
            if (DataCheck.checkOrgId(hashMap, org_id, orgFeign)) {
                return hashMap;
            }
            if (DataCheck.checkToken(hashMap, org_id, token, apiDockingConfFeign)) {
                return hashMap;
            }
            if (residential_id == null) {
                hashMap.put("result_msg", "小区id不能为空");
                return hashMap;
            }
            BuildingDto buildingDto = new BuildingDto();
            buildingDto.setResidentialId(residential_id);
            List<Building> list = this.buildingFeign.getListByCondition(buildingDto);
            hashMap.put("result_code", 1);
            List<BuildingApi> buildingApis = new ArrayList<>(list.size());
            for (Building building : list) {
                buildingApis.add(PojoToApi.buildingToApi(building));
            }
            hashMap.put("list", buildingApis);
            if (buildingApis.size() == 0) {
                hashMap.put("result_msg", "没有相关楼栋信息");
            } else {
                hashMap.put("result_msg", "获取楼栋信息成功");
            }
        } catch (Exception e) {
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }

    /**
     * 功能描述: 通过楼栋id获取单元列表
     *
     * @param map {
     *            building_id : 楼栋id,
     *            org_id         : 机构授权org_id，机构id
     *            token           : 对接令牌
     *            }
     * @return ResultBean<hashMap> 返回结果
     */
    @PostMapping(value = "/getUnitsByBuildingId")
    public Map<String, Object> getUnitsByBuildingId(@RequestBody Map<String, String> map) {
        log.warn("============================APP住户通过楼栋ID获取单元列表(/app/estate/getUnitsByBuildingId)请求数据===============================");
        log.warn(JsonUtils.objectToJson(map));
        Map<String, Object> hashMap = new HashMap<>();
        //result_code:0-失败  1-成功
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "查询失败");
        try {
            Long building_id = Long.valueOf(map.get("building_id"));
            String org_id = map.get("org_id");
            String token = map.get("token");
            if (DataCheck.checkOrgId(hashMap, org_id, orgFeign)) {
                return hashMap;
            }
            if (DataCheck.checkToken(hashMap, org_id, token, apiDockingConfFeign)) {
                return hashMap;
            }
            if (building_id == null) {
                hashMap.put("result_msg", "楼栋id不能为空");
                return hashMap;
            }
            UnitDto unitDto = new UnitDto();
            unitDto.setBuildingId(building_id);
            ResultBean<Unit> unitResultBean = this.unitFeign.findListByPosition(unitDto);

            if (unitResultBean != null) {
                List<Unit> units = unitResultBean.getList();
                hashMap.put("result_code", 1);
                List<UnitApi> unitApis = new ArrayList<>(units.size());
                for (Unit unit : units) {
                    unitApis.add(PojoToApi.unitToApi(unit));
                }
                hashMap.put("list", unitApis);
                if (unitApis.size() == 0) {
                    hashMap.put("result_msg", "没有相关楼栋信息");
                } else {
                    hashMap.put("result_msg", "获取楼栋信息成功");
                }
            } else {
                hashMap.put("result_msg", "没有相关楼栋信息");
            }

        } catch (Exception e) {
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }

    /**
     * 功能描述: 通过小区id获取单元列表
     *
     * @param map {
     *            residential_id : 小区id,
     *            org_id         : 机构授权org_id，机构id
     *            token           : 对接令牌
     *            }
     * @return ResultBean<hashMap> 返回结果
     */
    @PostMapping(value = "/getByResidentialId")
    public Map<String, Object> getByResidentialId(@RequestBody Map<String, String> map) {
        log.warn("============================APP住户通过小区ID获取单元列表(/app/estate/getByResidentialId)请求数据===============================");
        log.warn(JsonUtils.objectToJson(map));
        Map<String, Object> hashMap = new HashMap<>();
        //result_code:0-失败  1-成功
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "查询失败");
        try {
            Long residential_id = Long.valueOf(map.get("residential_id"));
            String org_id = map.get("org_id");
            String token = map.get("token");
            if (DataCheck.checkOrgId(hashMap, org_id, orgFeign)) {
                return hashMap;
            }
            if (DataCheck.checkToken(hashMap, org_id, token, apiDockingConfFeign)) {
                return hashMap;
            }
            if (residential_id == null) {
                hashMap.put("result_msg", "小区id不能为空");
                return hashMap;
            }
            List<Unit> list = this.unitFeign.getListByXqId(residential_id);
            hashMap.put("result_code", 1);
            List<UnitApi> unitApis = new ArrayList<>(list.size());
            for (Unit unit : list) {
                unitApis.add(PojoToApi.unitToApi(unit));
            }
            hashMap.put("list", unitApis);
            if (unitApis.size() == 0) {
                hashMap.put("result_msg", "没有相关单元信息");
            } else {
                hashMap.put("result_msg", "获取单元信息成功");
            }
        } catch (Exception e) {
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }

    /**
     * 功能描述: 通过单元id获取房间列表
     *
     * @param map {
     *            unit_id   :   单元id,
     *            org_id    :   机构授权org_id，机构id
     *            token     :   对接令牌
     *            }
     * @return ResultBean<hashMap> 返回结果
     */
    @PostMapping(value = "/getByUnitId")
    public Map<String, Object> getByUnitId(@RequestBody Map<String, String> map) {
        log.warn("============================APP住户通过单元ID获取房间列表(/app/estate/getByUnitId)请求数据===============================");
        log.warn(JsonUtils.objectToJson(map));
        Map<String, Object> hashMap = new HashMap<>();
        //result_code:0-失败  1-成功
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "查询失败");
        try {
            Long unit_id = Long.valueOf(map.get("unit_id"));
            String org_id = map.get("org_id");
            String token = map.get("token");
            if (DataCheck.checkOrgId(hashMap, org_id, orgFeign)) {
                return hashMap;
            }
            if (DataCheck.checkToken(hashMap, org_id, token, apiDockingConfFeign)) {
                return hashMap;
            }
            if (unit_id == null) {
                hashMap.put("result_msg", "单元id不能为空");
                return hashMap;
            }
            ResultBean<Room> resultBean = this.roomFeign.getByUnitId(unit_id);
            if (resultBean.getCode().equals("200")) {
                hashMap.put("result_code", 1);
                List<Room> list = resultBean.getList();
                List<RoomApi> roomApis = new ArrayList<>(list.size());
                for (Room room : list) {
                    roomApis.add(PojoToApi.roomToApi(room));
                }
                hashMap.put("list", roomApis);
                if (roomApis.size() == 0) {
                    hashMap.put("result_msg", "没有相关房屋信息");
                } else {
                    hashMap.put("result_msg", "获取房屋信息成功");
                }
            }
        } catch (Exception e) {
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }

    /**
     * 功能描述: 通过会员id获取会员的房屋列表
     *
     * @param map {
     *            member_id :   会员id,
     *            org_id    :   机构授权org_id，机构id
     *            token     :   对接令牌
     *            }
     * @return ResultBean<hashMap> 返回结果
     */
    @PostMapping(value = "/getRoomByMemberId")
    public Map<String, Object> getRoomByMemberId(@RequestBody Map<String, String> map) {
        log.warn("============================APP通过会员ID获取房屋列表(/app/estate/getRoomByMemberId)请求数据===============================");
        log.warn(JsonUtils.objectToJson(map));
        Map<String, Object> hashMap = new HashMap<>();
        //result_code:0-失败  1-成功
        hashMap.put("result_code", 0);
        try {
            String member_id = map.get("member_id");
            String org_id = map.get("org_id");
            String token = map.get("token");
            if (DataCheck.checkOrgId(hashMap, org_id, orgFeign)) {
                return hashMap;
            }
            if (DataCheck.checkToken(hashMap, org_id, token, apiDockingConfFeign)) {
                return hashMap;
            }
            if (member_id == null) {
                hashMap.put("result_msg", "member_id不能为空");
                return hashMap;
            }
            //查询会员对应的user
            MemberAndUser memberAndUser = new MemberAndUser();
            memberAndUser.setMemberId(Long.valueOf(member_id));
            List<MemberAndUser> list = this.memberAndUserFeign.getByCondition(memberAndUser);
            if (list == null || list.size() == 0) {
                //hashMap.put("result_msg", "没有查询到与会员对应的住户信息");
                return hashMap;
            } else {
                List<Long> roomIds = new ArrayList<>();
                List<Long> userIds = new ArrayList<>();
                for (MemberAndUser mu : list) {
                    roomIds.add(mu.getRoomId());
                    userIds.add(mu.getUserId());
                }
                //查询会员对应住户
                List<User> users = this.userFeign.getListByUserId(userIds);
                //查询会员对应的房间
                List<Room> rooms = this.roomFeign.getListByRoomId(roomIds);
                if (rooms == null || rooms.size() == 0) {
                    hashMap.put("result_msg", "没有相关房屋信息");
                } else {
                    List<RoomApi> roomApis = new ArrayList<>();
                    //住户和房屋的关系
                    for (Room room : rooms) {
                        Residential residential = this.residentialFeign.findResidentialById(room.getResidentialId());
                        Integer doorNeedAudit = 1;
                        if(residential != null){
                            doorNeedAudit = residential.getDoorNeedAudit();
                        }
                        if (users == null) {
                            roomApis.add(PojoToApi.roomToApi(room,doorNeedAudit,residential.getPersonTel()));
                        } else {
                            for (User user : users) {
                                if (user.getRoomId().equals(room.getId())) {
                                    room.setRelationshipType(user.getType());
                                    room.setResidentialId(user.getResidentialId());
                                    if (StringUtils.isNotBlank(user.getImageUri())) {
                                        room.setImageUri(confFeign.getFileServerHost() + user.getImageUri());
                                    }
                                    room.setUserId(user.getId());
                                    room.setIdcard(user.getIdCard());
                                    RoomApi roomApi = PojoToApi.roomToApi(room,doorNeedAudit,residential.getPersonTel());
                                    roomApi.setFaceBeginDate(user.getFaceBeginDate());
                                    roomApi.setFaceEndDate(user.getFaceEndDate());
                                    roomApi.setFaceEnable(user.getFaceEnable());
                                    if (user.getFaceEndDate() != null) {
                                        Conf conf = this.confFeign.getEntityByToken("expire.notice.days");
                                        if (conf != null) {
                                            Integer days = Integer.parseInt(conf.getConfValue());
                                            int compare = DateUtil.compare(DateUtil.offsetDay(new Date(), days), user.getFaceEndDate());
                                            roomApi.setFaceValid(compare > 0 ? false : true);
                                        }
                                    }
                                    roomApis.add(roomApi);
                                }
                            }
                        }
//                        else if(users.size() > 1){ //证明当前是由业主进行查询的
//                            for(User user:users){
//                                if(user.getType().equals(OperationConstant.ZERO)){
//                                    if(user.getRoomId().equals(room.getId())){
//                                        room.setRelationshipType(user.getType());
//                                        room.setResidentialId(user.getResidentialId());
//                                        if (StringUtils.isNotBlank(user.getImageUri())){
//                                            room.setImageUri(confFeign.getFileServerHost() + user.getImageUri());
//                                        }
//                                        room.setUserId(user.getId());
//                                        room.setIdcard(user.getIdCard());
//                                        roomApis.add(PojoToApi.roomToApi(room));
//                                    }
//                                }else{
//                                    continue;
//                                }
//                            }
//                        }else if(users.size() == 1){
//                            User user = users.get(0);
//                            if(user.getRoomId().equals(room.getId())){
//                                room.setRelationshipType(user.getType());
//                                room.setResidentialId(user.getResidentialId());
//                                if (StringUtils.isNotBlank(user.getImageUri())){
//                                    room.setImageUri(confFeign.getFileServerHost() + user.getImageUri());
//                                }
//                                room.setUserId(user.getId());
//                                room.setIdcard(user.getIdCard());
//                                roomApis.add(PojoToApi.roomToApi(room));
//                            }
//                        }
//                        for(User user:users){
//                            if(user.getRoomId().equals(room.getId())){
//                                room.setRelationshipType(user.getType());
//                                room.setResidentialId(user.getResidentialId());
//                                if (StringUtils.isNotBlank(user.getImageUri())){
//                                    room.setImageUri(confFeign.getFileServerHost() + user.getImageUri());
//                                }
//                                room.setUserId(user.getId());
//                                room.setIdcard(user.getIdCard());
//                            }
//                        }
                    }
                    hashMap.put("list", roomApis);
                    hashMap.put("result_code", 1);
                    hashMap.put("result_msg", "获取房屋列表成功");
                }
            }
        } catch (Exception e) {
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }

    /**
     * 功能描述:根据id获取房间
     *
     * @param map {
     *            member_id :   会员id,
     *            room_id   :   房间id,
     *            org_id    :   机构授权org_id，机构id
     *            token     :   对接令牌
     *            }
     * @return ResultBean<hashMap> 返回结果
     */
    @PostMapping(value = "/findRoomById")
    public Map<String, Object> findRoomById(@RequestBody Map<String, String> map) {
        log.warn("============================APP通过房间ID获取房间信息(/app/estate/findRoomById)请求数据===============================");
        log.warn(JsonUtils.objectToJson(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 org_id = map.get("org_id");
            String token = map.get("token");
            if (DataCheck.checkOrgId(hashMap, org_id, orgFeign)) {
                return hashMap;
            }
            if (DataCheck.checkToken(hashMap, org_id, token, apiDockingConfFeign)) {
                return hashMap;
            }
            if (StringUtils.isBlank(room_id)) {
                hashMap.put("result_msg", "房间id不能为空");
                return hashMap;
            }
            Room room = this.roomFeign.findRoomById(Long.parseLong(room_id));
            if (room != null) {
                hashMap.put("result_code", 1);
                RoomApi roomApi = PojoToApi.roomToApi(room);
                hashMap.put("roomInfo", roomApi);
                hashMap.put("result_msg", "获取房屋信息成功");
            }
        } catch (Exception e) {
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }

    @PostMapping(value = "/findUnitByResidentialId")
    public Map<String, Object> findResidentialById(@RequestBody Map<String, String> map) {
        log.warn("============================APP通过小区ID获取单元列表(/app/estate/findUnitByResidentialId)请求数据===============================");
        log.warn(JsonUtils.objectToJson(map));
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "查询失败");
        try {
            String residential_id = map.get("residential_id");
            String org_id = map.get("org_id");
            String token = map.get("token");
            if (DataCheck.checkOrgId(hashMap, org_id, orgFeign)) {
                return hashMap;
            }
            if (DataCheck.checkToken(hashMap, org_id, token, apiDockingConfFeign)) {
                return hashMap;
            }
            if (StringUtils.isBlank(residential_id)) {
                hashMap.put("result_msg", "小区id不能为空");
                return hashMap;
            }
            Residential residential = this.residentialFeign.findResidentialById(Long.parseLong(residential_id));
            if (residential != null) {
                List<Unit> units = this.unitFeign.getListByXqId(residential.getId());
                List<UnitApi> unitApis = new ArrayList<>();
                if (units != null && units.size() > 0) {
                    for (int i = 0; i < units.size(); i++) {
                        Unit unit = units.get(i);
                        List<Room> rooms = this.roomFeign.getListByUnitId(unit.getId());
                        UnitApi unitApi = PojoToApi.unitToApi(unit);
                        unitApi.setRooms(rooms);
                        unitApis.add(unitApi);
                    }
                }
                hashMap.put("result_code", 1);
                hashMap.put("list", unitApis);
                hashMap.put("result_msg", "获取小区单元信息成功");
            }
        } catch (Exception e) {
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }


}
