import json

from django.views.decorators.http import require_http_methods
from django.utils.timezone import make_aware

from DCbackend.utils import MyEncoder
from DCbackend.utils.common import getHttpPost, success, formatDateTime
from backend.Service.CustomerService import CustomerService
from backend.Service.ProjectService import ProjectService
from backend.models import Customer


@require_http_methods(['POST'])
def Search(reqeust):
    return CustomerService.Search(reqeust)


@require_http_methods(['POST'])
def sync(reqeust):
    saveData()
    return success(True)


def saveData():
    data = getHttpPost()
    for item in data:
        customer = Customer.objects.filter(code=item['objectId']).first()
        if not customer:  # 如果存在，则直接更新
            customer = Customer()
        customer.code = item['objectId']
        customer.name = item['Name']
        customer.mobile = item['mobile']
        customer.en_name=item['enName']
        customer.contact = item['contact']
        customer.address = item['address']
        customer.other = item['creator']
        customer.create_time = formatDateTime(item['CreatedTime'])
        customer.status = 5
        customer.save()
    return True
