"""
業態適応型伝票システム
事業者の業態に応じて最適なフォームを提供
"""

import flet as ft
import sqlite3
import signal
import sys
import logging
from datetime import datetime

class AdaptiveSlipSystem:
    def __init__(self, page: ft.Page):
        self.page = page
        self.setup_page()
        self.setup_database()
        self.setup_ui()
        
    def setup_page(self):
        self.page.title = "業態適応伝票"
        self.page.window.width = 420
        self.page.window.height = 900
        self.page.window.resizable = False
        self.page.window_center = True
        
    def setup_database(self):
        try:
            self.conn = sqlite3.connect('sales_assist.db')
            self.cursor = self.conn.cursor()
            
            # 業態マスター
            self.cursor.execute('''
                CREATE TABLE IF NOT EXISTS business_types (
                    id INTEGER PRIMARY KEY,
                    name TEXT UNIQUE,
                    slip_mode TEXT
                )
            ''')
            
            # サンプル業態
            business_types = [
                ("小売店", "detail"),      # 明細書モード
                ("配達業", "simple"),      # 簡素モード  
                ("サービス業", "detail"),   # 明細書モード
                ("製造業", "detail"),      # 明細書モード
            ]
            
            for bt in business_types:
                self.cursor.execute(
                    "INSERT OR IGNORE INTO business_types (name, slip_mode) VALUES (?, ?)", bt
                )
            
            self.conn.commit()
            
        except Exception as e:
            logging.error(f"DBエラー: {e}")
    
    def setup_ui(self):
        # 業態選択
        self.business_type_dropdown = ft.Dropdown(
            label="業態を選択",
            options=[
                ft.dropdown.Option("小売店"),
                ft.dropdown.Option("配達業"),
                ft.dropdown.Option("サービス業"),
                ft.dropdown.Option("製造業"),
            ],
            on_change=self.on_business_change
        )
        
        # 動的フォームコンテナ
        self.form_container = ft.Container()
        
        # メインレイアウト
        self.page.add(
            ft.Column([
                ft.Text("🏢 業態適応伝票システム", size=20, weight=ft.FontWeight.BOLD),
                self.business_type_dropdown,
                self.form_container
            ], spacing=20)
        )
    
    def on_business_change(self, e):
        business_type = e.control.value
        self.load_adaptive_form(business_type)
    
    def load_adaptive_form(self, business_type: str):
        """業態に応じたフォーム読み込み"""
        
        if business_type == "配達業":
            self.form_container.content = self.create_simple_form()
        else:
            self.form_container.content = self.create_detail_form()
        
        self.page.update()
    
    def create_simple_form(self):
        """簡素フォーム（配達業向け）"""
        return ft.Container(
            content=ft.Column([
                ft.Text("⛽ 簡素伝票モード", size=16, weight=ft.FontWeight.BOLD),
                ft.TextField(label="顧客名"),
                ft.Row([
                    ft.TextField(label="数量", width=100),
                    ft.TextField(label="単価", width=100),
                    ft.TextField(label="金額", width=100, read_only=True)
                ]),
                ft.TextField(label="配達先"),
                ft.ElevatedButton("保存", bgcolor=ft.Colors.BLUE, color=ft.Colors.WHITE)
            ], spacing=10),
            padding=20,
            bgcolor=ft.Colors.WHITE,
            border_radius=10
        )
    
    def create_detail_form(self):
        """明細フォーム（小売店・サービス業向け）"""
        return ft.Container(
            content=ft.Column([
                ft.Text("📋 明細伝票モード", size=16, weight=ft.FontWeight.BOLD),
                ft.TextField(label="顧客名"),
                
                # 明細テーブル
                ft.DataTable(
                    columns=[
                        ft.DataColumn(ft.Text("商品名")),
                        ft.DataColumn(ft.Text("数量")),
                        ft.DataColumn(ft.Text("単価")),
                        ft.DataColumn(ft.Text("金額")),
                    ],
                    rows=[
                        ft.DataRow(
                            cells=[
                                ft.DataCell(ft.TextField(hint_text="商品名")),
                                ft.DataCell(ft.TextField(hint_text="数量")),
                                ft.DataCell(ft.TextField(hint_text="単価")),
                                ft.DataCell(ft.TextField(hint_text="金額")),
                            ]
                        )
                    ]
                ),
                
                ft.Row([
                    ft.Text("小計:", weight=ft.FontWeight.BOLD),
                    ft.TextField(label="小計", width=100, read_only=True)
                ]),
                ft.Row([
                    ft.Text("税:", weight=ft.FontWeight.BOLD),
                    ft.TextField(label="消費税", width=100, read_only=True)
                ]),
                ft.Row([
                    ft.Text("合計:", weight=ft.FontWeight.BOLD),
                    ft.TextField(label="合計", width=100, read_only=True)
                ]),
                
                ft.ElevatedButton("保存", bgcolor=ft.Colors.BLUE, color=ft.Colors.WHITE)
            ], spacing=10),
            padding=20,
            bgcolor=ft.Colors.WHITE,
            border_radius=10
        )

def main(page: ft.Page):
    try:
        app = AdaptiveSlipSystem(page)
        logging.info("業態適応伝票システム起動")
    except Exception as e:
        logging.error(f"起動エラー: {e}")

if __name__ == "__main__":
    ft.run(main)
