import json
import logging
import random

import scrapy

from FsyAgent.utils.http_utils import json_post


class FtsAgent(scrapy.Spider):
    name = 'portal_agent'
    start_urls = ['http://47.115.228.133:28080/static/data.json']
    insert_api = 'http://39.98.192.5:28082/root/control/manuscript/addBaseManuscript'

    def __init__(self, params=None, *args, **kwargs):
        super(FtsAgent, self).__init__(*args, **kwargs)
        json_params = json.loads(params)
        if 'job_id' in json_params:
            self.job_id = json_params['job_id']

    def parse(self, response, **kwargs):
        rsp_str = response.text
        dataset = json.loads(rsp_str)
        data = random.choice(dataset)['_source']
        insert_data = {
            "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySW5mbyI6eyJpZCI6IjEiLCJ1c2VybmFtZSI6Im1pbmFkIiwiY2hpbmVzZU5hbWUiOiJhZG1pbiIsIm9mZmljZUlkIjoiOGE5ZjVkNGRjMzEzNDE5YThlZmYzMThkNjhhNGI2OWMiLCJvZmZpY2VOYW1lIjoi5Y2V5L2NIiwiY29tcGFueUlkIjoiOGE5ZjVkNGRjMzEzNDE5YThlZmYzMThkNjhhNGI2OWMiLCJqb2JOdW1iZXIiOiIwMDAyMjEiLCJyb2xlTmFtZSI6Iua1i-ivleeuoeeQhuWRmCIsInJvbGVJZGVudGl0aWVzIjpbIjEiXX0sImF1ZCI6WyJzb3MtcmVzb3VyY2UiXSwibG9naW5fbmFtZSI6Im1pbmFkIiwidXNlcl9uYW1lIjoibWluYWQiLCJzY29wZSI6WyJyZWFkIl0sImV4cCI6MTcxMTU2NDY1MCwidXNlcklkIjoiMSIsImF1dGhvcml0aWVzIjpbIlJPTEVfVVNFUiJdLCJqdGkiOiIzODI0MzY4Yi1iMDc0LTQxNGQtOGIzYi1mOGRiNjVkYzY4YTIiLCJjbGllbnRfaWQiOiIxMjM0NTY2Nzg5MCJ9.mRdnESn4oIhb9rLbiZ8kZ1setfvvtWI8kZjNMO7H7ec",
            "isTourist": "1", "columnName": "理论动态", "isBusinessDirection": "1",
            "businessDirectionList": [
                "业务方向1",
                "业务方向2"
            ], "isBureaus": "1", "bureausList": [
                {
                    "companyId": "8a9f5d4dc313419a8eff318d68a4b69c",
                    "officeId": "8a9f5d4dc313419a8eff318d68a4b69c1",
                    "parentIds": [
                        "11111",
                        "22222"
                    ]
                }
            ], "isInside": "1", "isTop": "1", "userId": "1",
            "companyId": "8a9f5d4dc313419a8eff318d68a4b69c", "officeId": "8a9f5d4dc313419a8eff318d68a4b69c",
            "authorName": "admin", 'officeName': data['es_authors'],
            'title': data['es_urltitle'], 'content': data['es_urlcontent']}

        result = json_post(url=self.insert_api, data=insert_data)
        logging.info(result.text)
        yield
