# -*- coding: utf-8 -*-

import base64
import json
import ssl
import warnings
from PIL import Image
import ddddocr
import onnxruntime
import requests
import os
onnxruntime.set_default_logger_severity(3)

ssl._create_default_https_context = ssl._create_unverified_context
warnings.filterwarnings("ignore")


def base64_2_img(img_path, base64_content, resize=False, width=400, height=200):
    # base64保存至图片
    img_content = base64_content.split(',')[-1]
    img_data = base64.b64decode(img_content)
    try:
        with open(img_path, mode="wb") as f:
            f.write(img_data)
            f.close()
        if resize:
            with Image.open(img_path) as image:
                resized_image = image.resize((width, height))
                resized_image.save(img_path)
    except Exception as e:
        print(f"base64_to_img error:{e}")


class DzSpider(object):
    def __init__(self):
        self.folder = fr'{os.getcwd()}'
        self.session = requests.session()
        self.data = {}
        self.name = ''
        self.bookId = '1854909287941992450'
        self.topUpTemplateId = '1854833762266247169'
        self.user_name = '康帅'
        self.password = 'Ks25666'
        self.headers_str = '''
        Accept: application/json, text/plain, */*
        Accept-Language: zh-CN,zh;q=0.9
        Cache-Control: no-cache
        Connection: keep-alive
        Content-Type: application/x-www-form-urlencoded
        Origin: https://manage.zhangwenpindu.cn
        Pragma: no-cache
        Referer: https://manage.zhangwenpindu.cn/
        Sec-Fetch-Dest: empty
        Sec-Fetch-Mode: cors
        Sec-Fetch-Site: same-site
        User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36
        sec-ch-ua: "Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"
        sec-ch-ua-mobile: ?0
        sec-ch-ua-platform: "Windows"
        '''
        self.headers = dict(
            [[y.strip() for y in x.strip().split(':', 1)] for x in self.headers_str.strip().split('\n') if x.strip()])

    def run_task(self):

        # 获取验证码
        self.get_captcha()
        # 登录
        self.login()
        # 充值模板
        self.get_topup_template_mapping()
        # 创建链接
        self.create_link()

    def get_topup_template_mapping(self):
        url = "https://ms.zhangwenpindu.cn/manage/distribution/topUpTemplateMapping"
        params = {
            "pageNum": "1",
            "pageSize": "30",
            "bookId": self.bookId
        }
        self.headers['Authorization'] = f'Bearer {self.data.get("token")}'
        res = requests.get(url, headers=self.headers, params=params).json()
        mbs = res.get('data')
        print(f'充值模板：{mbs}')

    def create_link(self):
        url = "https://ms.zhangwenpindu.cn/manage/distribution/createLink"
        data = {
            "name": self.name,
            "bookId": self.bookId,
            "passBackTemplateId": "5",
            "adPassbackTemplateId": "",
            "topUpTemplateId": self.topUpTemplateId,
            "mediaChannel": "1",
            "group": "35",
            "paidPoint": "",
            "site": "5"
        }
        res = requests.post(url, headers=self.headers, data=data).json()
        # print(res)
        print(f'{"=" * 40}\n'
              f'原始ID:{res.get("data").get("originalId")}\n'
              f'小程序ID:{res.get("data").get("appId")}\n'
              f'小程序启动页面:{res.get("data").get("launchPath")}\n'
              f'小程序启动参数:{res.get("data").get("launchParam")}\n'
              f'跳转路径参数:{res.get("data").get("fullPath")}\n'
              f'微信站外链接:{res.get("data").get("wxMountLink")}\n'
              f'{"=" * 40}\n')

    def get_captcha(self):
        url = "https://ms.zhangwenpindu.cn/captchaImage"
        res = self.session.get(url, headers=self.headers).json()
        img_path = fr'{self.folder}\qr.gif'
        base64_2_img(img_path, 'data:image/gif;base64,' + res.get('img'))
        ocr = ddddocr.DdddOcr(show_ad=False)
        with open(img_path, 'rb') as f:
            img_bytes = f.read()
            result = ocr.classification(img_bytes)
            f.close()
            self.data['code'] = result
            self.data['uuid'] = res.get('uuid')

    def login(self):
        url = "https://ms.zhangwenpindu.cn/login"
        headers = {
            "Accept": "application/json, text/plain, */*",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Content-Type": "application/json;charset=UTF-8",
            "Origin": "https://manage.zhangwenpindu.cn",
            "Pragma": "no-cache",
            "Referer": "https://manage.zhangwenpindu.cn/",
            "Sec-Fetch-Dest": "empty",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Site": "same-site",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36",
            "sec-ch-ua": "\"Chromium\";v=\"130\", \"Google Chrome\";v=\"130\", \"Not?A_Brand\";v=\"99\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\""
        }
        data = {
            'username': self.user_name,
            'password': self.password,
            'code': self.data['code'],
            'uuid': self.data['uuid']
        }
        data = json.dumps(data, separators=(',', ':'))
        res = self.session.post(url, headers=headers, data=data).json()
        if res.get('code') == 200:
            print('登录成功')
            self.data['token'] = res.get('token')
        else:
            print('登录失败')


if __name__ == '__main__':
    spider = DzSpider()

    # 用户名、密码
    spider.user_name = '康帅'
    spider.password = 'Ks25666'

    # 推广名称
    spider.name = '测试的'
    # 书的ID
    spider.bookId = '1854909287941992450'
    # 充值模板对应的key值
    spider.topUpTemplateId = '1854833762266247169'

    spider.run_task()
