const axios = require('axios');
const fs = require('fs');
const sharp = require("sharp")
const { promisify } = require('util');
const tools = require('../../../tools');
const readFile = promisify(fs.readFile);
// var createLinkHeaders = {'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"'}
var finish_call_back = null
const DzSpider = class {
  constructor() {
    this.session = axios.create({
      baseURL: 'https://ms.zhangwenpindu.cn',
      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"'
      }
    });
    this.data = {};
    this.name = '康帅自己的测试';
    this.bookId = '1855159421303205890';
    this.topUpTemplateId = '1854833762266247169';
    this.userName = tools.heiyan_config().default_user.userName;
    this.password = tools.heiyan_config().default_user.password;
    this.folder = __dirname; // 假设图片保存在脚本所在目录
  }

  async otherLogin(call_back){
    var resizedImagePath = await this.getCaptcha();
    await this.ocrImage(resizedImagePath,async (code)=>{
        this.data['code'] = code;
        await this.login();
        call_back(this.data)
    })
  }

  async runTask() {
    var resizedImagePath = await this.getCaptcha();
    await this.ocrImage(resizedImagePath,async (code)=>{
        this.data['code'] = code;
        await this.login();
        // await this.getTopupTemplateMapping();
        await this.createLink();
    })

  }



  async ocrImage(imagePath,call_back) {
    const base64Image = await this.imageToBase64(imagePath);
    const postData = {
      cmd:"ocr",
      base64_image_data:base64Image,
    };

    axios.post('http://127.0.0.1:8080', postData)
      .then(response => {
        call_back(response.data.received_data)
      })
      .catch(error => {
        console.error('There was an error!', error);
    });
  }


  async imageToBase64(imagePath) {
    const imageBuffer = await readFile(imagePath);
    return imageBuffer.toString('base64');
  }
  async getCaptcha() {
    try {
      const response = await this.session.get('/captchaImage');
      const imgBuffer = Buffer.from(response.data.img.replace(/^data:image\/\w+;base64,/, ""), 'base64');
      const imgPath = `${this.folder}/qr.gif`;
      fs.writeFileSync(imgPath, imgBuffer);

      const image = sharp(imgPath);
      const metadata = await image.metadata();
      const resizedImagePath = `${this.folder}/qr_resized.gif`;
      await image.resize({ width: 400, height: Math.round((metadata.height * 400) / metadata.width) }).toFile(resizedImagePath);

      // const { data: { text } } = await this.worker.recognize(resizedImagePath, 'chi_sim');
      // this.worker.terminate();

      // this.data['code'] = text;
      this.data['uuid'] = response.data.uuid;
      return resizedImagePath
    } catch (error) {
      console.error('Error getting captcha:', error);
    }
  }

  async login() {
    try {
      const response = await this.session.post('/login', {
        username: this.userName,
        password: this.password,
        code: this.data['code'],
        uuid: this.data['uuid']
      });

      if (response.data.code === 200) {
        console.log('登录成功');
        this.data['token'] = response.data.token;
      } else {
        console.log('登录失败');
      }
    } catch (error) {
      console.error('Error logging in:', error);
    }
  }

  async getTopupTemplateMapping(bookId,call_back) {
    try {
      const response = await this.session.get('/manage/distribution/topUpTemplateMapping', {
        params: {
          pageNum: '1',
          pageSize: '30',
          bookId: bookId
        },
        headers: {
          'Authorization': `Bearer ${ await tools.getHyToken()}`
        }
      });
      call_back(response.data)
      // console.log('充值模板：', response.data);
    } catch (error) {
      call_back({code:-1})
      console.error('Error getting topup template mapping:', error);
    }
  }

  async getChapterList(bookId,call_back) {
    try {
      const response = await this.session.get('/manage/chapter/list', {
        params: {
          pageNum: '1',
          pageSize: '10',
          bookId: bookId,
          volumeId:0
        },
        headers: {
          'Authorization': `Bearer ${await tools.getHyToken()}`
        }
      });
      call_back(response.data)
      // console.log('章节列表', response.data);
    } catch (error) {
      call_back({code:-1})
      console.error('Error getting topup template mapping:', error);
    }
  }

  async passBackTemplateMapping(call_back) {
    try {
      const response = await this.session.get('/manage/distribution/passBackTemplateMapping', {
        headers: {
          'Authorization': `Bearer ${await tools.getHyToken()}`
        }
      });
      call_back(response.data)
      // console.log('回调模板：', response.data);
    } catch (error) {
      call_back({code:-1})
      console.error('Error getting topup template mapping:', error);
    }
  }

  async createLink() {
    try {
      // createLinkHeaders['Authorization'] =  `Bearer ${this.data.token}`
      // const response = await this.session.post('/manage/distribution/createLink', {
      //   name: this.name,
      //   bookId: this.bookId,
      //   passBackTemplateId: '5',
      //   adPassbackTemplateId: '',
      //   topUpTemplateId: this.topUpTemplateId,
      //   mediaChannel: '1',
      //   group: '35',
      //   paidPoint: '',
      //   site: '5'
      // },createLinkHeaders);

      // console.log('='.repeat(40), '\n',
      //   `原始ID:${response.data.data.originalId}\n`,
      //   `小程序ID:${response.data.data.appId}\n`,
      //   `小程序启动页面:${response.data.data.launchPath}\n`,
      //   `小程序启动参数:${response.data.data.launchParam}\n`,
      //   `跳转路径参数:${response.data.data.fullPath}\n`,
      //   `微信站外链接:${response.data.data.wxMountLink}\n`,
      //   '='.repeat(40), '\n');

      await this.reqPythonCreateLink((response)=>{
        if(response!=null){
            console.log("createLink=",response.data.received_data)
            let params = response.data.received_data.fullPath.split('?')
            // let appId = response.data.data.appId
            let start_page = params[0]
            let start_param = params[1]
            if(finish_call_back!=null){
                finish_call_back(start_page,start_param,response.data.received_data) 
            }
        }
      })
    } catch (error) {
      console.error('Error creating link:', error);
    }
  }

async reqPythonCreateLink(call_back){
    const postData = {
      cmd:"create_link",
      name:this.name,
      bookId:this.bookId,
      topUpTemplateId:this.topUpTemplateId,
      token:this.data.token
    };
  
    axios.post('http://127.0.0.1:8080', postData)
      .then(response => {
          call_back(response)
      })
      .catch(error => {
        call_back(null)
        console.error('There was an error!', error);
    });
  }
};


function login(call_back){
  const spider = new DzSpider();
  spider.otherLogin(call_back)
}
function send(bookId,book_name,call_back){
  const spider = new DzSpider();
  spider.name = book_name;
  spider.bookId = bookId
  finish_call_back = call_back
  spider.runTask();
}

function get_recharge_template(book_id,call_back){
  const spider = new DzSpider();
  spider.getTopupTemplateMapping(book_id,call_back)
}

function get_passBack_template(call_back){
  const spider = new DzSpider();
  spider.passBackTemplateMapping(call_back)
}

function get_paid_point(bookId,call_back){
  const spider = new DzSpider();
  spider.getChapterList(bookId,call_back)
}
module.exports = {send,login,get_recharge_template,get_paid_point,get_passBack_template}

