'use strict';

const Service = require('egg').Service;
const puppeteer = require('puppeteer');
const fs = require('fs');
const path = require('path');
const cookiePath = '../public/data/ali-cookies.json';

const browserConfig = {
  headless: false,
  defaultViewport: {
    width: 1024,
    height: 768,
  },
};

class MailService extends Service {
  async getImage(mails) {
    const { ctx } = this;
    const result = [];
    let cookie = fs.readFileSync(path.join(__dirname, cookiePath)).toString();

    try {
      const browser = await puppeteer.launch(browserConfig);
      const page = await browser.newPage();
      if (cookie) await ctx.helper.addCookies(JSON.parse(cookie), page);
      ctx.logger.info('aliyun mail: 进入https://qiye.aliyun.com');
      await page.goto('https://qiye.aliyun.com', { waitUntil: 'networkidle2' });
      const loginPanelIframe = await page.$('.login_panel_iframe');
      if (loginPanelIframe) {
        const src = await page.$eval('.login_panel_iframe', el => el.src);
        await page.goto(src);
        const dingLoginFrame = await page.frames().find(f => f.name() === 'ding-login-iframe');
        await dingLoginFrame.$eval('#username', input => { input.value = ''; });
        await dingLoginFrame.type('#username', ctx.app.config.aliyun[0].account);
        await dingLoginFrame.type('#password', ctx.app.config.aliyun[0].password);
        await dingLoginFrame.click('#login_remember_check');
        await dingLoginFrame.click('#login_submit_btn');

        await page.waitFor(2500);
        let loginErrorLine = await dingLoginFrame.$('#login_checkcode_ico');
        if (loginErrorLine) {
          ctx.logger.warn('aliyun mail: 登录需要输入验证码!');
          let j = 0;
          while (loginErrorLine && j < 50) {
            j++;
            ctx.logger.warn(`aliyun mail: 第${j}次输入验证码!`);
            await ctx.helper.writeLoginCode(dingLoginFrame, ctx);
            await page.waitFor(5000);
            loginErrorLine = await page.$('.login_panel_iframe');
          }
          if (j === 50) throw new Error('验证码尝试过多');
        }
        cookie = await page.cookies('https://qiye.aliyun.com');
        fs.writeFileSync(path.join(__dirname, cookiePath), JSON.stringify(cookie));
      }
      ctx.logger.info('aliyun mail: 已登录');

      for (let i = 0; i < mails.length; i++) {
        const receiver = mails[i].receiver;
        await page.click('.e_textbox_input_wrap');
        await page.click('.header_search_advanced');
        await page.type('.criteria_receiver .e_entry_input', receiver);
        await page.click('.e_d_button_wrap .e_b');
        await page.waitFor(2500);
        await page.click('.root_frame_wrap>div:nth-child(3) .cblist_virtual_block_wrap .maillist_item_wrap');
        await page.waitFor(2500);
        await page.click('.mailsession_view_wrap_b .mailheader_spread');
        const receiverText = await page.$eval('div[_msdn="wrap"] .e_entry_label_wrap', el => el.innerHTML);
        if (!receiverText || receiverText.trim() !== receiver.split('@')[0]) {
          ctx.logger.warn(`未搜索到邮件. mail:${receiver}`);
          continue;
        }
        const sendText = await page.$eval('.maildetail_header_wrap .maildetail_status_send_text', el => el.innerHTML);
        if (sendText !== '发送成功，查看读信状态') {
          ctx.logger.warn(`邮件截图失败. reason: ${sendText}, mail:${receiver}`);
          continue;
        }
        const mailContainer = await page.$('.root_frame_wrap>div:nth-child(3) .maildetail_active');
        await mailContainer.screenshot({ path: `./app/public/images/${receiver}.png` });
        // const filePath = await this.service.fdfs.upload(path.join(__dirname, './app/public/images/${receiver}.png'));
        result.push({ receiver, status: '上传成功' });
      }
    } catch (e) {
      console.log('截图失败', e || e.message);
    }

    return result;
  }
}

module.exports = MailService;
