# coding=utf-8

import traceback
import json

from django.views.decorators.csrf import csrf_exempt
from django.db import transaction,IntegrityError
from django.db.models import ProtectedError
from django.db import transaction
from django.db.models import Q

from apps.exceptions import ExportChange, CustomError

from apps.foundation.models import BizLog
from libs.http import JSONResponse, JSONError, DataGridJSONResponse
from libs import utils
from apps.account.decorators import permission_required, token_required
from models import Customer
from serializers import CustomerSerializer
from filters import CustomerFilter
from resources import CustomerResource, CustomerImporter


@csrf_exempt
@permission_required('customer.view_customer')
def customer_list(request):
    f = CustomerFilter(request.GET, queryset=Customer.objects.all())
    rows, total = utils.get_page_data(request, f.qs)
    serializer = CustomerSerializer(rows, many=True)
    return DataGridJSONResponse(serializer.data, total)


@csrf_exempt
@permission_required('customer.export_customer')
def customer_export(request):
    f = CustomerFilter(request.GET, queryset=Customer.objects.all())
    serializer = CustomerSerializer(f.qs, many=True)
    export_data = ExportChange.dict_to_obj(serializer)
    export_data = CustomerResource().export(export_data)
    filename = utils.attachment_save(export_data)
    BizLog.objects.addnew(request.user, BizLog.EXPORT, u"导出客户")
    return JSONResponse({'filename': filename})


@csrf_exempt
@permission_required('customer.add_customer')
def customer_save(request):
    id = request.GET.get('id')
    data = json.loads(request.body)

    try:
        with transaction.atomic():
            serializer = CustomerSerializer.factory(request.user, data, id)
            serializer.validSave()
        return JSONResponse(serializer.data)
    except CustomError, e:
        return JSONError(e.get_error_msg())
    except Exception, e:
        traceback.print_exc()
        return JSONError(u'保存失败！')

@csrf_exempt
@permission_required('customer.delete_customer')
def customer_delete(request):
    id = request.GET.get('id')

    try:
        with transaction.atomic():
            customer = Customer.getById(id)
            BizLog.objects.addnew(request.user, BizLog.DELETE, u"删除客户[%s]，id=%d" % (customer.name, customer.id))
            customer.delete()
    except CustomError, e:
        return JSONError(e.get_error_msg())
    except ProtectedError:
        return JSONError(u'该客户已被使用，禁止删除！')
    except IntegrityError:
        return JSONError(u'该客户已被使用，禁止删除！')
    except Exception, e:
        traceback.print_exc()
        return JSONError(u'删除失败！')
    return JSONResponse({})

@csrf_exempt
@permission_required('customer.import_customer')
def customer_import(request):
    file = request.FILES.get('excel_file')

    try:
        line = 2
        importer = CustomerImporter()
        excel_rows = importer.getExcelData(file)
        with transaction.atomic():
            for excel_row in excel_rows:
                try:
                    row = importer.validRow(excel_row)
                    data = {}
                    data['name'] = row[u'姓名']
                    data['mobile'] = row[u'手机号']
                    data['company_name'] = row[u'公司名称']
                    data['company_tel'] = row[u'公司电话']
                    data['opening_bank'] = row[u'开户行']
                    data['account'] = row[u'账号']
                    data['credit_code'] = row[u'信用代码']
                    data['address'] = row[u'地址']
                    data['notes'] = row[u'备注']
                    serializer = CustomerSerializer.factory(request.user, data)
                    serializer.validSave()
                except CustomError, e:
                    raise CustomError(u'第%d行:%s' % (line, e.get_error_msg()))
                except Exception, e:
                    raise CustomError(u'第%d行:%s' % (line, unicode(e)))
                line += 1
            BizLog.objects.addnew(request.user, BizLog.IMPORT, u"导入客户数据[%s]条" % (line-2))
    except CustomError, e:
        return JSONError(e.get_error_msg())
    except Exception, e:
        traceback.print_exc()
        return JSONError(u'导入失败！')
    return JSONResponse()

@csrf_exempt
@token_required
def customer_select(request):
    param = request.GET.get('param') or request.GET.get('keywords')
    rows = Customer.objects.filter()
    if param:
        rows = rows.filter(
            Q(name__icontains=param)|
            Q(mobile__icontains=param)|
            Q(company_name__icontains=param)
        )

    serializer = CustomerSerializer(rows, many=True)
    return JSONResponse(serializer.data)