# -*- coding:utf-8 -*-
"""
@Author  : xuxingchen
@Contact : xuxingchen@sinochem.com
@Desc    : 模拟边缘对接所需的平台api接口
"""
from fastapi import APIRouter, Request, Query

from models.householders import HouseholdersTable
from models.houses import HousesTable
from models.spaces import SpacesTable
from models.subsystem import SubsystemTable, HouseDetailInfo
from routers.login import authenticate_token
from utils import logger
from utils.database import get_table_handler
from utils.misc import InvalidException, snake2camel_list_dict

router = APIRouter()


@router.post("/v2/accesskey_auth", summary="回传一个无效的随机字符串")
async def access_key_auth(_item: dict):
    return {"access_token": "Q0E5QjU4QUNDMDA4MTY4RDNFNkRGRjNGNzQ4NDAzMTQ5OTVBMDQwODMyNjBFMjBCQkIwQjA2QzlCNUQ3MUY3NA=="}


@router.get("/v3/realty-master-data/owners/{user_id}", summary="根据用户 id 获取房产信息")
async def get_property_info_by_user_id(request: Request, user_id: int):
    logger.Logger.debug(f"{request.url.path} <- {user_id}")
    th = get_table_handler()
    house_ids = HouseholdersTable.get_room_ids(th, user_id)
    resp = {
        "status": 200,
        "msg": "ok",
        "data": {
            "house_ids": house_ids
        },
        "code": 200,
        "det": 0
    }
    logger.Logger.debug(f"{request.url.path} {resp}")
    return resp


@router.post("/v3/realty-master-data/houses", summary="根据房产 id 获取房产详细信息")
async def get_house_detail_info(request: Request, item: dict):
    try:
        logger.Logger.debug(f"{request.url.path} <- {item}")
        house_ids = item["query"]["id"]["$in"]
        house_detail_list = []
        th = get_table_handler()
        for house_id in house_ids:
            house_detail_info = HousesTable.get_house_detail_info(th, house_id)
            if house_detail_info is not None:
                house_detail_list.append(house_detail_info)
        resp = {
            "status": 200,
            "msg": "ok",
            "data": {
                "total_count": len(house_detail_list),
                "total_page": 0,
                "list": house_detail_list
            },
            "code": 200,
            "det": 0
        }
        logger.Logger.debug(f"{request.url.path} {resp}")
        return resp
    except (KeyError, TypeError):
        raise InvalidException("请求参数结构异常")


@router.post("/v2/realty-master-data/SubsystemSpaceMap/list", summary="查找空间结构中的房间信息")
async def get_subsystem_house_detail_info(request: Request, item: dict):
    try:
        logger.Logger.debug(f"{request.url.path} <- {item}")
        project_id = item["query"]["project_id"]["$eq"]
        th = get_table_handler()
        data_list = SubsystemTable.get_house_detail_info_by_project_id(th, project_id)
        resp = {
            "status": 200,
            "msg": "ok",
            "data": {
                "total_count": len(data_list),
                "total_page": 0,
                "list": data_list
            },
            "code": 200,
            "det": 0
        }
        logger.Logger.debug(f"{request.url.path} -> {resp}")
        return resp
    except (KeyError, TypeError):
        raise InvalidException("请求参数结构异常")


@router.post("/v2/realty-master-data/SubsystemSpaceMap/added", summary="添加房产信息")
async def add_subsystem_house_info(request: Request, item: HouseDetailInfo):
    try:
        logger.Logger.debug(f"{request.url.path} <- {item}")
        th = get_table_handler()
        SubsystemTable.add_sub_system_house_info(th, item)
        resp = {
            "status": 200,
            "msg": "ok",
            "data": item.message_id,
            "code": 200,
            "det": 0
        }
        logger.Logger.debug(f"{request.url.path} {resp}")
        return resp
    except (KeyError, TypeError):
        raise InvalidException("请求参数结构异常")


@router.post("/v2/realty-master-data/SubsystemSpaceMap/update", summary="更新房产信息")
async def update_subsystem_house_info(request: Request, item: HouseDetailInfo):
    try:
        logger.Logger.debug(f"{request.url.path} <- {item}")
        th = get_table_handler()
        item.action = "update"
        SubsystemTable.add_sub_system_house_info(th, item)
        resp = {
            "status": 200,
            "msg": "ok",
            "data": item.message_id,
            "code": 200,
            "det": 0
        }
        logger.Logger.debug(f"{request.url.path} {resp}")
        return resp
    except (KeyError, TypeError):
        raise InvalidException("请求参数结构异常")


@router.post("/v2/smart-access/house/house_ty_maps", summary="查询房产的真实信息")
async def get_house_ty_info(request: Request, item: dict):
    try:
        logger.Logger.debug(f"{request.url.path} <- {item}")
        project_id = item["query"]["project_id"]["$eq"]
        room_id = item["query"]["_id"]["$eq"]
        th = get_table_handler()
        house_ty_info = HousesTable.get_house_ty_info(th, project_id, room_id)
        if house_ty_info is None:
            house_ty_infos = []
        else:
            house_ty_infos = [house_ty_info]
        resp = {
            "status": 200,
            "msg": "ok",
            "data": {
                "count": 1,
                "list": house_ty_infos,
                "query_res": {
                    "count": 1,
                    "list": snake2camel_list_dict(house_ty_infos)
                }
            },
            "det": 0
        }
        logger.Logger.debug(f"{request.url.path} {resp}")
        return resp
    except (KeyError, TypeError):
        raise InvalidException("请求参数结构异常")
