# coding=utf-8
import json
import traceback

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

from apps.account.decorators import permission_required, token_required
from apps.exceptions import ExportChange, CustomError
from apps.foundation.models import BizLog
from apps.supplier.filters import SupplierFilter
from apps.supplier.models import Supplier
from apps.supplier.resources import SupplierResource, SupplierImporter
from apps.supplier.serializers import SupplierSerializer
from libs import utils
from libs.http import DataGridJSONResponse, JSONResponse, JSONError

@csrf_exempt
@permission_required('supplier.view_supplier')
def supplier_list(request):
    f = SupplierFilter(request.GET, queryset=Supplier.objects.all())
    rows, total = utils.get_page_data(request, f.qs)
    serializer = SupplierSerializer(rows, many=True)
    return DataGridJSONResponse(serializer.data, total)


@csrf_exempt
@permission_required('supplier.export_supplier')
def supplier_export(request):
    f = SupplierFilter(request.GET, queryset=Supplier.objects.all())
    serializer = SupplierSerializer(f.qs, many=True)
    export_data = ExportChange.dict_to_obj(serializer)
    export_data = SupplierResource().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('supplier.add_supplier')
def supplier_save(request):
    id = request.GET.get('id')
    data = json.loads(request.body)
    try:
        with transaction.atomic():
            serializer = SupplierSerializer.factory(request.user, data, id)
            serializer.validSave()
    except CustomError, e:
        return JSONError(e.get_error_msg())
    except Exception, e:
        traceback.print_exc()
        return JSONError(u'保存失败！')
    return JSONResponse(serializer.data)

@csrf_exempt
@permission_required('supplier.delete_supplier')
def supplier_delete(request):
    id = request.GET.get('id')

    try:
        with transaction.atomic():
            supplier = Supplier.getById(id)
            BizLog.objects.addnew(request.user, BizLog.DELETE, u"删除供应商[%s]，id=%d" % (supplier.name, supplier.id))
            supplier.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('supplier.import_supplier')
def supplier_import(request):
    file = request.FILES.get('excel_file')

    try:
        line = 2
        importer = SupplierImporter()
        excel_rows = importer.getExcelData(file)
        with transaction.atomic():
            for excel_row in excel_rows:
                try:
                    row = importer.validRow(excel_row)
                    type = row[u'类别']
                    if type == u'耗材':
                        type = Supplier.CONSUMABLE
                    elif type == u'原料':
                        type = Supplier.MATERIAL
                    else:
                        raise CustomError(u'类别有误，只能填耗材或者原料')
                    data = {}
                    data['name'] = row[u'名称']
                    data['type'] = type
                    data['contacts'] = row[u'联系人']
                    data['phone_number'] = row[u'电话']
                    data['address'] = row[u'地址']
                    data['opening_bank'] = row[u'开户行']
                    data['account'] = row[u'账号']
                    data['tax_number'] = row[u'税号']
                    data['credit_code'] = row[u'信用代码']
                    data['notes'] = row[u'备注']
                    serializer = SupplierSerializer.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()

@token_required
def supplier_select(request):
    type = int(request.GET.get('type'))
    supplier = Supplier.objects.filter(type=type, enabled=True)
    data = []
    for row in supplier:
        item = {
            'id': row.id,
            'value': row.name
        }
        data.append(item)
    return JSONResponse(data)


@csrf_exempt
@token_required
def supplier_options(request):
    data = Supplier.TYPE_CHOICES_DICT
    return JSONResponse(data)