# coding=utf-8
import requests
import json
from django.db import transaction
from rest_framework.decorators import action
from django.utils import timezone
from utils import response_ok
from utils.permission import permission_required
from utils.custom_modelviewset import CustomModelViewSet
from utils.exceptions import CustomError
from apps.foundation.models import BizLog, Config
from apps.account import tenant_log
from apps.images.models import Images
from apps.store.models import Shop, StoreBrand
from apps.vehicle.models import Brand
from apps.store.filters import ShopFilter
from .serializers import ShopSerializer
from hashlib import md5
from rest_framework.views import APIView


class ShopViewSet(CustomModelViewSet):
    queryset = Shop.objects.filter(delete=False)
    serializer_class = ShopSerializer

    @permission_required('shop.browse_shop')
    def filter_queryset(self, queryset):
        queryset = queryset.filter()
        f = ShopFilter(self.request.GET, queryset=queryset)
        return f.qs

    def perform_create(self, serializer):
        super(ShopViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        tenant_log(self.request.user, BizLog.INSERT, u'添加门店[%s]，id=%d' % (instance.name, instance.id),validated_data)

    def destroy(self, request, *args, **kwargs):
        with transaction.atomic():
            instance = self.get_object()
            instance.delete = True
            instance.save()
            tenant_log(self.request.user, BizLog.DELETE, u'删除门店[%s]，id=%d' % (instance.name, instance.id))
        return response_ok()

    @action(methods=['post'], detail=True)
    def update_shop(self, request, pk):
        file = request.FILES.get('image', None)
        brands = request.POST.get('brands')
        user = request.user
        instance = self.get_object()

        if instance.delete:
            raise CustomError(u'该门店已删除，禁止操作！')

        with transaction.atomic():
            serializer = self.get_serializer(instance, data=request.data)
            serializer.is_valid(raise_exception=True)
            self.perform_update(serializer)

            tenant_log(user, BizLog.UPDATE, u'修改门店[%s]，id=%d' % (instance.name, instance.id), request.data)

            StoreBrand.objects.filter(store=instance).delete()

            if brands:
                brands = brands.split(',')
                for item in brands:
                    brand = Brand.objects.filter(id=int(item), enabled=True, delete=False).first()

                    if not brand:
                        raise CustomError(u'所选择的品牌不存在或不可用或已被删除')
                    StoreBrand.objects.create(store=instance, brand=brand)

            if file:
                old_img = instance.img
                img = Images.objects.employee_addnew(user, Images.SHOP_FILE, file)
                instance.img = img
                instance.save()
                if old_img:
                    old_img.del_images()

        return response_ok()

    @action(methods=['get'], detail=False)
    def update_company(self, request):
        with transaction.atomic():
            xgj_ip = Config.getConfigValue(Config.KEY_XGJ_IP)
            xgj_session_key = Config.getConfigValue(Config.KEY_XGJ_SESSION_KEY)
            if not xgj_ip:
                raise CustomError(u'没有配置销管佳地址，请前往基础设置中配置！')

            if not xgj_session_key:
                raise CustomError(u'没有配置销管佳密钥，请前往基础设置中配置！')
            ts = timezone.now().strftime('%Y%m%d%H%M%S')
            token = xgj_session_key + ts

            m = md5()
            m.update(token.encode("utf8"))
            sign = m.hexdigest()

            url = xgj_ip + 'wechat/applet/member/company/?ts=' + ts + '&sign=' + sign
            param = {}
            result = requests.post(url=url, data=json.dumps(param))
            result = result.json()
            if result['success']:
                data = result['data']
                for item in data:
                    store = Shop.objects.filter(xgj_id=item['id']).first()
                    if store:
                        store.delete = False
                        store.save()
                    else:
                        Shop.objects.create(
                            name=item['name'],
                            addr=item['company_address'],
                            tel=item['company_tel'],
                            is_xgj=False,
                            xgj_id=item['id'],
                        )

                tenant_log(request.user, BizLog.UPDATE, u'更新销管佳门店')
            else:
                if 'errors' in result:
                    raise CustomError(u'请求失败--' + str(result['errors']))
                else:
                    raise CustomError(u'请求失败')
        return response_ok()


class ShopSearchSearch(APIView):
    def get(self, request):

        keyword = request.GET.get('keyword')
        rows = Shop.objects.filter(delete=False, enabled=True)

        if keyword:
            rows = rows.filter(name__icontains=keyword)

        data = []
        for row in rows:
            item ={
                'value': row.id,
                'id': row.id,
                'name': row.name
            }
            data.append(item)

        return response_ok(data)