# encoding: UTF-8
from ....common.sqlSession import SqlSession
from ..service.createDataDictService import CreateDictService
from ..controller import commonController
from logger import logger
from ..model.createDictInfo import CreateDict
import os
from base_framework.public_tools.eureka_api import EurekaAPI
import configparser


class ScrapyController(object):
    def __init__(self, req_json, token):
        self.session = SqlSession()
        self.file_name = req_json.get('fileName')
        self.get_team = req_json.get('team')
        self.team_name = self.get_team.upper()
        self.username = req_json.get('username')
        self.password = req_json.get('password')
        self.token = token
        self.del_flag = 0
        self.req_json = req_json

    def scrapy_enter_db(self):
        """
        对抓取的数据进行入库
        :return:
        """
        get_common_controller = commonController.CommonController()
        create_dict_service = CreateDictService()
        filter_list = list()
        filter_list.append(CreateDict.dict_key == self.team_name)
        filter_list.append(CreateDict.data_type == 1)
        get_team_data = create_dict_service.get_dict_simple_data_by_filters(self.session, filter_list)
        if get_team_data:
            get_path = get_common_controller.get_keyword_path(team=self.team_name, file_name=self.file_name)  # 获取路径值
            print("get_path:", get_path)
            team_name = self.team_name
            get_team = team_name.upper()
            if get_team == "ALL":
                get_list_data = commonController.run(files_path=get_path, end_file="_public_business.py",
                                                     remove_file="common")
            else:
                get_list_data = commonController.run(files_path=get_path, end_file=".py", remove_file="")
            get_scrapy_info = get_common_controller.create_all_info(team_name=self.team_name, list_detail=get_list_data)
            if get_scrapy_info:
                err_msg = "抓取成功"
            else:
                err_msg = "未成功抓取数据，请重试"
        else:
            err_msg = "请检查数据字典，输入正确的组名"
        return err_msg

    def get_git_pull(self):
        """
        拉取git上的代码到本地
        :return:
        """
        create_dict_service = CreateDictService()
        filter_list = list()
        filter_list.append(CreateDict.team_name == self.team_name)
        filter_list.append(CreateDict.data_type == 4)
        get_dict_data = create_dict_service.get_dict_simple_data_by_filters(self.session, filter_list)
        if get_dict_data:
            base = get_dict_data.dict_value
        else:
            base = self.team_name
        username = self.username
        password = self.password
        print(base,"----base----")
        basic_path = os.path.dirname(os.path.abspath(__file__))
        base_path = os.path.abspath(os.path.join(basic_path, '../../../../{}'.format("base_framework")))
        team_path = os.path.abspath(os.path.join(basic_path, '../../../../{}'.format(base)))
        try:
            os.system(f"cd " + base_path + "&& git stash drop")
            os.system(f"cd " + base_path + "&& git pull")
            os.system(f"cd " + team_path + "&& git stash drop")
            os.system(f"cd " + team_path + "&& git pull")
            err_msg = ""
        except:
            err_msg = "拉取代码失败"
        return err_msg

    def get_eureka_ip(self):
        """
        重新获取eureka_ip地址，重写下ip
        :return:
        """
        create_dict_service = CreateDictService()
        filter_list = list()
        filter_list.append(CreateDict.team_name == self.team_name)
        filter_list.append(CreateDict.data_type == 4)
        get_dict_data = create_dict_service.get_dict_simple_data_by_filters(self.session, filter_list)
        if get_dict_data:
            team = get_dict_data.dict_value
        else:
            team = self.team_name
        get_eureka = EurekaAPI()
        get_eureka.team = team
        upper_team = team.upper()
        get_eureka.get_all_server_ip_from_eureka()
        get_eureka.get_all_server_ip_from_eureka(eureka="EC")
        file_path = os.path.dirname(os.path.abspath(__file__))
        env_choose_path = os.path.join(file_path, "../../../../../base_config/env_choose.ini")
        cof = configparser.ConfigParser()
        cof.read(env_choose_path, encoding='utf-8')
        cof.set(section="run_evn_name", option="current_team", value=upper_team)
        with open(env_choose_path, 'w') as fw:  # 循环写入
            cof.write(fw)
        test_vi_path = os.path.join(file_path, "test_vi.py")
        os.system(f"echo 1 >> {test_vi_path}")
        return True
