def handle_message(event):
    UserId = event.source.user_id
    UserMessage = event.message.text
    ert = event.reply_token
    firebase_rec = {}
        
    if '目前訂位' in UserMessage:# in c:
        doc_ref = firedb.collection_group('訂位紀錄')
        docs = doc_ref.stream() # generator
        reply_message = '目前有以下訂位: '
        for doc in docs:
            dic = doc.to_dict()
            for record in dic:
                try:
                    if datetime.strptime(dic[record][1], '%Y-%m-%dT%H:%M') > datetime.now():
                        reply_message += '\n\n姓名: ' + dic[record][0] + '\n預約時間: ' + dic[record][1].replace('T',' ') + "\n人數: " + dic[record][2]
                    else:
                        pass
                except: # NoneType
                    pass
            #print(u'{} => {}'.format(doc.id, doc.to_dict()))
        line_bot_api.reply_message(ert, TextSendMessage(text=reply_message) )
        return 0

    ''' 發送公告step1 '''
    if '發送公告' in UserMessage: 
        firebase_rec['step'] = 'b1'
        doc_ref = firedb.collection('發送公告').document(UserId)
        doc_ref.set(firebase_rec)
        line_bot_api.reply_message(ert, TextSendMessage(text="注意!!!\n下一句傳輸之訊息將會公告給所有客人,請確保訊息無誤再傳輸!") )
        return 0
    
    ''' 發送公告step2 '''
    doc_ref = firedb.collection('發送公告').document(UserId)
    doc = doc_ref.get()
    if doc.to_dict()['step'] == 'b1' and '目前訂位' not in UserMessage and '取消訂位' not in UserMessage and '發送公告' not in UserMessage:
        firebase_rec['step'] = 'b2'
        doc_ref = firedb.collection('發送公告').document(UserId)
        doc_ref.update(firebase_rec) # update 狀態

        doc_ref = firedb.collection_group('客戶端') # 收集客戶端全部的 User Id
        docs = doc_ref.stream() # generator
        for doc in docs:
            dic = doc.to_dict()
            line_bot_api_client.push_message(dic['User_Id'], TextSendMessage(text=UserMessage) ) # 客戶端的LineBot會傳公告訊息給客戶
        
        profile = line_bot_api.get_profile(UserId)
        doc_ref = firedb.collection_group('控制端')
        docs = doc_ref.stream() # generator
        for doc in docs:
            line_bot_api.push_message(doc.to_dict()['User_Id'] , TextSendMessage(
                text='管理員 {0} 已發送公告!\n公告內容如下:\n{1}'.format(profile.display_name, UserMessage)) )
        return 0
    elif doc.to_dict()['step'] == 'b1':
        firebase_rec['step'] = 'b2'
        doc_ref = firedb.collection('發送公告').document(UserId)
        doc_ref.update(firebase_rec)
        line_bot_api.reply_message(ert, TextSendMessage(text='取消公告'))
        if '目前訂位' in UserMessage:
            doc_ref = firedb.collection_group('訂位紀錄')
            docs = doc_ref.stream() # generator
            reply_message = '目前有以下訂位: '
            for doc in docs:
                dic = doc.to_dict()
                for record in dic:
                    try:
                        if datetime.strptime(dic[record][1], '%Y-%m-%dT%H:%M') > datetime.now():
                            reply_message += '\n\n姓名: ' + dic[record][0] + '\n預約時間: ' + dic[record][1].replace('T',' ') + "\n人數: " + dic[record][2]
                        else:
                            pass
                    except: # NoneType
                        pass
            line_bot_api.reply_message(ert, TextSendMessage(text=reply_message) )
            return 0
        elif '取消訂位' in UserMessage:
            TimeMessage = AllMessage.Time_Message()
            line_bot_api.reply_message(ert, TimeMessage) # 傳送選擇日期的Message
            return 0
        elif '發送公告' in UserMessage:
            firebase_rec['step'] = 'b1'
            doc_ref = firedb.collection('發送公告').document(UserId)
            doc_ref.set(firebase_rec)
            line_bot_api.reply_message(ert, TextSendMessage(text="注意!!!\n下一句傳輸之訊息將會公告給所有客人,請確保訊息無誤再傳輸!") )
            return 0

        return 0
    
    ''' Manager取消客戶訂位step1 '''
    if '取消訂位' in UserMessage:
        TimeMessage = AllMessage.Time_Message()
        line_bot_api.reply_message(ert, TimeMessage) # 傳送選擇日期的Message
        return 0
    
    ''' 清空過往訂單(暫時沒有開放) '''
    if '清空' in UserMessage:
        doc_ref = firedb.collection_group('訂位紀錄')
        docs = doc_ref.stream() # generator
        # 1個ID(collection)算一次迴圈
        for doc in docs:
            for d in doc.to_dict(): # for each in dict
                try:                    
                    if (datetime.strptime(doc.to_dict()[d][1].split("T")[0], '%Y-%m-%d') < datetime.today()):
                        doc_ref = firedb.collection('訂位紀錄').document(doc.id)
                        cancel_rec = {}
                        cancel_rec[d] = None
                        doc_ref.update(cancel_rec) # 用None取代
                except:
                    pass

    else:
        line_bot_api.reply_message(ert, TextSendMessage(text='無效操作') )
        return 0
def handle_postback(event):
    UserId = event.source.user_id
    ert = event.reply_token
    firebase_rec = {}
    data = event.postback.data
    doc_ref = firedb.collection('是否訂位').document(UserId)
    doc = doc_ref.get()
    print(event.postback)
    ''' 訂位功能step3 '''
    if doc.to_dict()['status'] == 'order' and doc.to_dict()['step'] == '2':
        firebase_rec['step'] = '3'
        firebase_rec['Name'] = doc.to_dict()['Name'] + event.postback.data
        doc_ref.update(firebase_rec)
        TimeMessage = AllMessage.Time_Message(number=1)
        line_bot_api.reply_message(ert, TimeMessage)  # 傳送選擇日期的Message
        return 0
    ''' 訂位功能step3.5 '''
    if event.postback.data == 'selected time' and doc.to_dict(
    )['status'] == 'order' and doc.to_dict()['step'] == '3':
        # 傳送選擇時間的Message, if 正確下一個step, 錯誤叫他重新點
        hour = int(event.postback.params['datetime'][-5:-3])
        minute = int(event.postback.params['datetime'][-2:])
        Select_time = hour * 3600 + minute * 60
        if 49800 >= Select_time >= 41400 or 71400 >= Select_time >= 61200:
            firebase_rec['step'] = '3.5'
            doc_ref.update(firebase_rec)
            ConfirmPostMessage = AllMessage.Confirm_PostMessage(
                event.postback.params['datetime'], number=5)
            line_bot_api.reply_message(ert, ConfirmPostMessage)
        else:
            line_bot_api.reply_message(ert, TextSendMessage(text='麻煩請選擇其他時間'))
        return 0
    ''' 訂位功能step4 '''
    if doc.to_dict()['status'] == 'order' and doc.to_dict()['step'] == '3.5':
        if 'yes' in event.postback.data:
            data = event.postback.data.split(' ')
            firebase_rec['step'] = '4'
            firebase_rec['selected_time'] = data[1]
            doc_ref.update(firebase_rec)
            line_bot_api.reply_message(ert, TextSendMessage(text='請問共有幾位貴賓?'))
        else:
            firebase_rec['step'] = '3'
            doc_ref.update(firebase_rec)
            TimeMessage = AllMessage.Time_Message(number=1)
            line_bot_api.reply_message(ert, TimeMessage)  # 傳送選擇日期的Message
        return 0
    ''' 取消訂位step2 '''
    if doc.to_dict()['step'] == 'C1' and doc.to_dict()['status'] == 'cancel':
        firebase_rec['step'] = 'C2'
        doc_ref.update(firebase_rec)

        ConfirmMessage = AllMessage.Confirm_PostMessage(data, number=1)
        line_bot_api.reply_message(ert, ConfirmMessage)
        return 0
    ''' 取消訂位step3 '''
    if doc.to_dict()['step'] == 'C2' and doc.to_dict()['status'] == 'cancel':
        if data == 'no':
            firebase_rec['step'] = 'F'
            firebase_rec['status'] = 'free'
            doc_ref.update(firebase_rec)
            line_bot_api.reply_message(ert, TextSendMessage(text='感謝您不取消訂位~'))
            return 0
        doc_ref = firedb.collection('訂位紀錄').document(UserId)
        doc = doc_ref.get()
        reply_message = '[取消訂位]\n詳細資訊如下:\n姓名: ' + doc.to_dict(
        )[data][0] + '\n預約日期: ' + doc.to_dict()[data][1].split(
            'T')[0] + '\n預約時間: ' + doc.to_dict()[data][1].split(
                'T')[1] + '\n預約人數: ' + doc.to_dict(
                )[data][2] + '\n訂單編號: ' + doc.to_dict()[data][4]

        cancel_rec = {}
        cancel_rec[data] = None
        doc_ref.update(cancel_rec)  # 用None 取代

        firebase_rec['step'] = 'F'
        firebase_rec['status'] = 'free'
        doc_ref = firedb.collection('是否訂位').document(UserId)
        doc_ref.update(firebase_rec)

        line_bot_api.reply_message(ert, TextSendMessage(text=reply_message))

        doc_ref = firedb.collection_group('控制端')
        docs = doc_ref.stream()  # generator
        for doc in docs:
            line_bot_api_server.push_message(
                doc.to_dict()['User_Id'],
                TextSendMessage(text='[客人取消訂位]\n詳細資訊如下:\n' +
                                reply_message[10:]))  # 通知Manager端 取消訂位

        return 0
    ''' 新增餐點 '''
    if bool(re.match('加', event.postback.data)):
        data = event.postback.data.split(' ')  # list
        if doc.to_dict()['status'] == 'oout':
            doc_ref = firedb.collection('外帶購物車').document(UserId)
        else:
            doc_ref = firedb.collection('內用購物車').document(UserId)
        doc = doc_ref.get()
        if doc.to_dict() == None:  # 無過往紀錄
            firebase_rec[data[1]] = 1
            doc_ref.set(firebase_rec)
        else:
            if data[1] in doc.to_dict():
                firebase_rec[data[1]] = doc.to_dict()[data[1]] + 1
                doc_ref.update(firebase_rec)
            else:
                firebase_rec[data[1]] = 1
                doc_ref.update(firebase_rec)
        return 0
    ''' 刪除餐點 '''
    if bool(re.match('減', event.postback.data)):
        data = event.postback.data.split(' ')
        if doc.to_dict()['status'] == 'oout':
            doc_ref = firedb.collection('外帶購物車').document(UserId)
        else:
            doc_ref = firedb.collection('內用購物車').document(UserId)
        doc = doc_ref.get()
        if doc.to_dict() == None:  # 無過往紀錄
            pass
        else:
            if data[1] in doc.to_dict():
                if doc.to_dict()[data[1]] == 0:
                    pass
                else:
                    firebase_rec[data[1]] = doc.to_dict()[data[1]] - 1
                    if firebase_rec[data[1]] == 0:
                        firebase_rec[data[1]] = None
                    doc_ref.update(firebase_rec)
            else:
                pass
        return 0
    ''' 當日外帶 step3 '''
    if doc.to_dict()['status'] == 'oout' and doc.to_dict()['step'] == '3':
        # 傳送選擇時間的Message, if 正確下一個step, 錯誤叫他重新點
        hour = int(event.postback.params['datetime'][-5:-3])
        minute = int(event.postback.params['datetime'][-2:])
        Select_time = hour * 3600 + minute * 60
        if 49800 >= Select_time >= 41400 or 71400 >= Select_time >= 61200:
            firebase_rec['step'] = '3.5'
            doc_ref.update(firebase_rec)
            ConfirmPostMessage = AllMessage.Confirm_PostMessage(
                event.postback.params['datetime'], number=5)
            line_bot_api.reply_message(ert, ConfirmPostMessage)
        else:
            line_bot_api.reply_message(ert, TextSendMessage(text='麻煩請選擇其他時間'))
        return 0
    ''' 當日外帶 step4 '''
    if doc.to_dict()['status'] == 'oout' and doc.to_dict()['step'] == '3.5':
        if bool(re.match('yes', event.postback.data)):
            data = event.postback.data.split(' ')
            firebase_rec['selected_time'] = data[1]
            firebase_rec['step'] = 'F'
            firebase_rec['status'] = 'free'
            doc_ref.update(firebase_rec)

            doc_ref = firedb.collection('外帶購物車').document(UserId)
            dict_doc = doc_ref.get().to_dict()

            profile = line_bot_api.get_profile(UserId)
            reply_message = "顧客 " + profile.display_name + " 的外帶詳細如下:" + "\n外帶時間: " + data[
                1]
            for key, value in dict_doc.items():
                reply_message += "\n" + key + ":" + str(value) + "份"
            firebase_rec = None
            doc_ref.set(firebase_rec)
            line_bot_api.reply_message(ert,
                                       TextSendMessage(text=reply_message))

            doc_ref = firedb.collection_group('控制端')
            docs = doc_ref.stream()  # generator
            for doc in docs:
                line_bot_api_server.push_message(
                    doc.to_dict()['User_Id'],
                    TextSendMessage(
                        text=reply_message))  # 通知Manager端, 讓其確認是否同意
        else:
            firebase_rec['step'] = '3'
            doc_ref.update(firebase_rec)
            TimeMessage = AllMessage.Time_Message(number=1)
            line_bot_api.reply_message(ert, TimeMessage)  # 傳送選擇日期的Message
        return 0

    if bool(re.match('confirm', event.postback.data)):
        firebase_rec['step'] = '2'
        doc_ref.update(firebase_rec)
        if doc.to_dict()['status'] == 'oout':
            doc_ref = firedb.collection('外帶購物車').document(UserId)
        else:
            doc_ref = firedb.collection('內用購物車').document(UserId)
        doc = doc_ref.get()
        dict_doc = doc.to_dict()
        #{'東坡肉': 1, '芒果炒雞柳': 3}
        ConfirmPostMessage = AllMessage.Confirm_PostMessage(dict_doc, 6)
        line_bot_api.push_message(UserId, ConfirmPostMessage)
        return 0
    ''' 確認餐點 step2'''
    if bool(re.match('menu',
                     event.postback.data)) and doc.to_dict()['step'] == '2':
        if bool(re.match('yes', event.postback.data)):
            if doc.to_dict()['status'] == 'oin':
                firebase_rec['step'] = 'F'
                firebase_rec['status'] = 'free'
                doc_ref.update(firebase_rec)
                doc_ref = firedb.collection('內用購物車').document(UserId)
                line_bot_api.push_message(
                    UserId,
                    TextSendMessage(text='好的! 已幫您告知告知店家,請於用餐完畢後結帳,感謝您!'))

                data = event.postback.data.split(' ')[2:]
                profile = line_bot_api.get_profile(UserId)
                reply_message = "顧客 " + profile.display_name + " 的店內點餐餐點詳細如下:"
                for d in range(0, len(data) - 1, 2):
                    reply_message = reply_message + '\n' + data[
                        d] + ' ' + data[d + 1] + "份"
                firebase_rec = None
                doc_ref.set(firebase_rec)
                doc_ref = firedb.collection_group('控制端')
                docs = doc_ref.stream()  # generator
                for doc in docs:
                    line_bot_api_server.push_message(
                        doc.to_dict()['User_Id'],
                        TextSendMessage(
                            text=reply_message))  # 通知Manager端, 讓其確認
            else:
                firebase_rec['step'] = '3'
                doc_ref.update(firebase_rec)
                TimeMessage = AllMessage.Time_Message(number=1)
                line_bot_api.reply_message(ert, TimeMessage)  # 傳送選擇日期的Message
        else:
            Menu_Message = AllMessage.Menu_Message()
            line_bot_api.push_message(UserId, Menu_Message)
        return 0
    else:
        line_bot_api.reply_message(ert, TextSendMessage(text='麻煩請重新操作!!'))
        return 0