#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/3/21 0021
# @Author  : justin.郑 3907721@qq.com
# @File    : area_baidu.py
# @Desc    : 获取百度迁徙数据

import json
import requests
import pandas as pd
from gopup.event.cons import province_dict, city_dict


def migration_area_baidu(area="武汉市", indicator="move_in", date="20200201"):
    """
    百度地图慧眼-百度迁徙-XXX迁入地详情
    百度地图慧眼-百度迁徙-XXX迁出地详情
    以上展示 top100 结果，如不够 100 则展示全部
    迁入来源地比例: 从 xx 地迁入到当前区域的人数与当前区域迁入总人口的比值
    迁出目的地比例: 从当前区域迁出到 xx 的人口与从当前区域迁出总人口的比值
    https://qianxi.baidu.com/?from=shoubai#city=0
    :param area: 可以输入 省份 或者 具体城市 但是需要用全称
    :type area: str
    :param indicator: move_in 迁入 move_out 迁出
    :type indicator: str
    :param date: 查询的日期 20200101以后的时间
    :type date: str
    :return: 迁入地详情/迁出地详情的前50个
    :rtype: pandas.DataFrame
    """
    try:
        if area == "全国":
            payload = {
                "dt": "country",
                "id": 0,
                "type": indicator,
                "date": date,
            }
        else:
            city_dict.update(province_dict)
            inner_dict = dict(zip(city_dict.values(), city_dict.keys()))
            if inner_dict[area] in province_dict.keys():
                dt_flag = "province"
            else:
                dt_flag = "city"
            payload = {
                "dt": dt_flag,
                "id": inner_dict[area],
                "type": indicator,
                "date": date,
            }

        url = "https://huiyan.baidu.com/migration/cityrank.jsonp"
        r = requests.get(url, params=payload)
        json_data = json.loads(r.text[r.text.find("({") + 1 : r.text.rfind(");")])
        return pd.DataFrame(json_data["data"]["list"])
    except:
        return None


def migration_scale_baidu(area="武汉市", indicator="move_out", date="20210112"):
    """
    百度地图慧眼-百度迁徙-迁徙规模
    * 迁徙规模指数：反映迁入或迁出人口规模，城市间可横向对比
    * 城市迁徙边界采用该城市行政区划，包含该城市管辖的区、县、乡、村
    https://qianxi.baidu.com/?from=shoubai#city=0
    :param area: 可以输入 省份 或者 具体城市 但是需要用全称
    :type area: str
    :param indicator: move_in 迁入 move_out 迁出
    :type indicator: str
    :param date: 结束查询的日期 20200101 以后的时间
    :type end_date: str
    :return: 时间序列的迁徙规模指数
    :rtype: pandas.DataFrame
    """
    try:
        if area == "全国":
            payload = {
                "dt": "country",
                "id": 0,
                "type": indicator,
                "date": date
            }
        else:
            city_dict.update(province_dict)
            inner_dict = dict(zip(city_dict.values(), city_dict.keys()))
            try:
                if inner_dict[area] in province_dict.keys():
                    dt_flag = "province"
                else:
                    dt_flag = "city"

                payload = {
                    "dt": dt_flag,
                    "id": inner_dict[area],
                    "type": indicator,
                    "date": date
                }
            except Exception as e:
                return "省份 或者 具体城市名 错误"
        url = "https://huiyan.baidu.com/migration/historycurve.jsonp"
        r = requests.get(url, params=payload)
        json_data = json.loads(r.text[r.text.find("({") + 1 : r.text.rfind(");")])
        temp_df = pd.DataFrame.from_dict(json_data["data"]["list"], orient="index")
        temp_df.index = pd.to_datetime(temp_df.index)
        temp_df.columns = ["迁徙规模指数"]
        return temp_df
    except:
        return None


if __name__ == "__main__":
    tmp = migration_scale_baidu(area="武汉", indicator="move_out")
    print(tmp)


