from django.views import View
from Model.models import Device_User, Order_Model, CountryModel
from Object.AWS.S3Email import S3Email
from Ansjer.config import CONFIG_INFO, CONFIG_US
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject


class RegionCountryView(View):

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation', None)
        request_dict = request.GET
        return self.validate(request_dict, operation)

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation', None)
        request_dict = request.POST
        return self.validate(request_dict, operation)

    def validate(self, request_dict, operation):
        response = ResponseObject()
        token = TokenObject(request_dict.get('token', None))
        if token.code != 0:
            return response.json(token.code)

        if operation == 'initUserRegion':
            return self.init_user_region(token.userID, request_dict, response)
        else:
            return response.json(414)

    @staticmethod
    def init_user_region(user_id, request_dict, response):
        """
        初始化用户地区
        @param user_id: 用户id
        @param request_dict: 请求数据
        @request_dict number: 国家id
        @param response: 响应
        @return: response
        """
        region_country = request_dict.get('number', None)
        if not region_country:
            return response.json(444)

        device_user_qs = Device_User.objects.filter(userID=user_id).values('region_country')
        if not device_user_qs.exists():
            return response.json(104)

        region_country = int(region_country)
        # 云存用户切换为欧洲地区,发邮件提醒
        if CONFIG_INFO == CONFIG_US:
            country_qs = CountryModel.objects.filter(id=region_country).values('region_id')
            if country_qs.exists():
                if country_qs[0]['region_id'] == 4:
                    order_qs = Order_Model.objects.filter(userID_id=user_id, payType=1, status=1)
                    if order_qs.exists():
                        email_content = '云存用户切换为欧洲地区,请处理云存数据'
                        S3Email().faEmail(email_content, 'servers@ansjer.com')

        device_user_qs.update(region_country=region_country, region_status=True)
        return response.json(0)
