import json
import time

import requests
from urllib.parse import unquote


class Ding():
    def __init__(self):
        self.img_path = "../img"
        self.session = requests.session()

    def get_token(self):
        url = "http://7ddapi.7dingdong.com/login/index"
        login_data = {
            'user_name': "杨永超",
            'password': "Yyc119911@",
            'token': 'F7C2753FC7BFD7C8F838DE4AD85702C9',
            't': '1534814081',
            'device': 3,
            'company': 1,
            'api': 'login/index',
        }

        response = self.session.post(url=url, data=login_data)
        requests.session()
        data1 = json.loads(response.text)
        user_data = data1.get('data')
        user_psw = user_data.get('psw')
        coding_data = unquote(user_psw)
        json_data = unquote(coding_data)
        source_data = json.loads(json_data)
        print(source_data)
        token = source_data.get("tokenId")
        self.token = token

    def get_condition(self):
        data = {
            'token': "FE9D7B55FE084D334EF4B8DF9B542E3A",
            "t": "1534401238",
            "api": "shoppingmall/getallcate",
        }
        r2 = self.session.post('http://7ddapi.7dingdong.com/shoppingmall/getallcate',
                               data=data,
                               )
        data1 = json.loads(r2.text)
        print(data1)

    # 第二次请求
    def get_data(self):
        self.get_token()
        data = {
            'token': "55F891D076DCFEB8D62759BEE6D98B65",
            "t": "1534401238",
            "cate_id": 0,#二级分类id
            'cate_id_1': 8,#分类id
            "zhe": 0,
            "sort": 0,
            "order": "Desc",
            "keywords": "",
            "brand_id": "",
            "page": 1,
            "limit": 20,
            'tokenId': self.token,
            'c': 0,
            "priceStart": "",
            "priceEnd": "",
            "api": "shoppingmall/goods_listPc",
            #keywords搜索框字段
        }
        r2 = self.session.post('http://7ddapi.7dingdong.com/shoppingmall/goods_listPc',
                               data=data,
                               )
        data = json.loads(r2.text)
        # 第三次请求
        datas = data.get("data")
        for i in datas:
            r = requests.get(i.get("default_image"))

            now = time.time()  # 返回float数据

            # 毫秒级时间戳
            # 将获取到的图片二进制流写入本地文件
            with open('%s/%d.png' % (self.img_path, int(round(now * 1000))), 'wb') as f:
                # 对于图片类型的通过r.content方式访问响应内容,将响应内容写入baidu.png中
                f.write(r.content)
            print(i)


# 自动帮我们保存cookie信息

try:
    Ding().get_condition()
except Exception as e:
    print("结束")