from base_resource import BaseResource,SendBaseResource
from overtime_model import OvertimeModel
# from werkzeug.datastructures import FileStorage
import os, werkzeug, base64, pandas as pd
from docx import Document
from io import BytesIO
from datetime import datetime

# ========== 新增加班紀錄 ==========
class OvertimeInsert(BaseResource):
    def __init__(self):
        super().__init__("InsertOvertime")
        self.parser.add_argument('person_id', required=True, help="人員ID，上限10字")
        self.parser.add_argument('department_id', help="部門ID，上限10字")
        self.parser.add_argument('date', help="加班日期，上限15字")
        self.parser.add_argument('start', help="開始時間，上限20字")
        self.parser.add_argument('end', help="結束時間，上限20字")
        self.parser.add_argument('hour', help="加班小時數")
        self.parser.add_argument('day_category', help="加班日型態")
        self.parser.add_argument('reason', help="加班原因，上限15字")
        self.parser.add_argument('is_key', help="是否有鑰匙")
        self.parser.add_argument('status', help="審核狀態")
    def post(self):
        args = self.parser.parse_args()
        model = OvertimeModel.FromDBByDate(args['person_id'],args['date'], self.log.SetMessage)
        if not model.isExist:
            model.SetPersonId(args['person_id'])
            model.SetDepartmentId(args['department_id'])
            model.SetDate(args['date'])
            model.SetStart(args['start'])
            model.SetEnd(args['end'])
            model.SetHour(args['hour'])
            model.SetDayCategory(args['day_category'])
            model.SetReason(args['reason'])
            model.SetIsKey(args['is_key'])
            model.SetStatus(args['status'])
            if model.InsertToDB(self.log.SetMessage):
                self.message = "person：{0} Date：{1} inserted".format(args['person_id'],args['date'])
            else:
                self.message = "person：{0} Date：{1} insert failed".format(args['person_id'],args['date'])
        else:
            self.message = "person：{0} Date：{1} is exist in database".format(args['person_id'],args['date'])
        return self.GetResponse()

# ========== 更新加班紀錄 ==========
class OvertimeUpdate(BaseResource):
    def __init__(self):
        super().__init__("UpdateOvertime")
        self.parser.add_argument('no', required=True, help="加班編號")
        self.parser.add_argument('person_id', required=True, help="人員ID，上限10字")
        self.parser.add_argument('department_id', help="部門ID，上限10字")
        self.parser.add_argument('date', help="加班日期，上限15字")
        self.parser.add_argument('start', help="開始時間，上限20字")
        self.parser.add_argument('end', help="結束時間，上限20字")
        self.parser.add_argument('hour', help="加班小時數")
        self.parser.add_argument('day_category', help="加班日型態")
        self.parser.add_argument('reason', help="加班原因，上限15字")
        self.parser.add_argument('is_key', help="是否有鑰匙")
        self.parser.add_argument('status', help="審核狀態")
    def post(self):
        args = self.parser.parse_args()
        model = OvertimeModel.FromDB(args['no'], self.log.SetMessage)
        if model.isExist:
            model.SetPersonId(args['person_id'])
            model.SetDepartmentId(args['department_id'])
            model.SetDate(args['date'])
            model.SetStart(args['start'])
            model.SetEnd(args['end'])
            model.SetHour(args['hour'])
            model.SetDayCategory(args['day_category'])
            model.SetReason(args['reason'])
            model.SetIsKey(args['is_key'])
            model.SetStatus(args['status'])
            if model.UpdateToDB(self.log.SetMessage):
                self.message = []
                if model.HasChangePersonId():
                    self.message.append(
                        "PersonId: {0} -> {1}".format(model.GetOldPersonId(), model.GetPersonId())
                    )
                if model.HasChangeDepartmentId():
                    self.message.append(
                        "DepartmentId: {0} -> {1}".format(model.GetOldDepartmentId(), model.GetDepartmentId())
                    )
                if model.HasChangeDate():
                    self.message.append(
                        "Date: {0} -> {1}".format(model.GetOldDate(), model.GetDate())
                    )
                if model.HasChangeStart():
                    self.message.append(
                        "Start: {0} -> {1}".format(model.GetOldStart(), model.GetStart())
                    )    
                if model.HasChangeEnd():
                    self.message.append(
                        "End: {0} -> {1}".format(model.GetOldEnd(), model.GetEnd())
                    )
                if model.HasChangeHour():
                    self.message.append(
                        "Hour: {0} -> {1}".format(model.GetOldHour(), model.GetHour())
                    )
                if model.HasChangeDayCategory():
                    self.message.append(
                        "DayCategory: {0} -> {1}".format(model.GetOldDayCategory(), model.GetDayCategory())
                    )
                if model.HasChangeReason():
                    self.message.append(
                        "Reason: {0} -> {1}".format(model.GetOldReason(), model.GetReason())
                    )
                if model.HasChangeIsKey():
                    self.message.append(
                        "IsKey: {0} -> {1}".format(model.GetOldIsKey(), model.GetIsKey())
                    )
                if model.HasChangeStatus():
                    self.message.append(
                        "Status: {0} -> {1}".format(model.GetOldStatus(), model.GetStatus())
                    )
                self.message = ", ".join(self.message) if len(self.message) > 0 else ""
            else:
                self.message = "person：{0} update Overtime failed".format(args['person_id'])
        else:
            self.message = "person：{0}'s Overtime isn't exist in database".format(args['person_id'])
        return self.GetResponse()
# ========== 刪除加班紀錄 ==========
class OvertimeDelete(BaseResource):
    def __init__(self):
        super().__init__("DeleteOvertime")
        self.parser.add_argument('no', required=True)
    def post(self):
        args = self.parser.parse_args()
        model = OvertimeModel.FromDB(args['no'], self.log.SetMessage)
        if model.isExist:
            if model.DeleteFromDB(self.log.SetMessage):
                self.message = "{0} deleted".format(args['no'], model.GetNow())
            else:
                self.message = "{0} delete failed".format(args['no'])
        else:
            self.message = "{0} isn't exist in database".format(args['no'])
        return self.GetResponse()    
# ========== 查詢所有加班紀錄 ==========
class OverTimeSelectAll(BaseResource):
    def __init__(self):
        super().__init__("SelectOvertime")
    def post(self, ID=None):
        models = OvertimeModel.AllFromDB(self.log.SetMessage)
        if len(models) > 0:
            self.data = []
            for model in models:
                self.data.append(model.ToDict())
            self.message = "{0} selected".format(len(self.data))
        else:
            self.message = "no data in database"
        return self.GetResponse()    
# ========== word匯出加班 ==========
class OvertimeToWord(SendBaseResource):
    def __init__(self):
        super().__init__(self)
        self.parser.add_argument('overtime_id', required=True, help="加班編號")
        self.parser.add_argument('person_id', required=True, help="員工編號")
        self.parser.add_argument('person_name', required=True, help="員工姓名")
        self.parser.add_argument('department', required=True, help="部門名稱")
        self.parser.add_argument('date', required=True, help="日期")
        self.parser.add_argument('day_category', required=True, help="加班日類別")
        self.parser.add_argument('start_time', required=True, help="開始時間")
        self.parser.add_argument('end_time', required=True, help="結束時間")
        self.parser.add_argument('hour', required=True, help="加班時數")
        self.parser.add_argument('reason', required=True, help="加班原因")
    def post(self):
        args = self.parser.parse_args()
        doc = Document('resources/test/加班申請表.docx')
        now = datetime.now()
        doc.paragraphs[2].text='加班編號:{0}                                  列印日期:{1}年 {2}月 {3}日'.format(args['overtime_id'],now.year,now.month,now.day)
        tables = doc.tables
        table = tables[0]
        table.cell(0,1).text=args['person_id']
        table.cell(1,1).text=args['person_name']
        table.cell(2,1).text=args['department']
        table.cell(3,1).text=args['date']
        table.cell(3,4).text=args['day_category']
        table.cell(4,1).text=args['start_time']
        table.cell(4,4).text=args['end_time']
        table.cell(5,1).text=args['hour']
        table.cell(6,1).text=args['reason']
        stream = BytesIO()
        doc.save(stream)
        stream.seek(0)
        #doc.save('/home/shuochen/Documents/punch_card_api/flask/notebook/resources/test/申請書{0}.docx'.format(args['name']))
        return self.GetWordResponse("加班單{0}".format(args['overtime_id']), stream)
# ========== *新版本-word匯出加班(吉鑫) ==========
class OvertimeToWordVerson2(SendBaseResource):
    def __init__(self):
        super().__init__(self)
        self.parser.add_argument('overtime_id', required=True, help="加班編號")
        self.parser.add_argument('person_id', required=True, help="員工編號")
        self.parser.add_argument('person_name', required=True, help="員工姓名")
        self.parser.add_argument('department', required=True, help="部門名稱")
        self.parser.add_argument('date', required=True, help="日期")
        self.parser.add_argument('start_time', required=True, help="開始時間")
        self.parser.add_argument('end_time', required=True, help="結束時間")
        self.parser.add_argument('hour', required=True, help="加班時數")
        self.parser.add_argument('reason', required=True, help="加班原因")
    def post(self):
        args = self.parser.parse_args()
        doc = Document('resources/test/加班申請表_吉鑫.docx')
        now = datetime.now()
        doc.paragraphs[2].text='加班編號:{0}                                     列印日期:{1}年 {2}月 {3}日'.format(args['overtime_id'],now.year,now.month,now.day)
        tables = doc.tables
        table = tables[0]
        table.cell(0,1).text=args['person_id']
        table.cell(1,1).text=args['person_name']
        table.cell(2,1).text=args['department']
        table.cell(3,1).text=args['date']
        table.cell(4,1).text=args['start_time']
        table.cell(4,3).text=args['end_time']
        table.cell(5,1).text=args['hour']
        table.cell(6,1).text=args['reason']
        stream = BytesIO()
        doc.save(stream)
        stream.seek(0)
        #doc.save('/home/shuochen/Documents/punch_card_api/flask/notebook/resources/test/申請書{0}.docx'.format(args['name']))
        return self.GetWordResponse("加班單{0}".format(args['overtime_id']), stream)