# -*- coding: utf-8 -*-

import json
import logging

import requests
from django.conf import settings
from django.db import transaction
from django_models_ext import ProvinceModelMixin, ProvinceShortModelMixin
from django_six import CompatibilityBaseCommand, close_old_connections

from statistic.models import ConsumeProvinceSaleStatisticInfo
from utils.redis.connect import r
from utils.redis.rkeys import MINI_PROGRAM_GIS_LIST


logger = logging.getLogger('console')


class Command(CompatibilityBaseCommand):
    def handle(self, *args, **options):

        logger.info('Gis is dealing')

        while True:
            # r.rpushjson('MINI_PROGRAM_GIS_LIST', {
            #     'brand_id': 'brand_id',
            #     'lat': .0,
            #     'lon': .0,
            #     'phone': '18888888888',
            #     'ymd': '20121212',
            # })
            k, v = r.blpopjson(MINI_PROGRAM_GIS_LIST, 60)
            if not v:
                continue

            logger.info(v)

            close_old_connections()

            with transaction.atomic():
                try:
                    gisinfo = requests.get(settings.GIS_2_ADMINISTRATIVE_DIVISION.format(v.get('lat', 0), v.get('lon', 0))).json()
                except Exception as e:
                    logger.info(e.message)

                zh1 = gisinfo.get('data', {}).get('zh1', '')

                province_code = ProvinceModelMixin.PROVINCE_NAME_CODE_DICT.get(zh1) if zh1 else ''

                # 手机归属地
                if not province_code:
                    try:
                        phoneinfo = requests.get(settings.PHONE_2_ADMINISTRATIVE_DIVISION.format(v.get('phone', 0)))
                    except Exception as e:
                        logger.info(e.message)
                        continue
                    try:
                        province_name = json.loads(phoneinfo.content.split('(')[-1][:-1])['data']['area']
                    except Exception as e:
                        logger.info(e.message)
                        continue
                    province_code = ProvinceShortModelMixin.PROVINCE_NAME_CODE_DICT.get(province_name)

                if not province_code:
                    continue

                brand_id = v.get('brand_id', '')
                user_id = v.get('user_id', '')
                ymd = v.get('ymd', '')

                # [消费者维度]省份销量统计
                # 日
                cpssi, _ = ConsumeProvinceSaleStatisticInfo.objects.select_for_update().get_or_create(
                    brand_id=brand_id,
                    province_code=province_code,
                    ymd=ymd,
                )
                if not cpssi.province_name:
                    cpssi.province_name = ProvinceShortModelMixin.PROVINCE_CODE_NAME_DICT.get(province_code)
                cpssi.users = list(set(cpssi.users + [user_id]))
                cpssi.num = len(cpssi.users)
                cpssi.num2 += 1
                cpssi.save()
                # 月
                cpssi, _ = ConsumeProvinceSaleStatisticInfo.objects.select_for_update().get_or_create(
                    brand_id=brand_id,
                    province_code=province_code,
                    ymd=ymd[:6],
                )
                if not cpssi.province_name:
                    cpssi.province_name = ProvinceShortModelMixin.PROVINCE_CODE_NAME_DICT.get(province_code)
                cpssi.users = list(set(cpssi.users + [user_id]))
                cpssi.num = len(cpssi.users)
                cpssi.num2 += 1
                cpssi.save()
                # 年
                cpssi, _ = ConsumeProvinceSaleStatisticInfo.objects.select_for_update().get_or_create(
                    brand_id=brand_id,
                    province_code=province_code,
                    ymd=ymd[:4],
                )
                if not cpssi.province_name:
                    cpssi.province_name = ProvinceShortModelMixin.PROVINCE_CODE_NAME_DICT.get(province_code)
                cpssi.users = list(set(cpssi.users + [user_id]))
                cpssi.num = len(cpssi.users)
                cpssi.num2 += 1
                cpssi.save()

            close_old_connections()
