from DrissionPage import ChromiumPage, ChromiumOptions
import tkinter as tk
from tkinter import ttk
import time
import json
from lxml import etree
import os
import traceback
import random


class Boss_zhipin():
    def __init__(self):
        self.user_phone = None
        self.init_user_info()
        self.init_quit_chrome()
        # 使用系统浏览器用户目录 调用本地浏览器
        try:
            co = ChromiumOptions().use_system_user_path()
            self.page = ChromiumPage(co)
        except:
            print('启动浏览器失败：：')
            Boss_zhipin().run()

    def get_search_data(self):
        span_list = self.page.eles('xpath://*[@id="headerWrap"]/div/div/div[2]/div[2]/ul//li')
        print(len(span_list))
        self.item_value = []
        options_list = []
        for span in span_list:
            options_list.append(span.text)
            # 返回属性值
            self.item_value.append(span.attr('value'))

        if options_list:
            selected_text = self.combo_box(options_list)
            print('用户选择：：', selected_text)
            ele = self.page.eles('xpath://div[@class="ui-dropmenu-label"]')[1]
            ele.click()
            self.index_num = options_list.index(selected_text)
            print(self.index_num, '下标')
            ac = span_list[self.index_num]
            ac.click()
            self.page.reconnect(wait=3)

    def is_longin_boss(self):
        self.page.get('https://www.zhipin.com/web/chat/recommend')
        html_resp = self.page.html
        if '当前登录状态已失效' in html_resp:
            self.show_popup()
        else:
            self.login_boss()

    def login_boss(self):
        self.page.get('https://www.zhipin.com/web/chat/recommend')
        self.page.refresh()  # 刷新页面
        # # self.page.reconnect(wait=2)
        self.get_search_data()
        time.sleep(1)
        print(self.item_value)
        self.get_page_uid()

    def get_page_uid(self):
        jobId = self.item_value[self.index_num]
        tab = self.page.new_tab()  # 新建标签页，获取标签页对象
        for i in range(1, 2):
            url = f'https://www.zhipin.com/wapi/zpjob/rec/geek/list?age=16,-1&major=0&activation=0&gender=0&recentNotView=0&exchangeResumeWithColleague=0&school=0&switchJobFrequency=0&experience=0&degree=0&salary=0&intention=0&jobId={jobId}&page={i}&coverScreenMemory=0&cardType=0'
            print(url)
            tab.get(url)
            tab.reconnect(wait=1)
            html_str = tab.html
            resp = etree.HTML(html_str)
            pre_str = resp.xpath('//pre/text()')[0]
            pre_str = str(pre_str).encode('utf-8').decode('utf-8', 'ignore')
            pre_dict = json.loads(pre_str.replace('\n', ' ').replace('\r', ' '))
            print('message::', pre_dict['message'])
            if pre_dict['message'] == 'Success':
                geekList = pre_dict['zpData']['geekList']
                for geek in geekList:
                    for i in range(3):
                        securityId = geek['geekCard']['securityId']
                        user_url = f'https://www.zhipin.com/wapi/zpjob/view/geek/info?expectId=863113475&jid=346431432&lid=e423292e-4f52-460f-9242-5e4a7103f02e.f1:common.eyJzZXNzaW9uSWQiOiIyMjEyNWQ1NS0xNzYxLTQ3YjgtOTA1Zi04NzQ1YzQ4YWUzYzAiLCJyY2RCelR5cGUiOiJmMV9icmNkIn0.5&wayType=0&sourceType=3&securityId={securityId}'
                        print(user_url)
                        tab.get(user_url)
                        user_html = tab.html
                        user_resp = etree.HTML(user_html)
                        user_pre_str = user_resp.xpath('//pre/text()')[0]
                        user_pre = str(user_pre_str).encode('utf-8').decode('utf-8', 'ignore')
                        usr_pre_dict = json.loads(user_pre.replace('\n', ' ').replace('\r', ' '))
                        if usr_pre_dict['message'] == '查看太频繁，请稍后重试':
                            print('查看太频繁, 随机睡眠 5-20s')
                            time.sleep(random.randint(5, 20))
                            print('打印usr_pre_dict', usr_pre_dict)
                            continue
                        else:
                            print('返回成功', usr_pre_dict)
                            time.sleep(random.randint(1, 3))
                            break
            else:
                with open('error_log.txt', 'w', encoding='utf-8')as f:
                    f.write(html_str)
            self.page.reconnect(wait=2)
        print('关闭浏览器')
        self.page.quit()

    def get_input(self, root, entry):
        self.user_phone = entry.get()  # 获取文本框中的内容
        root.destroy()  # 关闭窗口

    def user_input(self):
        root = tk.Tk()
        root.title("用户信息输入")
        root.geometry("400x250")
        # 创建标签
        label = tk.Label(root, text="请输入您的登录手机号", font=("Helvetica", 12))
        label.pack(pady=15)
        # 创建文本框
        entry = tk.Entry(root, width=30)
        entry.pack(pady=20)

        # 创建按钮
        button = tk.Button(root, text="确定", command=lambda: self.get_input(root, entry), width=10, height=2,
                           font=("Helvetica", 12))
        button.pack(pady=15)
        root.mainloop()

    def combo_box(self, options):
        # 创建主窗口
        root = tk.Tk()
        root.title("下拉框选择具体搜索发布岗位")

        # 创建下拉框
        combo_box = ttk.Combobox(root, state="readonly", width=100)
        combo_box.configure(height=20)  # 设置下拉列表的最大可见行数
        # 定义选项列表

        # 将选项添加到下拉框中
        combo_box["values"] = options
        # 设置默认选中的选项
        combo_box.current(0)

        # 创建变量用于存储用户选择的文本
        selected_text_var = tk.StringVar()

        # 创建回调函数，获取用户选择的文本
        def get_selected_text():
            selected_text = combo_box.get()
            selected_text_var.set(selected_text)
            # 关闭窗口
            root.destroy()

        # 创建按钮，用于获取用户选择的文本
        btn = tk.Button(root, text="  确定  ", command=get_selected_text, width=20, height=2)
        # 显示下拉框和按钮
        combo_box.pack(pady=100)
        btn.pack(pady=100)
        # 运行主循环
        root.mainloop()
        return selected_text_var.get()

    def continue_after_login(self):
        popup.destroy()  # 关闭提示框
        self.login_boss()  # 登录成功执行下一步

    def show_popup(self):
        global popup
        popup = tk.Tk()
        popup.wm_title("账号登录状态提示")
        # 设置整个窗口大小
        popup.geometry("600x250")
        label = tk.Label(popup, text="当前账号登录状态已失效, 请先扫码登录", font=("Helvetica", 25))
        label.pack(pady=60)
        # 添加确定按钮，设置字体大小为16
        confirm_button = tk.Button(popup, text="已扫码登录 确定", command=self.continue_after_login, font=("Helvetica", 16))
        confirm_button.pack()
        # 获取屏幕尺寸
        screen_width = popup.winfo_screenwidth()
        screen_height = popup.winfo_screenheight()
        # 计算窗口在屏幕中央的位置
        x = (screen_width - popup.winfo_reqwidth()) / 2
        y = (screen_height - popup.winfo_reqheight()) / 2
        # 设置窗口位置
        popup.geometry("+%d+%d" % (x, y))
        popup.mainloop()

    def init_quit_chrome(self):
        try:
            pr_name = "chrome.exe"
            os.system('%s%s' % ("taskkill /F /IM ", pr_name))
        except Exception as e:
            print("强制关闭chrome.exe失败：", e, f"\n{traceback.format_exc()}")

    def init_user_info(self):
        file_path = 'user_info.txt'
        if os.path.exists(file_path):
            print(f"当前用户文档存在.")
            with open('user_info.txt', 'r', encoding='utf-8')as f:
                self.user_phone = f.read()
        else:
            print(f"当前用户文档不存在.")
            self.user_input()
            with open('user_info.txt', 'w', encoding='utf-8')as f:
                f.write(self.user_phone)

    def run(self):
        print('当前登录用户：', self.user_phone)
        time.sleep(1)
        self.is_longin_boss()
        time.sleep(3)


if __name__ == '__main__':
    Boss_zhipin().run()
