from django.utils import timezone
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.contrib.auth.decorators import permission_required
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from leave.models import LeavePlan, LeaveHoliday, LeaveEmployee, LeaveType
from .models import ITcontractDB, ITContractEmailAlert
from django.urls import reverse_lazy
from django.http import HttpResponseRedirect
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.utils.timezone import localtime
from datetime import datetime
from django.conf import settings
from django.http import HttpResponse
from django.views import generic
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.contrib.auth.models import User, Group
from datetime import timedelta, datetime
from django.db.models import Sum
from django.utils.dateparse import parse_datetime
from django.http import JsonResponse
from post_office import mail
from page.rules import *
from django.core.files.storage import FileSystemStorage
from django.utils import translation
from django.core import serializers
from django.utils.translation import ugettext as _
from django.db.models import CharField, Value
from django.utils.timezone import now
from django.core.exceptions import ValidationError
from base64 import b64encode
from django.db import connection
from .forms import ITcontractDBForm
from django.http import FileResponse
from gfthboard.settings import MEDIA_ROOT
from os import path
import django.db as db
import xlwt
import sys
import json
import collections

from django.contrib.auth.models import User, Group

from rest_framework import viewsets
from rest_framework import permissions
# from .serializers import UserSerializer, GroupSerializer, ITContractSerializer
from .serializers import ITContractSerializer

current_year = datetime.now().year

@permission_required('ITcontract.view_itcontractdb', login_url='/accounts/login/')
def ITcontractPolicy(request):

    print("ITcontractPolicy()")

    username = request.user.username
    user_language = getDefaultLanguage(request.user.username)
    translation.activate(user_language)
    page_title = settings.PROJECT_NAME
    db_server = settings.DATABASES['default']['HOST']
    project_name = settings.PROJECT_NAME
    project_version = settings.PROJECT_VERSION
    today_date = getDateFormatDisplay(user_language)

    itcontractdb_object = None
    it_contract_list = []

    city_object = None
    city_list = []
    record = {}

    customer_obj = None
    customer_list = []

    contract_type_obj = None
    contract_type_list = []

    it_contract_id = ""
    department = ""
    vendor = ""
    description = ""
    contact = ""
    phone = ""
    email = ""
    start_date = ""
    end_date = ""
    price = ""
    remark = ""
    upd_by = ""

    dept_id = ""
    dept_en = ""

    if isStillUseDefaultPassword(request):
        template_name = 'page/force_change_password.html'
        return render(request, template_name, {})
    else:
        if isPasswordExpired(request):
            if isPasswordChanged(request):
                template_name = 'page/force_change_password.html'
                return render(request, template_name, {})

    if user_language == "th":
        if request.user.username == "999999":
            username_display = request.user.first_name
        else:
            username_display = LeaveEmployee.objects.filter(emp_id=request.user.username).values_list('emp_fname_th', flat=True).get()
    else:
        if request.user.username == "999999":
            username_display = request.user.first_name
        else:
            username_display = LeaveEmployee.objects.filter(emp_id=request.user.username).values_list('emp_fname_en', flat=True).get()

    # ***************************
    # Check Contract List
    # ***************************
    dept_id, dept_en = getDepartmentInfo(username)

    sql = "select "
    sql += "con.id, con.dept, con.vendor, con.description, con.person, con.tel, con.e_mail, con.start_date, con.end_date, con.price, "
    sql += "con.remark, con.upd_by, con.afile, con.contract_number, ct.name_en as contract_name_en, con.cnt_id, vca.cus_name_en, vca.zone_en, "
    sql += "con.quantity, con.pr_number, con.po_number, datediff(day, con.end_date, getdate()) as date_diff "
    sql += "from itcontractdb con "
    sql += "left join itcontract_contract_type ct on con.contract_type=ct.id "
    sql += "left join v_contract_active vca on con.cnt_id=vca.cnt_id "
    sql += "where con.dept_id=" + str(dept_id) + " and upd_flag!='D' "
    sql += "order by date_diff desc;"
    # sql += "order by con.id;"
    print("SQLxx : ", sql)

    try:
        with connection.cursor() as cursor:
            cursor.execute(sql)
            itcontractdb_object = cursor.fetchall()

            if itcontractdb_object:
                str_today_date = datetime.now().strftime("%Y-%m-%d")
                today_date = datetime.strptime(str_today_date, '%Y-%m-%d').date()

                for item in itcontractdb_object:
                    it_contract_id = item[0]

                    if item[13]:
                        if item[13].strip() != "":
                            contract_number_display = item[13]
                        else:
                            contract_number_display = it_contract_id
                    else:
                        contract_number_display = it_contract_id

                    # print("contract_number_display = ", contract_number_display)

                    department = item[1].replace("/Indirect Functional", "").replace("/Bangkok/Indirect Field", "") if item[1] else ""

                    vendor = item[2] if item[2] else ""
                    description = item[3] if item[3] else ""
                    contact = item[4]
                    phone = item[5]
                    email = item[6]
                    start_date = item[7]
                    end_date = item[8]
                    price = item[9]
                    remark = item[10] if item[10] else ""
                    upd_by = item[11]
                    contract_type_name_en = item[14] if item[14] else "ไม่ระบุประเภท"

                    cnt_id = item[15] if item[15] else ""
                    if item[15]:
                        post_number = convertCntIdToPostNo(cnt_id)
                    else:
                        post_number = ""

                    # post_name = item[16][0:30]+"..." if item[16] else ""
                    post_name = item[16].strip() if item[16] else ""

                    zone_name_en = item[17] if item[17] else ""
                    zone_name_en = zone_name_en.replace("ZONE ", "").replace("PHUKET", "P").replace("SAMUI", "S").replace("SONGKLA","").replace("KHON KAEN", "K")

                    quantity = item[18] if item[18] else 0
                    pr_number = item[19] if item[19] else ""
                    po_number = item[20] if item[20] else ""

                    if (end_date.date() >= today_date):
                        is_contract_expired = False
                    else:
                        is_contract_expired = True

                    remaining_day = end_date.date() - today_date

                    # contract_number_display = item[12].strip if item[12] else it_contract_id

                    record = {
                        "id": it_contract_id,
                        "contract_number_display": contract_number_display,
                        "dept": department,
                        "vendor": vendor,
                        "description": description,
                        "contact": contact,
                        "phone": phone,
                        "email": email,
                        "start_date": start_date,
                        "end_date": end_date,
                        "price": price,
                        "remark": remark,
                        "upd_by": upd_by,
                        "is_contract_expired": is_contract_expired,
                        "remaining_day": remaining_day.days,
                        "contract_type_name_en": contract_type_name_en,
                        "post_number": post_number,
                        "post_name": post_name,
                        "zone_name_en": zone_name_en,
                        "quantity": quantity,
                        "pr_number": pr_number,
                        "po_number": po_number,
                    }

                    it_contract_list.append(record)

            is_error = False
            message = "No error"

    except db.OperationalError as e:
        is_error = True
        message = "Error message: " + str(e)
    except db.Error as e:
        is_error = True
        message = "Error message: " + str(e)
    finally:
        cursor.close()

    # *****************
    # Get last login
    # *****************
    last_login = getLastLogin(request)

    # *****************
    # Get city
    # *****************
    sql = "select city_id, city_th, city_en from t_city;"
    print("SQL : ", sql)
    try:
        with connection.cursor() as cursor:
            cursor.execute(sql)
            city_object = cursor.fetchall()

            for item in city_object:
                city_id = item[0]
                city_th = item[1]
                city_en = item[2]
                record = {"city_id": city_id, "city_th": city_th, "city_en": city_en}
                city_list.append(record)

            is_error = False
            message = "No error"

    except db.OperationalError as e:
        is_error = True
        message = "Error message: " + str(e)
    except db.Error as e:
        is_error = True
        message = "Error message: " + str(e)
    finally:
        cursor.close()

    # *********************
    # Get Customer List
    # *********************
    # sql = "select cnt_id, cus_name_en, zone_en from complaint_contract order by cnt_id;"
    sql = "select cnt_id, cus_name_th, zone_en, city_th from tcl_contract_qty order by cnt_id;"
    try:
        with connection.cursor() as cursor:
            cursor.execute(sql)
            customer_obj = cursor.fetchall()

        if customer_obj is not None:
            for item in customer_obj:
                cnt_id = item[0]

                cus_name_en = item[1].strip() if item[1] else ""
                zone_en = item[2].strip() if item[2] else ""
                zone_en = zone_en.replace("ZONE ", "")
                city_th = item[3].strip() if item[3] else ""

                record = {"cnt_id":cnt_id, "cus_name_en": cus_name_en, "zone_en": zone_en, "city_ty": city_th}
                customer_list.append(record)
            is_error = False
            message = "No error"

    except db.OperationalError as e:
        is_error = True
        message = "Error message: " + str(e)
    except db.Error as e:
        is_error = True
        message = "Error message: " + str(e)
    finally:
        cursor.close()

    # *********************
    # Get Contract Type
    # *********************
    sql = "select id, name_en, name_th from itcontract_contract_type;"
    try:
        with connection.cursor() as cursor:
            cursor.execute(sql)
            contract_type_obj = cursor.fetchall()

        if contract_type_obj is not None:
            for item in contract_type_obj:
                contract_type_id = item[0]
                name_en = item[1].strip() if item[1] else ""
                name_th = item[2].strip() if item[2] else ""

                record = {"contract_type_id":contract_type_id, "name_en": name_en, "name_th": name_th}
                contract_type_list.append(record)
            is_error = False
            message = "No error"

    except db.OperationalError as e:
        is_error = True
        message = "Error message: " + str(e)
    except db.Error as e:
        is_error = True
        message = "Error message: " + str(e)
    finally:
        cursor.close()

    print("contract_type_list : ", len(contract_type_list))

    sql = "select conu.emp_id, conu.dept_id, d.dept_th, d.dept_en, d.dept_sht from itcontract_user conu left join com_department d on conu.dept_id=d.dept_id where conu.emp_id=" + str(username) + ";";
    user_department_name = ""
    try:
        with connection.cursor() as cursor:
            cursor.execute(sql)
            user_department = cursor.fetchone()

        if user_department:
            dept_id = user_department[1]
            user_department_name = user_department[4]

            is_error = False
            message = "No error"

    except db.OperationalError as e:
        is_error = True
        message = "Error message: " + str(e)
    except db.Error as e:
        is_error = True
        message = "Error message: " + str(e)
    finally:
        cursor.close()

    print("dept_id : ", dept_id)

    if dept_id == 2010:
        template_name = 'ITcontract/sp_contract_policy.html'
    elif dept_id == 3102:
        template_name = 'ITcontract/ITcontract_policy.html'
    elif dept_id == 1040:
        template_name = 'ITcontract/ITcontract_policy.html'
    else:
        template_name = 'ITcontract/ITcontract_policy.html'

    return render(request,
        template_name, {
        'page_title': settings.PROJECT_NAME,
        'today_date': today_date,
        'project_version': settings.PROJECT_VERSION,
        'db_server': settings.DATABASES['default']['HOST'],
        'project_name': settings.PROJECT_NAME,
        'user_language': user_language,
        'username_display': username_display,
        'ITcontractList': it_contract_list,
        'today_date': today_date,
        'last_login': last_login,
        'dept_id': dept_id,
        'dept_en': dept_en,
        'city_list': list(city_list),
        'customer_list': list(customer_list),
        'contract_type_list': list(contract_type_list),
        'department_name': user_department_name,
    })

@permission_required('ITcontract.view_itcontractdb', login_url='/accounts/login/')
def ajax_get_it_contract_item(request):

    print("EDIT")

    it_contract_id = request.POST.get("id")
    print("it_contract_id", it_contract_id)

    record = {}
    itcontract_list = []
    contract_obj = None
    contract_list = []

    is_error = True
    error_message = ""
    dept = ""
    vendor = ""
    description = ""
    person = ""
    tel = ""
    price = 0
    e_mail = ""
    remark = ""
    start_date = ""
    end_date = ""
    is_attacehed = False
    attached_file_name = ""
    username = request.user.username

    if it_contract_id is not None:
        sql = "select "
        sql += "con.id, con.dept, con.description, con.vendor, con.ae_mail, con.ae_mail1, con.description1, con.e_mail, con.end_date, "     # 8
        sql += "con.op1, con.op2, con.op3, con.opd1, con.opd2, con.opn1, con.opn2, con.opn3, con.person, con.price, con.remark, "           # 19
        sql += "con.start_date, con.tel, con.upd_by, con.upd_date, con.upd_flag, con.afile, con.afile_data, con.turn_off_notification, "    # 27
        sql += "con.contract_type, con.contract_number, con.cnt_id, con.dept_id, con.cus_name_en, con.cus_name_th, con.city_id, "           # 34
        sql += "con.quantity, con.pr_number, con.po_number " # 37
        sql += "from itcontractdb con "
        sql += "where con.id=" + str(it_contract_id) + ";"
        print("XXXAAA : ", sql)
        try:
            with connection.cursor() as cursor:
                cursor.execute(sql)
                contract_obj = cursor.fetchone()
                is_error = False
                message = "No error"

        except db.OperationalError as e:
            is_error = True
            message = "Error message: " + str(e)
        except db.Error as e:
            is_error = True
            message = "Error message: " + str(e)
        finally:
            cursor.close()

    if not is_error:
        if contract_obj:
            error_message = ""
            contract_id = contract_obj[0]
            dept = contract_obj[1] if contract_obj[1] else ""
            vendor = contract_obj[3] if contract_obj[3] else ""
            description = contract_obj[2] if contract_obj[2] else ""
            person = contract_obj[17] if contract_obj[17] else ""
            tel = contract_obj[21] if contract_obj[21] else ""
            price = contract_obj[18] if contract_obj[18] else 0
            e_mail = contract_obj[7] if contract_obj[7] else ""
            remark = contract_obj[19] if contract_obj[19] else ""
            start_date = contract_obj[20].strftime("%d/%m/%Y") if contract_obj[20] else ""
            end_date = contract_obj[8].strftime("%d/%m/%Y") if contract_obj[8] else ""
            turn_off_notification = contract_obj[27] if contract_obj[27] else 0
            contract_number = contract_obj[29].strip() if contract_obj[29] else ""
            contract_type = contract_obj[28] if contract_obj[28] else 0
            cnt_id = contract_obj[30] if contract_obj[30] else ""
            city_id = contract_obj[34] if contract_obj[34] else ""
            afile = contract_obj[25] if contract_obj[25] else ""
            afile_data = contract_obj[26] if contract_obj[26] else None
            quantity = contract_obj[35] if contract_obj[35] else 0
            pr_number = contract_obj[36] if contract_obj[36] else ""
            po_number = contract_obj[37] if contract_obj[37] else ""

            if afile != "":
                if afile_data is not None:
                    attacehed_file = True
                    attached_file_name = str(afile)
            else:
                attacehed_file = False

            if contract_number == "":
                contract_number = contract_id

            response = JsonResponse(data={
                "success": True,
                "is_error": is_error,
                "error_message": error_message,
                "it_contract_id": it_contract_id,
                "dept": dept,
                "vendor": vendor,
                "description": description,
                "person": person,
                "tel": tel,
                "price": price,
                "e_mail": e_mail,
                "remark": remark,
                "start_date": start_date,
                "end_date": end_date,
                "attacehed_file": attacehed_file,
                "attached_file_name": attached_file_name,
                "turn_off_notification": turn_off_notification,
                "contract_number": contract_number,
                "contract_type": contract_type,
                "cnt_id": cnt_id,
                "city_id": city_id,
                "quantity": quantity,
                "pr_number": pr_number,
                "po_number": po_number,
            })

    print("AAABBBCCC")

    response.status_code = 200
    return response

    '''
    if it_contract_id is not None:
        itcontract = ITcontractDB.objects.filter(pk=it_contract_id).get()
        if itcontract is not None:
            error_message = ""
            dept = "" if itcontract.dept is None else itcontract.dept
            vendor = "" if itcontract.vendor is None else itcontract.vendor
            description = "" if itcontract.description is None else itcontract.description
            person = "" if itcontract.person is None else itcontract.person
            tel = "" if itcontract.tel is None else itcontract.tel
            price = 0 if itcontract.price is None else itcontract.price
            e_mail = "" if itcontract.e_mail is None else itcontract.e_mail
            remark = "" if itcontract.remark is None else itcontract.remark
            start_date = None if itcontract.start_date is None else itcontract.start_date.strftime("%d/%m/%Y")
            end_date = None if itcontract.end_date is None else itcontract.end_date.strftime("%d/%m/%Y")
            turn_off_notification = True if itcontract.turn_off_notification else False

            contract_number = itcontract.contract_number.strip() if itcontract.contract_number else ""
            contract_type = itcontract.contract_type if itcontract.contract_type else 0
            cnt_id = itcontract.cnt_id if itcontract.cnt_id else ""
            city_id = itcontract.city_id if itcontract.city_id else ""

            if itcontract.afile != "":
                if itcontract.afile_data is not None:
                    attacehed_file = True
                    attached_file_name = str(itcontract.afile)
            else:
                attacehed_file = False

            is_error = False
            error_message = ""
        else:
            error_message = "Not found"
    else:
        error_message = "Not found"

    response = JsonResponse(data={
        "success": True,
        "is_error": is_error,
        "error_message": error_message,
        "it_contract_id": it_contract_id,
        "dept": dept,
        "vendor": vendor,
        "description": description,
        "person": person,
        "tel": tel,
        "price": price,
        "e_mail": e_mail,
        "remark": remark,
        "start_date": start_date,
        "end_date": end_date,
        "attacehed_file": attacehed_file,
        "attached_file_name": attached_file_name,
        "turn_off_notification": turn_off_notification,
        "contract_number": contract_number,
        "contract_type": contract_type,
        "cnt_id": cnt_id,
        "city_id": city_id,
    })

    response.status_code = 200
    return response
    '''

@permission_required('ITcontract.add_itcontractdb', login_url='/accounts/login/')
def ajax_add_it_contract_item(request):
    is_error = True
    message = ""

    if request.POST.get("contract_number"):
        contract_number = request.POST.get("contract_number")
    else:
        contract_number = ""

    if request.POST.get("contract_type_option"):
        contract_type = request.POST.get("contract_type_option")
    else:
        contract_type = ""

    if request.POST.get("post_option"):
        post_number = request.POST.get("post_option")
    else:
        post_number = ""

    if request.POST.get("city_option"):
        city = request.POST.get("city_option")
    else:
        city = ""

    if request.POST.get("dept_add"):
        dept = request.POST.get("dept_add")
    else:
        dept = ""

    vendor = request.POST.get("vendor_add")
    if vendor is None:
        vendor = ""

    description = request.POST.get("description_add")
    if description is None:
        description = ""

    person = request.POST.get("person_add")
    if person is None:
        person = ""

    tel = request.POST.get("tel_add")
    if tel is None:
        tel = ""

    if request.POST.get("price_add"):
        price = request.POST.get("price_add")
    else:
        price = 0

    e_mail = request.POST.get("e_mail_add")
    if e_mail is None:
        e_mail = ""

    remark = request.POST.get("remark_add")
    if remark is None:
        remark = ""

    if request.POST.get("start_date_add"):
        start_date = datetime.strptime(request.POST.get("start_date_add"), "%d/%m/%Y").date()
    else:
        start_date = ""

    if request.POST.get("end_date_add"):
        end_date = datetime.strptime(request.POST.get("end_date_add"), "%d/%m/%Y").date()
    else:
        end_date = ""

    username = request.user.username

    user_first_name = request.user.first_name

    dept_id, dept_en = getUserDepartmentInfo(username)
    cus_name_en = getCustomerName(post_number)

    if request.FILES:
        afile = request.FILES["it_contract_document_add"].name
        afile_data = request.FILES['it_contract_document_add'].read()
    else:
        afile = ""
        afile_data = None

    record = {}
    refresh_it_contract_list = []

    # Insert data
    sql = "insert into itcontractdb ("
    sql += "dept, description, vendor, person, tel, "
    sql += "price, e_mail, remark, start_date, end_date, "
    sql += "upd_date, upd_by, upd_flag, afile, afile_data, dept_id, "
    sql += "turn_off_notification, "
    sql += "contract_type, contract_number, cnt_id, cus_name_en, city_id) "
    sql += "values ("
    sql += "'" + str(dept_en) + "','" + str(description) + "','" + str(vendor) + "','" + str(person) + "','" + str(tel) + "', "
    sql += str(price) + ",'" + str(e_mail) + "','" + str(remark) + "','" + str(start_date) + "','" + str(end_date) + "', "
    sql += "'" + str(datetime.now()) + "','" + str(user_first_name) + "', 'A', '" + str(afile) + "', null, "

    if dept_id:
        sql += str(dept_id) + ", "
    else:
        sql += "null, "

    sql += "0, "

    if contract_type:
        if contract_type != "":
            sql += str(contract_type) + ", "
        else:
            sql += "null, "
    else:
        sql += "null, "

    if contract_number:
        if contract_number != "":
            sql += "'" + str(contract_number) + "', "
        else:
            sql += "null, "
    else:
        sql += "null, "

    if post_number:
        if post_number != "":
            sql += "'" + str(post_number) + "', "
        else:
            sql += "null, "
    else:
        sql += "null, "

    if cus_name_en:
        if cus_name_en != "":
            sql += "'" + str(cus_name_en) + "', "
        else:
            sql += "null, "
    else:
        sql += "null, "

    if city:
        if city != "":
            sql += "'" + str(city) + "' "
        else:
            sql += "null "
    else:
        sql += "null "

    sql += ");"

    print("sql insert : ", sql)

    try:
        cursor = connection.cursor()
        cursor.execute(sql)
        cursor.execute("SELECT @@IDENTITY AS ID;")
        it_contract_id = cursor.fetchone()[0]

        if request.FILES:
            itcontract = ITcontractDB.objects.filter(pk=it_contract_id).get()
            itcontract.afile_data = afile_data
            itcontract.save()

        is_error = False
        bg_color = "bg-success",
        message = "ทำรายการสำเร็จ"

    except db.OperationalError as e:
        is_error = True
        bg_color = "bg-danger",
        message = "<b>Error: please send this error to IT team</b><br>" + str(e)
    except db.Error as e:
        is_error = True
        bg_color = "bg-danger",
        message = "<b>Error: please send this error to IT team</b><br>" + str(e)
    except Exception as e:
        is_error = True
        bg_color = "bg-danger",
        message = "<b>Error: please send this error to IT team</b><br>" + str(e)
    finally:
        cursor.close()

    if not is_error:
        refresh_it_contract_list = get_refresh_it_contract_list(username)
        is_error = False
        message = "ทำรายการสำเร็จ"

    response = JsonResponse(data={
        "success": True,
        "is_error": is_error,
        "message": message,
        "refresh_it_contract_list": refresh_it_contract_list,
    })

    response.status_code = 200
    return response

@permission_required('ITcontract.change_itcontractdb', login_url='/accounts/login/')
def ajax_save_it_contract_item(request):

    print("SAVE")

    is_error = True
    message = ""

    username = request.user.username
    it_contract_id = request.POST.get("contract_id_edit")
    # dept = request.POST.get("dept_edit")
    vendor = request.POST.get("vendor_edit")
    description = request.POST.get("description_edit")
    person = request.POST.get("person_edit")
    tel = request.POST.get("tel_edit")
    price = request.POST.get("price_edit")
    e_mail = request.POST.get("e_mail_edit")
    remark = request.POST.get("remark_edit")
    start_date = datetime.strptime(request.POST.get("start_date_edit"), "%d/%m/%Y").date()
    end_date = datetime.strptime(request.POST.get("end_date_edit"), "%d/%m/%Y").date()

    turn_off_notification_edit = request.POST.get("turn_off_notification_edit")
    # print("turn_off_notification_edit : ", turn_off_notification_edit)

    contract_number = request.POST.get("contract_number_edit").strip()
    contract_type = request.POST.get("contract_type_option_edit")
    post_number = request.POST.get("post_option_edit")
    city = request.POST.get("city_option_edit")

    quantity = request.POST.get("quantity_edit")
    pr_number = request.POST.get("pr_edit")
    po_number = request.POST.get("po_edit")

    #print("%s | %s |%s" % (quantity, pr_number, po_number))
    #return False

    record = {}
    itcontractdb_object = None
    refresh_it_contract_list = []

    sql = "update itcontractdb set "
    sql += "vendor='" + str(vendor) + "', description='" + str(description) + "', person='" + str(person) + "', tel='" + str(tel) + "', e_mail='" + str(e_mail) + "', "
    sql += "price=" + str(price) + ", quantity=" + str(quantity) + ", remark='" + str(remark) + "', start_date='" + str(start_date) + "', end_date='" + str(end_date) + "', "
    sql += "upd_date='" + str(datetime.now()) + "', upd_by='" + str(request.user.first_name) + "', turn_off_notification=" + str(turn_off_notification_edit) + ", "
    sql += "contract_number='" + str(contract_number) + "', "

    if contract_type:
        sql += "contract_type=" + str(contract_type) + ", "

    if post_number:
        sql += "cnt_id=" + str(post_number) + ", "

    if city:
        sql += "city_id=" + str(city) + ", "

    sql += "pr_number='" + str(pr_number) + "', po_number='" + str(po_number) + "' "
    sql += "where id=" + str(it_contract_id) + ";"

    print("X : ", sql)

    try:
        cursor = connection.cursor()
        cursor.execute(sql)

        if request.FILES:
            itcontract = ITcontractDB.objects.filter(pk=it_contract_id).get()

            if itcontract:
                try:
                    itcontract.afile = request.FILES["it_contract_document_edit"].name
                    itcontract.afile_data = request.FILES['it_contract_document_edit'].read()
                    itcontract.save()
                    is_error = False
                    message = "อัพเดทข้อมูลสำเร็จ"
                except db.OperationalError as e:
                    is_error = True
                    message = str(e)
                except db.Error as e:
                    is_error = True
                    message = str(e)
                except Exception as e:
                    is_error = True
                    message = str(e)

        is_error = False
        refresh_it_contract_list = get_refresh_it_contract_list(username)
        message = "อัพเดทข้อมูลสำเร็จ"

    except db.OperationalError as e:
        is_error = True
        message = "<b>Error: please send this error to IT team</b><br>" + str(e)
    except db.Error as e:
        is_error = True
        message = "<b>Error: please send this error to IT team</b><br>" + str(e)
    except Exception as e:
        is_error = True
        message = "<b>Error: please send this error to IT team</b><br>" + str(e)
    finally:
        cursor.close()

    '''
    if it_contract_id is not None:
        itcontract = ITcontractDB.objects.filter(pk=it_contract_id).get()

        if itcontract is not None:

            # itcontract.dept = dept
            itcontract.vendor = vendor
            itcontract.description = description
            itcontract.person = person
            itcontract.tel = tel
            itcontract.price = price
            itcontract.e_mail = e_mail
            itcontract.remark = remark
            itcontract.start_date = start_date
            itcontract.end_date = end_date
            itcontract.upd_date = datetime.now()
            itcontract.upd_by = request.user.first_name
            itcontract.upd_flag = 'E'
            itcontract.turn_off_notification = turn_off_notification_edit
            itcontract.contract_number = contract_number
            itcontract.contract_type = contract_type
            itcontract.cnt_id = post_number
            itcontract.city_id = city

            if request.FILES:
                itcontract.afile = request.FILES["it_contract_document_edit"].name
                itcontract.afile_data = request.FILES['it_contract_document_edit'].read()
            else:
                print("do nothing")

            try:
                itcontract.save()
                is_error = False
                message = "ทำรายการสำเร็จ"
            except db.OperationalError as e:
                message = str(e)
            except db.Error as e:
                message = str(e)
            except Exception as e:
                message = str(e)

            if not is_error:
                refresh_it_contract_list = get_refresh_it_contract_list(username)
                is_error = False
                message = "ทำรายการสำเร็จ"
        else:
            message = "Error"
    else:
        message = "Error"

    '''

    response = JsonResponse(data={
        "success": True,
        "is_error": is_error,
        "message": message,
        "refresh_it_contract_list": refresh_it_contract_list,
    })

    response.status_code = 200
    return response

@permission_required('ITcontract.delete_itcontractdb', login_url='/accounts/login/')
def ajax_delete_it_contract_item(request):
    it_contract_id = request.POST.get("it_contract_id")

    username = request.user.username
    is_error = True
    message = "Erorr"
    record = {}
    refresh_it_contract_list = []

    if it_contract_id is not None:
        itcontract = ITcontractDB.objects.filter(pk=it_contract_id).get()
        if itcontract is not None:
            itcontract.upd_date = datetime.now()
            itcontract.upd_by = request.user.first_name
            itcontract.upd_flag = 'D'

            try:
                itcontract.save()
                is_error = False
                message = "ทำรายการสำเร็จ"
            except db.OperationalError as e:
                message = str(e)
            except db.Error as e:
                message = str(e)
            except Exception as e:
                message = str(e)

            if not is_error:
                refresh_it_contract_list = get_refresh_it_contract_list(username)
                is_error = False
                message = "ทำรายการสำเร็จ"
        else:
            message = "Error"
    else:
        message = "Error"

    response = JsonResponse(data={
        "success": True,
        "is_error": is_error,
        "message": message,
        "refresh_it_contract_list": refresh_it_contract_list,
    })

    response.status_code = 200
    return response

def getUserDepartmentInfo(username):
    record = {}
    refresh_it_contract_list = []
    it_contract_list = []

    # ***************************
    # Check User Department
    # ***************************
    dept_id, dept_en = getDepartmentInfo(username)

    sql = "select "
    sql += "con.id, con.dept, con.vendor, con.description, con.person, con.tel, con.e_mail, con.start_date, con.end_date, con.price, con.remark, con.upd_by, con.afile "
    sql += "from itcontractdb con "
    sql += "where con.dept_id=" + str(dept_id) + " and con.upd_flag!='D';"
    print("SQL xxxx : ", sql)

    try:
        with connection.cursor() as cursor:
            cursor.execute(sql)
            itcontractdb_object = cursor.fetchall()

            if itcontractdb_object:
                str_today_date = datetime.now().strftime("%Y-%m-%d")
                today_date = datetime.strptime(str_today_date, '%Y-%m-%d').date()

                for item in itcontractdb_object:
                    it_contract_id = item[0]
                    department = item[1]
                    vendor = item[2]
                    description = item[3]
                    contact = item[4]
                    phone = item[5]
                    email = item[6]
                    start_date = item[7]
                    end_date = item[8]
                    price = item[9]
                    remark = item[10]
                    upd_by = item[11]
                    afile = item[12]

                    if (end_date.date() >= today_date):
                        is_contract_expired = False
                    else:
                        is_contract_expired = True

                    remaining_day = end_date.date() - today_date

                    record = {
                        "id": it_contract_id,
                        "dept": department,
                        "vendor": vendor,
                        "description": description,
                        "contact": contact,
                        "phone": phone,
                        "email": email,
                        "start_date": start_date,
                        "end_date": end_date,
                        "price": price,
                        "remark": remark,
                        "upd_by": upd_by,
                        "afile": afile,
                        "is_contract_expired": is_contract_expired,
                        "remaining_day": remaining_day.days,
                    }

                    it_contract_list.append(record)

            is_error = False
            message = "No error"

    except db.OperationalError as e:
        is_error = True
        message = "Error message: " + str(e)
    except db.Error as e:
        is_error = True
        message = "Error message: " + str(e)
    finally:
        cursor.close()

    return dept_id, dept_en

def get_refresh_it_contract_list(username):
    record = {}
    refresh_it_contract_list = []
    it_contract_list = []

    # ***************************
    # Check User Department
    # ***************************
    dept_id, dept_en = getDepartmentInfo(username)

    sql = "select "
    sql += "con.id, con.dept, con.vendor, con.description, con.person, con.tel, con.e_mail, con.start_date, con.end_date, con.price, "
    sql += "con.remark, con.upd_by, con.afile, con.contract_number, ct.name_en as contract_name_en, con.cnt_id, vca.cus_name_en, vca.zone_en, "
    sql += "con.quantity, con.pr_number, con.po_number, datediff(day, con.end_date, getdate()) as date_diff "
    sql += "from itcontractdb con "
    sql += "left join itcontract_contract_type ct on con.contract_type=ct.id "
    sql += "left join v_contract_active vca on con.cnt_id=vca.cnt_id "
    sql += "where con.dept_id=" + str(dept_id) + " and upd_flag!='D' "
    sql += "order by date_diff desc;"
    # sql += "order by con.id;"
    print("SQLxx : ", sql)

    try:
        with connection.cursor() as cursor:
            cursor.execute(sql)
            itcontractdb_object = cursor.fetchall()

            if itcontractdb_object:
                str_today_date = datetime.now().strftime("%Y-%m-%d")
                today_date = datetime.strptime(str_today_date, '%Y-%m-%d').date()

                for item in itcontractdb_object:
                    it_contract_id = item[0]

                    department = item[1].replace("/Indirect Functional", "") if item[1] else ""

                    vendor = item[2]
                    description = item[3]
                    contact = item[4]
                    phone = item[5]
                    email = item[6]
                    start_date = item[7]
                    end_date = item[8]
                    price = item[9]
                    remark = item[10] if item[10] else ""
                    upd_by = item[11]
                    afile = item[12]

                    if item[13]:
                        if item[13].strip() != "":
                            contract_number = item[13].strip()
                        else:
                            contract_number = it_contract_id
                    else:
                        contract_number = item[0]

                    contract_number_display = contract_number

                    contract_type_name_en = item[14] if item[14] else "ไม่ระบุประเภท"

                    cnt_id = item[15] if item[15] else ""

                    if item[15]:
                        post_number = convertCntIdToPostNo(cnt_id)
                    else:
                        post_number = ""

                    # post_name = item[16][0:20]+"..." if item[16] else ""
                    post_name = item[16] if item[16] else ""

                    zone_name_en = item[17] if item[17] else ""
                    zone_name_en = zone_name_en.replace("ZONE ", "").replace("PHUKET", "P").replace("SAMUI", "S").replace("SONGKLA","").replace("KHON KAEN", "K")

                    if (end_date.date() >= today_date):
                        is_contract_expired = False
                    else:
                        is_contract_expired = True

                    remaining_day = end_date.date() - today_date

                    record = {
                        "id": it_contract_id,
                        "it_contract_id": it_contract_id,
                        "dept": department,
                        "vendor": vendor,
                        "description": description,
                        "contact": contact,
                        "phone": phone,
                        "e_mail": email,
                        "start_date": start_date.strftime("%d/%m/%Y"),
                        "end_date": end_date.strftime("%d/%m/%Y"),
                        "price": price,
                        "remark": remark,
                        "upd_by": upd_by,
                        "afile": afile,
                        "is_contract_expired": is_contract_expired,
                        "remaining_day": remaining_day.days,
                        "tel": phone,
                        "person": contact,
                        "contract_number_display": contract_number_display,
                        "contract_type_name_en": contract_type_name_en,
                        "post_number": post_number,
                        "post_name": post_name,
                        "zone_name_en": zone_name_en,
                    }

                    it_contract_list.append(record)

            is_error = False
            message = "No error"

    except db.OperationalError as e:
        is_error = True
        message = "Error message: " + str(e)
    except db.Error as e:
        is_error = True
        message = "Error message: " + str(e)
    finally:
        cursor.close()

    print("error : ", message)

    return it_contract_list

@permission_required('ITcontract.view_itcontractdb', login_url='/accounts/login/')
def view_contract_document(request, it_contract_id):
    result = {}
    total_day = 0
    total_hour = 0
    document_obj = ITcontractDB.objects.filter(id__exact=it_contract_id).get()
    write_document_data = open('media/' + str(document_obj.afile), 'wb').write(document_obj.afile_data)
    document_data = open('media/' + str(document_obj.afile), 'rb')
    response = FileResponse(document_data)
    return response

@permission_required('ITcontract.view_itcontractdb', login_url='/accounts/login/')
def ajax_print_it_contract_report(request):

    base_url = MEDIA_ROOT + '/itcontract/template/'
    template_name = base_url + 'it_contract_list.docx'
    file_name = "IT_Contract_List"

    it_contract_obj = ITcontractDB.objects.exclude(upd_flag='D').all().values_list('id','dept','vendor','description','person','tel','e_mail','start_date','end_date','price','remark','upd_by')
    print_datetime = datetime.now().strftime("%d/%m/%Y %H:%M")

    it_contract_list = []
    record = {}

    if it_contract_obj is not None:
        for item in it_contract_obj:
            it_contract_id = item[0]
            department = item[1]
            vendor = item[2]
            description = item[3]
            contact = item[4]
            phone = item[5]
            email = item[6]
            start_date = item[7].strftime("%d/%m/%Y")
            end_date = item[8].strftime("%d/%m/%Y")
            price = item[9]
            remark = item[10]
            upd_by = item[11]

            record = {
                "it_contract_id": it_contract_id,
                "vendor": vendor,
                "description": description,
                "contact": contact,
                "phone": phone,
                "email": email,
                "start_date": start_date,
                "end_date": end_date,
                "price": price,
                "remark": remark,
            }

            it_contract_list.append(record)

    context = {'it_contract_list': list(it_contract_list), 'print_datetime': print_datetime}

    tpl = DocxTemplate(template_name)
    tpl.render(context)
    tpl.save(MEDIA_ROOT + '/itcontract/download/' + file_name + ".docx")

    docx_file = path.abspath("media\\itcontract\\download\\" + file_name + ".docx")
    pdf_file = path.abspath("media\\itcontract\\download\\" + file_name + ".pdf")
    convert(docx_file, pdf_file)

    return FileResponse(open(pdf_file, 'rb'), content_type='application/pdf')

@permission_required('ITcontract.view_itcontractdb', login_url='/accounts/login/')
def export_it_contract_to_excel(request):
    response = HttpResponse(content_type='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename="IT_Contract_List.xls"'

    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet('IT_Contract_List')

    font_style = xlwt.XFStyle()
    font_style.font.bold = True
    font_style = xlwt.easyxf('font: bold 1,height 280;')
    ws.write(0, 5, "IT Contract List", font_style)

    font_style = xlwt.easyxf('font: height 180;')
    ws.col(1).width = int(13*260)
    ws.col(2).width = int(13*260)
    ws.col(3).width = int(13*260)
    ws.col(4).width = int(13*260)
    ws.col(5).width = int(13*260)
    ws.col(6).width = int(13*260)
    ws.col(7).width = int(13*260)
    ws.col(8).width = int(13*260)
    ws.col(9).width = int(20*260)

    columns = ['ID', 'Vendor', 'Description', 'Contact', 'Phone', 'Email', 'Start Date', 'End Date', 'Price', 'Remark']
    for col_num in range(len(columns)):
        ws.write(2, col_num, columns[col_num], font_style)

    font_style = xlwt.XFStyle()
    font_style = xlwt.easyxf('font: height 180;')

    row_num = 3
    counter = 1

    it_contract_obj = ITcontractDB.objects.exclude(upd_flag='D').all().values_list('id','dept','vendor','description','person','tel','e_mail','start_date','end_date','price','remark','upd_by')

    if it_contract_obj is not None:
        for row in it_contract_obj:
            it_contract_id = item[0]
            department = item[1]
            vendor = item[2]
            description = item[3]
            contact = item[4]
            phone = item[5]
            email = item[6]
            start_date = item[7].strftime("%d/%m/%Y")
            end_date = item[8].strftime("%d/%m/%Y")
            price = item[9]
            remark = item[10]
            upd_by = item[11]

            for col_num in range(len(columns)):
                if(col_num==0):
                    ws.write(row_num, 0, it_contract_id, font_style)
                elif(col_num==1):
                    ws.write(row_num, 1, vendor, font_style)
                elif(col_num==2):
                    ws.write(row_num, 2, description, font_style)
                elif(col_num==3):
                    ws.write(row_num, 3, contact, font_style)
                elif(col_num==4):
                    ws.write(row_num, 4, phone, font_style)
                elif(col_num==5):
                    ws.write(row_num, 5, email, font_style)
                elif(col_num==6):
                    ws.write(row_num, 6, start_date, font_style)
                elif(col_num==7):
                    ws.write(row_num, 7, end_date, font_style)
                elif(col_num==8):
                    ws.write(row_num, 8, price, font_style)
                else:
                    ws.write(row_num, 9, remark, font_style)

            row_num += 1
            counter += 1

    wb.save(response)
    return response

@permission_required('ITcontract.view_itcontractdb', login_url='/accounts/login/')
def ITcontractAlertSetting(request):
    if isStillUseDefaultPassword(request):
        template_name = 'page/force_change_password.html'
        return render(request, template_name, {})
    else:
        if isPasswordExpired(request):
            if isPasswordChanged(request):
                template_name = 'page/force_change_password.html'
                return render(request, template_name, {})

    username = request.user.username
    user_language = getDefaultLanguage(request.user.username)
    translation.activate(user_language)
    page_title = settings.PROJECT_NAME
    db_server = settings.DATABASES['default']['HOST']
    project_name = settings.PROJECT_NAME
    project_version = settings.PROJECT_VERSION
    today_date = getDateFormatDisplay(user_language)

    email_alert_object = None
    email_alert_list = []
    record = {}

    send_to_email = ""
    send_to_group_email = ""

    if user_language == "th":
        if request.user.username == "999999":
            username_display = request.user.first_name
        else:
            username_display = LeaveEmployee.objects.filter(emp_id=request.user.username).values_list('emp_fname_th', flat=True).get()
    else:
        if request.user.username == "999999":
            username_display = request.user.first_name
        else:
            username_display = LeaveEmployee.objects.filter(emp_id=request.user.username).values_list('emp_fname_en', flat=True).get()

    # ***************************
    # Check User Department
    # ***************************
    if request.user.username == "999999":
        # print("do nothing")
        sql = "select "
        sql += "u.emp_id, u.dept_id, d.dept_en "
        sql += "from itcontract_user u "
        sql += "left join com_department d on u.dept_id=d.dept_id "
        sql += "where u.emp_id=" + str(username) + ";"
        print("SQL : ", sql)
        try:
            with connection.cursor() as cursor:
                cursor.execute(sql)
                user_object = cursor.fetchone()

                if user_object:
                    dept_id = user_object[1]
                    dept_en = user_object[2]

                is_error = False
                message = "No error"

        except db.OperationalError as e:
            is_error = True
            message = "Error message: " + str(e)
        except db.Error as e:
            is_error = True
            message = "Error message: " + str(e)
        finally:
            cursor.close()
    else:
        sql = "select "
        sql += "u.emp_id, u.dept_id, d.dept_en "
        sql += "from itcontract_user u "
        sql += "left join com_department d on u.dept_id=d.dept_id "
        sql += "where u.emp_id=" + str(username) + ";"
        print("SQL : ", sql)
        try:
            with connection.cursor() as cursor:
                cursor.execute(sql)
                user_object = cursor.fetchone()

                if user_object:
                    dept_id = user_object[1]
                    dept_en = user_object[2]

                is_error = False
                message = "No error"

        except db.OperationalError as e:
            is_error = True
            message = "Error message: " + str(e)
        except db.Error as e:
            is_error = True
            message = "Error message: " + str(e)
        finally:
            cursor.close()

    # print("%s | %s" % (dept_id, dept_en))

    # itcontract_email_alert_list = ITContractEmailAlert.objects.filter(app_name='ITcontract').get()

    sql = "select alert_id, send_to_email, send_to_group_email, reach_minimum_day, alert_active from itcontract_email_alert where dept_id=" + str(dept_id) + ";"
    print("SQL : ", sql)
    try:
        with connection.cursor() as cursor:
            cursor.execute(sql)
            email_alert_object = cursor.fetchone()

            if email_alert_object:
                alert_id = email_alert_object[0]
                send_to_email = email_alert_object[1]
                send_to_group_email = email_alert_object[2]
                reach_minimum_day = email_alert_object[3]
                alert_active = email_alert_object[4]

            is_error = False
            message = "No error"

    except db.OperationalError as e:
        is_error = True
        message = "Error message: " + str(e)
    except db.Error as e:
        is_error = True
        message = "Error message: " + str(e)
    finally:
        cursor.close()

    # get last login
    last_login = getLastLogin(request)

    # *********************
    # Get Customer List
    # *********************
    customer_obj = None
    customer_list = []
    record = {}

    sql = "select cnt_id, cus_name_en, zone_en from complaint_contract order by cnt_id;"
    try:
        with connection.cursor() as cursor:
            cursor.execute(sql)
            customer_obj = cursor.fetchall()

        if customer_obj is not None:
            for item in customer_obj:
                cnt_id = item[0]
                cus_name_en = item[1].strip() if item[1] else ""

                zone_en = item[2].strip() if item[2] else ""
                zone_en = zone_en.replace("ZONE ", "")

                record = {"cnt_id":cnt_id, "cus_name_en": cus_name_en, "zone_en": zone_en}
                customer_list.append(record)
            is_error = False
            message = "No error"

    except db.OperationalError as e:
        is_error = True
        message = "Error message: " + str(e)
    except db.Error as e:
        is_error = True
        message = "Error message: " + str(e)
    finally:
        cursor.close()

    return render(request,
        'ITcontract/it_contract_alert_setting.html', {
        'page_title': settings.PROJECT_NAME,
        'today_date': today_date,
        'project_version': settings.PROJECT_VERSION,
        'db_server': settings.DATABASES['default']['HOST'],
        'project_name': settings.PROJECT_NAME,
        'user_language': user_language,
        'username_display': username_display,
        'today_date': today_date,
        # 'schedule_alert_setting_list': itcontract_email_alert_list,
        'alert_id': alert_id,
        'send_to_email': send_to_email,
        'send_to_group_email': send_to_group_email,
        'last_login': last_login,
        'reach_minimum_day': reach_minimum_day,
        'alert_active': alert_active,
        'customer_list': list(customer_list),
    })

@permission_required('ITcontract.view_itcontractdb', login_url='/accounts/login/')
def AjaxUpdateEmailAlertSetting(request):
    is_error = True
    message = "Error #0 - Please contact IT."

    alert_id = request.POST.get("alert_id")
    send_to_email = request.POST.get("send_to_email")
    send_to_group_email = request.POST.get("send_to_group_email")
    reach_minimum_day = request.POST.get("reach_minimum_day")
    alert_active = request.POST.get("alert_active")

    print(alert_id,send_to_email, send_to_group_email, reach_minimum_day, alert_active)

    itcontract_email_alert_list = ITContractEmailAlert.objects.filter(alert_id=alert_id).get()
    if itcontract_email_alert_list is not None:
        itcontract_email_alert_list.send_to_email = send_to_email
        itcontract_email_alert_list.send_to_group_email = send_to_group_email
        itcontract_email_alert_list.reach_minimum_day = reach_minimum_day
        itcontract_email_alert_list.alert_active = alert_active

        itcontract_email_alert_list.modified_date = datetime.now()
        itcontract_email_alert_list.modified_by = request.user.first_name
        itcontract_email_alert_list.modified_flag = 'E'

        itcontract_email_alert_list.save()

        is_error = False
        message = "บันทึกรายการสำเร็จ"
    else:
        is_error = True
        message = "ไม่พบข้อมูลในระบบ"

    response = JsonResponse(data={
        "success": True,
        "is_error": is_error,
        "message": message,
    })

    response.status_code = 200
    return response

@permission_required('ITcontract.view_itcontractdb', login_url='/accounts/login/')
def AjaxSearchSpAdminContract(request):

    print("**************************")
    print("AjaxSearchSpAdminContract()")
    print("**************************")

    cnt_id = request.POST.get('post_number')
    contract_type_id = request.POST.get('contract_type_option')

    # print("%s | %s" % (cnt_id, contract_type_id))

    is_error = False
    message = ""
    username = request.user.username

    str_today_date = datetime.now().strftime("%Y-%m-%d")
    today_date = datetime.strptime(str_today_date, '%Y-%m-%d').date()

    contract_object = None
    contract_list = []
    record = {}

    # ***************************
    # Check Contract List
    # ***************************
    dept_id, dept_en = getDepartmentInfo(username)

    sql = "select "
    sql += "con.id contract_id, con.dept, con.vendor, con.description, con.person, con.tel, con.e_mail, con.start_date, con.end_date, con.price, "
    sql += "con.remark, con.upd_by, con.afile, con.contract_number, ct.name_en as contract_name_en, con.cnt_id, vca.cus_name_en, vca.zone_en, "
    sql += "con.quantity, con.pr_number, con.po_number "
    sql += "from itcontractdb con "
    sql += "left join itcontract_contract_type ct on con.contract_type=ct.id "
    sql += "left join v_contract_active vca on con.cnt_id=vca.cnt_id "
    sql += "where con.dept_id=" + str(dept_id) + " and upd_flag!='D' "

    if cnt_id:
        if cnt_id != "":
            sql += "and con.cnt_id=" + str(cnt_id).strip() + " "

    if contract_type_id:
        if contract_type_id != "0":
            sql += "and con.contract_type=" + str(contract_type_id).strip() + " "

    sql += "order by con.id;"
    # print("SQLxx : ", sql)

    try:
        with connection.cursor() as cursor:
            cursor.execute(sql)
            contract_object = cursor.fetchall()

            if contract_object:

                for item in contract_object:
                    it_contract_id = item[0]

                    if item[13]:
                        if item[13].strip() != "":
                            contract_number_display = item[13]
                        else:
                            contract_number_display = it_contract_id
                    else:
                        contract_number_display = it_contract_id

                    department = item[1].replace("/Indirect Functional", "").replace("/Bangkok/Indirect Field", "") if item[1] else ""

                    vendor = item[2] if item[2] else ""
                    description = item[3] if item[3] else ""
                    contact = item[4]
                    phone = item[5]
                    email = item[6]
                    start_date = item[7]
                    end_date = item[8]
                    price = item[9]
                    remark = item[10] if item[10] else ""
                    upd_by = item[11]
                    contract_type_name_en = item[14] if item[14] else "ไม่ระบุประเภท"

                    cnt_id = item[15] if item[15] else ""
                    if item[15]:
                        post_number = convertCntIdToPostNo(cnt_id)
                    else:
                        post_number = ""

                    # post_name = item[16][0:30]+"..." if item[16] else ""
                    post_name = item[16].strip() if item[16] else ""

                    zone_name_en = item[17] if item[17] else ""
                    zone_name_en = zone_name_en.replace("ZONE ", "").replace("PHUKET", "P").replace("SAMUI", "S").replace("SONGKLA","").replace("KHON KAEN", "K")

                    quantity = item[18] if item[18] else 0
                    pr_number = item[19] if item[19] else ""
                    po_number = item[20] if item[20] else ""

                    if (end_date.date() >= today_date):
                        is_contract_expired = False
                    else:
                        is_contract_expired = True

                    remaining_day = end_date.date() - today_date

                    # contract_number_display = item[12].strip if item[12] else it_contract_id

                    record = {
                        "id": item[0],
                        "contract_number_display": contract_number_display,
                        "dept": department,
                        "vendor": vendor,
                        "description": description,
                        "contact": contact,
                        "phone": phone,
                        "email": email,
                        "start_date": start_date,
                        "end_date": end_date,
                        "price": price,
                        "remark": remark,
                        "upd_by": upd_by,
                        "is_contract_expired": is_contract_expired,
                        "remaining_day": remaining_day.days,
                        "contract_type_name_en": contract_type_name_en,
                        "post_number": post_number,
                        "post_name": post_name,
                        "zone_name_en": zone_name_en,
                        "quantity": quantity,
                        "pr_number": pr_number,
                        "po_number": po_number,
                    }

                    contract_list.append(record)

            is_error = False
            message = "No error"

    except db.OperationalError as e:
        is_error = True
        message = "Error message: " + str(e)
    except db.Error as e:
        is_error = True
        message = "Error message: " + str(e)
    finally:
        cursor.close()

    response = JsonResponse(data={
        "success": True,
        "is_error": is_error,
        "message": message,
        "contract_list": list(contract_list),
    })

    response.status_code = 200
    return response

def getDepartmentInfo(username):

    if username == "999999":
        # print("do nothing")
        sql = "select "
        sql += "u.emp_id, u.dept_id, d.dept_en "
        sql += "from itcontract_user u "
        sql += "left join com_department d on u.dept_id=d.dept_id "
        sql += "where u.emp_id=" + str(username) + ";"
        print("SQL : ", sql)
        try:
            with connection.cursor() as cursor:
                cursor.execute(sql)
                user_object = cursor.fetchone()

                if user_object:
                    dept_id = user_object[1]
                    # dept_en = user_object[2].replace("/Indirect Functional", "")
                    dept_en = user_object[2].replace("/Indirect Functional", "").replace("/Bangkok/Indirect Field", "").strip()

                is_error = False
                message = "No error"

        except db.OperationalError as e:
            is_error = True
            message = "Error message: " + str(e)
        except db.Error as e:
            is_error = True
            message = "Error message: " + str(e)
        finally:
            cursor.close()
    else:
        sql = "select "
        sql += "u.emp_id, u.dept_id, d.dept_en "
        sql += "from itcontract_user u "
        sql += "left join com_department d on u.dept_id=d.dept_id "
        sql += "where u.emp_id=" + str(username) + ";"
        print("SQL zz : ", sql)
        try:
            with connection.cursor() as cursor:
                cursor.execute(sql)
                user_object = cursor.fetchone()

                if user_object:
                    dept_id = user_object[1]
                    dept_en = user_object[2].replace("/Indirect Functional", "").replace("/Bangkok/Indirect Field", "").strip().strip()

                is_error = False
                message = "No error"

        except db.OperationalError as e:
            is_error = True
            message = "Error message: " + str(e)
        except db.Error as e:
            is_error = True
            message = "Error message: " + str(e)
        finally:
            cursor.close()

    print("%s | %s" % (dept_id, dept_en))

    return dept_id, dept_en

def getCustomerName(post_number):
    cus_name_en = ""
    customer_object = None

    sql = "select cus_name_en from complaint_contract where cnt_id=" + str(post_number) + ";"
    try:
        with connection.cursor() as cursor:
            cursor.execute(sql)
            customer_object = cursor.fetchone()

            if customer_object:
                cus_name_en = customer_object[0].strip()

            is_error = False
            message = "No error"

    except db.OperationalError as e:
        is_error = True
        message = "Error message: " + str(e)
    except db.Error as e:
        is_error = True
        message = "Error message: " + str(e)
    finally:
        cursor.close()

    return cus_name_en

def ajax_get_city(request):
    print("*************************")
    print("ajax_get_city()")
    print("*************************")

    is_error = True
    message = ""

    username = request.user.username
    post_number = request.GET.get('post_number')

    print("username : ", username)
    print("post_number : ", post_number)

    customer_obj = None
    is_error = True
    message = ""

    city_id = ""
    city_th = ""
    city_en = ""
    cus_add1_th = ""

    if post_number != "0":
        # sql = "select city_th from tcl_contract_qty where cnt_id='" + str(post_number) + "';"
        sql = "select ci.city_id, cus.city_th, ci.city_en, cus.cus_add1_th "
        sql += "from tcl_contract_qty cus "
        sql += "left join t_city ci on cus.city_th=ci.city_th "
        sql += "where cus.cnt_id='" + str(post_number) + "'";

        print("ZZ : ", sql)
        try:
            with connection.cursor() as cursor:
                cursor.execute(sql)
                customer_obj = cursor.fetchone()

            if customer_obj:
                city_id = customer_obj[0]
                city_th = customer_obj[1].strip() if customer_obj[1] else ""
                city_en = customer_obj[2].strip() if customer_obj[2] else ""
                cus_add1_th = customer_obj[3].strip() if customer_obj[3] else ""

                is_error = False
                message = "No error"

        except db.OperationalError as e:
            is_error = True
            message = "Error message: " + str(e)
        except db.Error as e:
            is_error = True
            message = "Error message: " + str(e)
        finally:
            cursor.close()
    else:
        is_error = True
        message = "Post number is not correct"

    response = JsonResponse(data={
        "success": True,
        "is_error": is_error,
        "message": message,
        "city_id": city_id,
        "city_th": city_th,
        "city_en": city_en,
        "cus_add1_th": cus_add1_th,
    })
    response.status_code = 200
    return response

def convertCntIdToPostNo(cnt_id):
    cus_id = str(cnt_id)[0:4]
    cus_brn = str(cnt_id)[4:7]

    if int(cus_brn) > 0:
        cus_brn = "-" + str(int(cus_brn))
    else:
        cus_brn = ""

    post_number = cus_id + cus_brn

    return post_number

@permission_required('ITcontract.view_itcontractdb', login_url='/accounts/login/')
def exportSpContractToExcel(request, *args, **kwargs):
    response = HttpResponse(content_type='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename="Contract_List.xls"'

    try:
        cnt_id = kwargs['cnt_id']
    except:
        cnt_id = None

    try:
        contract_type_id = kwargs['contract_type']
    except:
        contract_type_id = None

    # print("%s | %s" % (cnt_id, contract_type_id))

    is_error = False
    message = ""
    username = request.user.username

    str_today_date = datetime.now().strftime("%Y-%m-%d")
    today_date = datetime.strptime(str_today_date, '%Y-%m-%d').date()

    contract_object = None
    contract_list = []
    record = {}
    count = 1

    # ***************************
    # Check Contract List
    # ***************************
    dept_id, dept_en = getDepartmentInfo(username)

    sql = "select "
    sql += "con.id contract_id, con.dept, con.vendor, con.description, con.person, con.tel, con.e_mail, con.start_date, con.end_date, con.price, "
    sql += "con.remark, con.upd_by, con.afile, con.contract_number, ct.name_en as contract_name_en, con.cnt_id, vca.cus_name_en, vca.zone_en, "
    sql += "con.quantity, con.pr_number, con.po_number "
    sql += "from itcontractdb con "
    sql += "left join itcontract_contract_type ct on con.contract_type=ct.id "
    sql += "left join v_contract_active vca on con.cnt_id=vca.cnt_id "
    sql += "where con.dept_id=" + str(dept_id) + " and upd_flag!='D' "

    if cnt_id:
        if cnt_id != "":
            sql += "and con.cnt_id=" + str(cnt_id).strip() + " "

    if contract_type_id:
        if contract_type_id != "0":
            sql += "and con.contract_type=" + str(contract_type_id).strip() + " "

    sql += "order by con.id;"
    print("SQLxx : ", sql)

    try:
        with connection.cursor() as cursor:
            cursor.execute(sql)
            contract_object = cursor.fetchall()

            if contract_object:

                for item in contract_object:
                    it_contract_id = item[0]

                    if item[13]:
                        if item[13].strip() != "":
                            contract_number_display = item[13]
                        else:
                            contract_number_display = it_contract_id
                    else:
                        contract_number_display = it_contract_id

                    department = item[1].replace("/Indirect Functional", "").replace("/Bangkok/Indirect Field", "") if item[1] else ""

                    vendor = item[2] if item[2] else ""
                    description = item[3] if item[3] else ""
                    contact = item[4]
                    phone = item[5]
                    email = item[6]

                    start_date = item[7]
                    end_date = item[8]

                    start_date_display = item[7]
                    end_date_display = item[8]

                    price = item[9]
                    remark = item[10] if item[10] else ""
                    upd_by = item[11]
                    contract_type_name_en = item[14] if item[14] else "ไม่ระบุประเภท"

                    cnt_id = item[15] if item[15] else ""
                    if item[15]:
                        post_number = convertCntIdToPostNo(cnt_id)
                    else:
                        post_number = ""

                    # post_name = item[16][0:30]+"..." if item[16] else ""
                    post_name = item[16].strip() if item[16] else ""

                    zone_name_en = item[17] if item[17] else ""
                    zone_name_en = zone_name_en.replace("ZONE ", "").replace("PHUKET", "P").replace("SAMUI", "S").replace("SONGKLA","").replace("KHON KAEN", "K")

                    quantity = item[18] if item[18] else 0
                    pr_number = item[19] if item[19] else ""
                    po_number = item[20] if item[20] else ""

                    if (end_date.date() >= today_date):
                        is_contract_expired = False
                    else:
                        is_contract_expired = True

                    remaining_day = end_date.date() - today_date

                    total_price = quantity * price

                    start_date_1 = item[7].strftime("%Y-%m-%d") if item[7] else None
                    end_date_1 = item[8].strftime("%Y-%m-%d") if item[7] else None
                    start_date_1 = datetime.strptime(start_date_1, "%Y-%m-%d")
                    end_date_1 = datetime.strptime(end_date_1, "%Y-%m-%d")

                    total_month = (end_date_1.year - start_date_1.year) * 12 + (end_date_1.month - start_date_1.month)
                    print("total_month : ", total_month)
                    # total_month = abs((end_date_1 - start_date_1).month)

                    record = {
                        "count_item": count,
                        "id": item[0],
                        "cnt_id": cnt_id,
                        "contract_number_display": contract_number_display,
                        "dept": department,
                        "vendor": vendor,
                        "description": description,
                        "contact": contact,
                        "phone": phone,
                        "email": email,
                        "start_date_display": start_date_display,
                        "end_date_display": end_date_display,
                        "price": price,
                        "remark": remark,
                        "upd_by": upd_by,
                        "is_contract_expired": is_contract_expired,
                        "remaining_day": remaining_day.days,
                        "contract_type_name_en": contract_type_name_en,
                        "post_number": post_number,
                        "post_name": post_name,
                        "zone_name_en": zone_name_en,
                        "quantity": quantity,
                        "pr_number": pr_number,
                        "po_number": po_number,
                        "total_price": total_price,
                        "total_month": total_month,
                    }

                    contract_list.append(record)
                    count += 1

            is_error = False
            message = "No error"

    except db.OperationalError as e:
        is_error = True
        message = "Error message: " + str(e)
    except db.Error as e:
        is_error = True
        message = "Error message: " + str(e)
    finally:
        cursor.close()

    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet('Contract_List')

    font_style = xlwt.XFStyle()
    #font_style.font.bold = True
    #font_style = xlwt.easyxf('font: bold 1,height 280;')
    #ws.write(0, 5, "Contract List", font_style)

    font_style = xlwt.easyxf('font: height 210;')
    font_style.font.bold = True
    ws.col(0).width = int(8*260)
    ws.col(1).width = int(8*260)
    ws.col(2).width = int(15*260)
    ws.col(3).width = int(30*260)   # ชื่อหน่วยงาน
    ws.col(4).width = int(25*260)   # รายการ
    ws.col(5).width = int(8*260)    # จำนวน
    ws.col(6).width = int(18*260)
    ws.col(7).width = int(15*260)
    ws.col(8).width = int(10*260)
    ws.col(9).width = int(10*260)
    ws.col(10).width = int(10*260)
    ws.col(11).width = int(12*260)
    ws.col(12).width = int(12*260)
    ws.col(13).width = int(30*260)

    columns = ['ลำดับ', 'โซน', 'โพสหน่วยงาน', 'ชื่อหน่วยงาน', 'รายการ', 'จำนวน', 'ระยะเวลาเช่า/เดือน', 'ราคาเช่า/เดือน', 'ราคารวม', 'PR', 'PO', 'วันที่เริ่มเช่า', 'วันที่สิ้นสุด', 'หมายเหตุ']
    for col_num in range(len(columns)):
        ws.write(0, col_num, columns[col_num], font_style)

    font_style = xlwt.XFStyle()
    font_style = xlwt.easyxf('font: height 180;')

    row_num = 1
    counter = 1

    if contract_list:
        for row in contract_list:
            count_item = row['count_item']
            zone_name_en = row['zone_name_en']
            post_number = row['post_number']
            post_name = row['post_name']
            contract_type_name_en = row['contract_type_name_en']
            start_date_display = row['start_date_display'].strftime("%d/%m/%Y")
            end_date_display = row['end_date_display'].strftime("%d/%m/%Y")
            price = row['price']
            quantity = row['quantity']
            remark = row['remark'].strip()
            pr_number = row['pr_number'].strip()
            po_number = row['po_number'].strip()
            total_price = row['total_price']
            total_month = row['total_month']

            for col_num in range(len(columns)):
                if(col_num==0):
                    ws.write(row_num, 0, count_item, font_style)
                elif(col_num==1):
                    ws.write(row_num, 1, zone_name_en, font_style)
                elif(col_num==2):
                    ws.write(row_num, 2, post_number, font_style)
                elif(col_num==3):
                    ws.write(row_num, 3, post_name, font_style)
                elif(col_num==4):
                    ws.write(row_num, 4, contract_type_name_en, font_style)
                elif(col_num==5):
                    ws.write(row_num, 5, quantity, font_style)
                elif(col_num==6):
                    ws.write(row_num, 6, total_month, font_style)
                elif(col_num==7):
                    ws.write(row_num, 7, price, font_style)
                elif(col_num==8):
                    ws.write(row_num, 8, total_price, font_style)
                elif(col_num==9):
                    ws.write(row_num, 9, pr_number, font_style)
                elif(col_num==10):
                    ws.write(row_num, 10, po_number, font_style)
                elif(col_num==11):
                    ws.write(row_num, 11, start_date_display, font_style)
                elif(col_num==12):
                    ws.write(row_num, 12, end_date_display, font_style)
                elif(col_num==13):
                    ws.write(row_num, 13, remark, font_style)

            row_num += 1
            counter += 1

    wb.save(response)
    return response

'''
class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer
    permission_classes = [permissions.IsAuthenticated]

class GroupViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer
    permission_classes = [permissions.IsAuthenticated]
'''

class ITContractViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """

    queryset = ITcontractDB.objects.all()
    serializer_class = ITContractSerializer
    permission_classes = [permissions.IsAuthenticated]


from __future__ import print_function

import cv2
import numpy as np
import math
import queue

class Stop():
    def __init__(self):
        self.sum_cx1 = self.sum_cy1 = self.sum_cx2 = self.sum_cy2 = 0
        self.filtercnt = 100
        self.MAF = queue.Queue()

    def angle(self, dx, dy):
        return math.atan2(dy, dx) * 180 / math.pi

    def push(self, x1, y1, x2, y2):
        self.MAF.put((x1, y1, x2, y2))
        self.sum_cx1 += x1
        self.sum_cy1 += y1
        self.sum_cx2 += x2
        self.sum_cx2 += y2

    def pop(self):
        (x1, y1, x2, y2) = self.MAF.get()
        self.sum_cx1 -= x1
        self.sum_cy1 -= y1
        self.sum_cx2 -= x2
        self.sum_cx2 -= y2

    def GetStopLine(self, img):
        img2 = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)

        edge = cv2.Canny(img, 200, 350)
        row, col, ch = img2.shape

        lines = cv2.HoughLinesP(edge, 1, math.pi / 180.0, 50, np.array([]), 50, 80)
        cx1 = cy1 = cx2 = cy2 = 0

        if lines is not None:
            a, b, c = lines.shape
            (d, e) = (row / 2, col / 2)
            (f, g) = (-1, -1)

            cnt = 0
            for i in range(a):
                (x1, y1, x2, y2) = (lines[i][0][0], lines[i][0][1], lines[i][0][2], lines[i][0][3])
                # Average Stop Line cordinate in this frame
                if x1 < col / 2 and x2 > col / 2 and abs(self.angle(x2 - x1, y2 - y1)) < 5:
                    cx1 += x1
                    cx2 += x2
                    cy1 += y1
                    cy2 += y2
                    cnt += 1

            if cnt is not 0:
                (cx1, cy1, cx2, cy2) = (int(cx1 / cnt), int(cy1 / cnt), int(cx2 / cnt), int(cy2 / cnt))

        cv2.line(img, (int(cx1), int(cy1)), (int(cx2), int(cy2)), (0, 0, 255), 3, cv2.LINE_AA)

        cv2.imshow('Detected Line', img)
        if cx1 is not 0 and cy1 is not 0 and cx2 is not 0 and cy2 is not 0:
            if cy1 > 20 or cy2 > 20:
                return True
        else:
            return False