from sqlalchemy.exc import SQLAlchemyError
from be.model import error
from be.model import postgreSQLORM
from be.model.postgreSQLORM import New_Order
from be.model import db_conn
from sqlalchemy import and_
import json

class Seller(db_conn.DBConn):

    def __init__(self):
        db_conn.DBConn.__init__(self)

    def add_book(self, user_id: str, store_id: str, book_id: str, book_json_str: str, stock_level: int):
        try:
            if not self.user_id_exist(user_id):
                return error.error_non_exist_user_id(user_id)
            if not self.store_id_exist(store_id):
                return error.error_non_exist_store_id(store_id)
            if self.book_id_exist(store_id, book_id):
                return error.error_exist_book_id(book_id)
            # self.session.query(postgreSQLORM.Store_Book).
            new_book = postgreSQLORM.Store_Book(store_id=store_id,book_id=book_id,book_info=book_json_str,stock_level=stock_level)
            self.session.add(new_book)
            book = json.loads(book_json_str)
            thelist = []  # 由于没有列表类型，故使用将列表转为text的办法
            for tag in book.get('tags'):
                if tag.strip() != "":
                    # book.tags.append(tag)
                    thelist.append(tag)
            book['tags'] = str(thelist)  # 解析成list请使用eval(
            if book.get('picture') is not None:
                new_Book = postgreSQLORM.Book(book_id=book['id'], title=book['title'],
                                            author=book['author'],publisher=book['publisher'],
                                            original_title=book['original_title'],translator=book['translator'],
                                            pub_year=book['pub_year'],pages=book['pages'],
                                            original_price=book['price'],currency_unit=book['currency_unit'],
                                            binding=book['binding'],isbn=book['isbn'],
                                            author_intro=book['author_intro'],book_intro=book['book_intro'],
                                            content=book['content'],tags=book['tags'],
                                            picture=book['picture'])
            else:
                new_Book = postgreSQLORM.Book(book_id=book['id'], title=book['title'],
                                            author=book['author'],publisher=book['publisher'],
                                            original_title=book['original_title'],translator=book['translator'],
                                            pub_year=book['pub_year'],pages=book['pages'],
                                            original_price=book['price'],currency_unit=book['currency_unit'],
                                            binding=book['binding'],isbn=book['isbn'],
                                            author_intro=book['author_intro'],book_intro=book['book_intro'],
                                            content=book['content'],tags=book['tags'],
                                            picture=book['picture'])
            self.session.add(new_Book)
            # self.conn.execute("INSERT into store(store_id, book_id, book_info, stock_level)"
            #                   "VALUES (?, ?, ?, ?)", (store_id, book_id, book_json_str, stock_level))
            # self.conn.commit()
            self.session.query(postgreSQLORM.Store).filter_by(store_id=store_id).update({'stock_level':postgreSQLORM.Store.stock_level+1})
            self.session.commit()
        except SQLAlchemyError as e:
            return 528, "{}".format(str(e))
        except BaseException as e:
            return 530, "{}".format(str(e))
        return 200, "ok"

    def add_stock_level(self, user_id: str, store_id: str, book_id: str, add_stock_level: int):
        try:
            if not self.user_id_exist(user_id):
                return error.error_non_exist_user_id(user_id)
            if not self.store_id_exist(store_id):
                return error.error_non_exist_store_id(store_id)
            if not self.book_id_exist(store_id, book_id):
                return error.error_non_exist_book_id(book_id)
            self.session.query(postgreSQLORM.Store).filter_by(store_id=store_id).update({'stock_level':add_stock_level})
            self.session.query(postgreSQLORM.Store_Book).filter_by(store_id=store_id,book_id=book_id).update({'stock_level':add_stock_level})
            
            # self.conn.execute("UPDATE store SET stock_level = stock_level + ? "
            #                   "WHERE store_id = ? AND book_id = ?", (add_stock_level, store_id, book_id))
            # self.conn.commit()
            self.session.commit()
        except SQLAlchemyError as e:
            return 528, "{}".format(str(e))
        except BaseException as e:
            return 530, "{}".format(str(e))
        return 200, "ok"

    def create_store(self, user_id: str, store_id: str) -> (int, str):
        try:
            if not self.user_id_exist(user_id):
                return error.error_non_exist_user_id(user_id)
            if self.store_id_exist(store_id):
                return error.error_exist_store_id(store_id)
            # new_store = postgreSQLORM.Store(store_id=store_id,stock_level=0)
            new_user_store = postgreSQLORM.User_Store(user_id=user_id,store_id=store_id)
            # self.session.add(new_store)
            # self.session.commit()
            self.session.add(new_user_store)
            # self.conn.execute("INSERT into user_store(store_id, user_id)"
            #                   "VALUES (?, ?)", (store_id, user_id))
            # self.conn.commit()
            self.session.commit()
            # print('touch1')
        except SQLAlchemyError as e:
            # print('touch2')
            return 528, "{}".format(str(e))
        except BaseException as e:
            # print('touch3')
            return 530, "{}".format(str(e))
        return 200, "ok"

    def send_out(self, order_id:str, user_id:str):
        session = self.session
        try:
            if not self.user_id_exist(user_id):
                return error.error_non_exist_user_id(user_id)
                
            row = session.query(New_Order).filter(New_Order.order_id==order_id).first()
            if row is None:
                return error.error_invalid_order_id(order_id)
            if row.status != 1:
                return error.error_invalid_order_id(order_id)
            
            row = session.query(New_Order).filter(New_Order.order_id==order_id).update({'status':2})

            if row == 0:
                return error.error_invalid_order_id(order_id)

            session.commit()

        except SQLAlchemyError as e:
            return 528, "{}".format(str(e))
        except BaseException as e:
            # print('touch3')
            return 530, "{}".format(str(e))
        return 200, "ok"