# coding=utf-8

import json

from django.db import transaction
from django.conf import settings
from rest_framework.decorators import action
from utils.custom_modelviewset import CustomModelViewSet
from utils import response_ok, response_error
from utils.exceptions import CustomError
from utils.permission import IsEmployee

from apps.config.models import Config
from apps.config.serializers import ConfigSerializer
from apps.config.filters import ConfigFilter
from apps.commodity.models import Commodity
from apps.log.models import BizLog
from apps.base import Formater


class ConfigViewSet(CustomModelViewSet):
    permission_classes = [IsEmployee, ]
    queryset = Config.objects.filter()
    serializer_class = ConfigSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return response_ok(serializer.data)

    def create(self, request, *args,**kwargs):
        data = json.loads(request.POST.get('data'))
        keys = [
            'point_rule',
            'first_lv1', 'first_lv2', 'first_lv3', 'first_lv4', 'first_lv5',
            'again_lv1', 'again_lv2', 'again_lv3', 'again_lv4', 'again_lv5',
        ]
        with transaction.atomic():
            for item in data:
                config = Config.objects.filter(property=item['key']).first()
                if item['value']:
                    if item['key'] not in keys:
                        raise CustomError(u'综合设置属性[%s]不存在' % item['key'])
                    else:
                        item['value'] = item['value'].strip()

                    if config:
                        config.value = item['value']
                        config.save()
                    else:
                        Config.objects.create(property=item['key'], value=item['value'])
            BizLog.objects.addnew(self.request.user, BizLog.INSERT, u'修改系统配置', data)
        return response_ok()

    @action(methods=['post'], detail=False)
    def set_commodity(self, request):
        '''
        存在commodity_id  查询相应的商品并保存设置
        不存在commodity_id  将原来的设置清空
        :param request:
        :return:
        '''
        commodity_id = request.POST.get('commodity_id', None)

        commodity = None
        if commodity_id:
            commodity = Commodity.objects.filter(id=commodity_id).first()
        if commodity and commodity.delete:
            raise CustomError(u'该商品已删除！')
        if commodity and commodity.status == settings.OFFLINE:
            raise CustomError(u'该商品已下架！')
        with transaction.atomic():
            config = Config.objects.filter(property=Config.KEY_DISTRIBUTOR_COMMODITY).first()
            if config:
                config.value = commodity_id
                config.save()
            else:
                Config.objects.create(property=Config.KEY_DISTRIBUTOR_COMMODITY, value=commodity_id)
        return response_ok()

    @action(methods=['get'], detail=False)
    def get_commodity(self, request):
        '''
        返回设置商品信息  如果该商品在销售过程中 下架或者删除 设置商品同时失效
        :param request:
        :return:
        '''
        commodity_id = Config.get_commodity()
        data = {}
        if commodity_id:
            commodity = Commodity.objects.filter(id=commodity_id, delete=False, status=settings.ONLINE).first()
            if not commodity:
                return response_ok(data)
            data['name'] = commodity.name or ''
            data['price'] = Formater.formatValueShow(commodity.price)
            data['vip_price'] = Formater.formatValueShow(commodity.vip_price)
            data['point_price'] = commodity.point_price or '0.00'
            data['show_image'] = commodity.show_image and commodity.show_image.get_path() or ''
        return response_ok(data)
