# -*- coding:utf-8 -*-
"""
@Author  : xuxingchen
@Contact : xuxingchen@sinochem.com
@Desc    : 可视对讲厂家信息表 改&查
"""
from pydantic import BaseModel, field_validator

from utils.database import BaseTable, get_table_handler
from utils.misc import InvalidException


class UpdateBrand(BaseModel):
    name: str

    @field_validator("name")
    def check_name(cls, value):
        th = get_table_handler()
        if BrandsTable.exists(th, value):
            return value
        else:
            raise InvalidException("请提供正确的可视对讲厂家名")


class BrandsTable(BaseTable):
    @staticmethod
    def get_checked_factory(table_handler: BaseTable):
        """获取当前启用的可视对讲厂家"""
        table_handler.query("SELECT brand_name FROM brands WHERE status = '开启'")
        res = table_handler.cursor.fetchall()
        if res:
            return {"name": res[0][0]}
        else:
            return {"name": None}

    @staticmethod
    def update_checked_factory(table_handler: BaseTable, brand_name: str):
        """更新启用的可视对讲厂家"""
        sqls = [
            "UPDATE brands SET status = '关闭' WHERE status = '开启'",
            "UPDATE brands SET status = '开启' WHERE brand_name = ?"
        ]
        table_handler.execute(sqls, [(), (brand_name,)])
        return {"status": True}

    @staticmethod
    def exists(table_handler: BaseTable, brand_name: str):
        """可视对讲厂家是否存在"""
        table_handler.query("SELECT brand_name FROM brands WHERE brand_name = ?", (brand_name,))
        res = table_handler.cursor.fetchall()
        if res:
            return True
        else:
            return False
