/* eslint-disable */
var fs = require('fs')
const PDFDocument = require('pdfkit');
var JsBarcode = require('jsbarcode');
const dayjs = require('dayjs')
const { Client } = require('pg')
var _ = require('@sailshq/lodash')
var async = require('async')
var archiver = require('archiver')
const { query } = require('../async-db')

// Canvas v2
var { createCanvas } = require("canvas");

process.on('message', async (batch_num) => {

  console.log('Message from parent:', batch_num);
  await createPdf(batch_num)
});

async function template_004 (embarkingInfo, itineraries, batch_num) {
  try {
    let isJapan = false
    // let pdf_path = 'assets/pdf_file/' + embarkingInfo.cruise
    let pdf_path = '/mnt/assets/pdf_file/' + embarkingInfo.cruise
    cruise = embarkingInfo.cruise
    let filename = embarkingInfo.cruise + '-' + embarkingInfo.room_number + '-' + embarkingInfo.last_name
      + ' ' + embarkingInfo.first_name + '.pdf'
    let path = pdf_path + '/' + filename
    if (!embarkingInfo['ship_name_cn']) {
      let shipInfo = await query(`select * from ship where id = ? limit 1`, [embarkingInfo.ship])
      console.log(shipInfo)
      if (shipInfo.length > 0) {
        embarkingInfo['ship_name_cn'] = shipInfo[0].name_cn
        embarkingInfo['ship_name_en'] = shipInfo[0].name_en
      }
    }
    console.log()
    let berthInfo = await query(`select * from berthinfo where ship = ? and room_number = ? limit 1`, [embarkingInfo.ship, embarkingInfo.room_number])
    if (berthInfo.length > 0) {
      berthInfo = berthInfo[0]
    } else {
      berthInfo = null;
    }

    var doc = new PDFDocument({size: 'A4'});
    // var stream = doc.pipe(blobStream());
    if (!fs.existsSync(pdf_path)) {
      fs.mkdirSync(pdf_path);
    }

    doc.pipe(fs.createWriteStream(path))
    doc.image('assets/images/qingdao/page1.png', 19, 0, {fit: [595, 843]})
    var canvas = createCanvas(400, 45);
    JsBarcode(canvas, embarkingInfo.ticket_code, {displayValue: false});
    const buf = canvas.toBuffer()
    var lCanvas = createCanvas(150, 45);
    let lCode = embarkingInfo.ticket_code;
    for (let i = 0; i < (9 - embarkingInfo.ticket_code.length); i ++) {
      lCode = '0' + lCode
    }
    lCode = '0' + lCode + '1'
    JsBarcode(lCanvas, lCode,{displayValue: true});
    const lbuf = lCanvas.toBuffer()
    if (embarkingInfo.tour_group_code && embarkingInfo.tour_group_code != '' && embarkingInfo.tour_group_code != 'CH820897' && embarkingInfo.tour_group_code != 'CH821897') {
      doc.font('assets/SIMHEI.TTF').fontSize(15)
        .text(embarkingInfo.tour_group_code, 110, 121);
    } else {
    }

    doc.font('assets/SIMHEI.TTF').fontSize(13)
      .text('歌诗达邮轮', 110, 240);
    doc.font('assets/SIMHEI.TTF').fontSize(13)
      .text('Costa Cruises', 110, 254)
    doc.font('assets/SIMHEI.TTF').fontSize(10)
      .text(embarkingInfo.ship_name_cn, 110, 268)
    doc.font('assets/SIMHEI.TTF').fontSize(10)
      .text(embarkingInfo.ship_name_en, 110, 279)
    doc.font('assets/SIMHEI.TTF').fontSize(13)
      .text(cruise, 110, 320)
    doc.font('assets/SIMHEI.TTF').fontSize(13)
      .text(dayjs.unix(embarkingInfo.date + 28800).format('YYYY-MM-DD'), 110, 358)
    doc.font('assets/SIMHEI.TTF').fontSize(13)
      .text('青岛国际邮轮母港中心', 110, 392)
    doc.font('assets/SIMHEI.TTF').fontSize(13)
      .text('Qingdao Cruise Terminal', 110, 406)
    let y = 435
    console.log(itineraries)
    _.each(itineraries, item => {
      if (item.country == 'Japan') {
        isJapan = true
      }
      let a = item.date + 28800
      doc.font('assets/SIMHEI.TTF').fontSize(12)
        .text(dayjs.unix(a).format('YYYY-MM-DD') + ' ' + item.location_cn + item.location, 110, y)
      y = y + 12
    })
    doc.image(buf, 308, 144, {width: 260, height: 42.5})
    doc.font('assets/SIMHEI.TTF').fontSize(10)
      .text(embarkingInfo.ticket_code, 408, 190);
    doc.font('assets/SIMHEI.TTF').fontSize(15)
      .text(embarkingInfo.name_cn, 110, 560);
    doc.font('assets/SIMHEI.TTF').fontSize(15)
      .text(embarkingInfo.last_name + ' ' + embarkingInfo.first_name, 110, 580);
    doc.font('assets/SIMHEI.TTF').fontSize(15)
      .text(embarkingInfo.country_code && embarkingInfo.country_code == 'RC' ? 'CHN' : embarkingInfo.country_code, 110, 614);
    doc.font('assets/SIMHEI.TTF').fontSize(15)
      .text(embarkingInfo.passport_code, 110, 657);
    let identity_card = embarkingInfo.identity_card
    // const preiStr = identity_card && identity_card.slice(0, 6);
    // const endiStr = identity_card && identity_card.slice(14).padStart(12, '*')
    // doc.font('assets/SIMHEI.TTF').fontSize(15)
    //   .text(preiStr + endiStr, 121, 676);
    let prepStr = ''
    let endpStr = ''
    if (embarkingInfo.phone && embarkingInfo.phone != '-') {
      let phone = embarkingInfo.phone
      prepStr = phone && phone.slice(0, 3);
      endpStr = phone && phone.slice(7).padStart(8, '*')
    }
    doc.font('assets/SIMHEI.TTF').fontSize(15)
      .text(prepStr + endpStr, 110, 700)
    doc.font('assets/SIMHEI.TTF').fontSize(15)
      .text(embarkingInfo.order_no, 368, 248)
    if (berthInfo) {
      doc.font('assets/SIMHEI.TTF').fontSize(15)
        .text(berthInfo["floor"], 368, 290)
    }
    doc.font('assets/SIMHEI.TTF').fontSize(15)
      .text(embarkingInfo.room_number, 368, 335)
    if (embarkingInfo.tour_group_code && embarkingInfo.tour_group_code != '' && embarkingInfo.tour_group_code != 'CH820897' && embarkingInfo.tour_group_code != 'CH821897') {
      doc.font('assets/SIMHEI.TTF').fontSize(15)
        .text('团队', 368, 381);
    } else {
      doc.font('assets/SIMHEI.TTF').fontSize(15)
        .text('散客', 368, 381);
    }
    if (berthInfo) {
      // doc.image('assets/muster_station.png', 475, 338, {fit: [72, 62]})
      doc.font('assets/SIMHEI.TTF').fontSize(20).fillColor('white')
        .text(berthInfo.area, 500, 370)
      // if (berthInfo.area == 'A') {
      //   doc.image('assets/muster_station_A.png', 485, 338, {fit: [72, 62]})
      // } else {
      //   doc.image('assets/muster_station_B.png', 485, 338, {fit: [72, 62]})
      // }
    } else {
      // doc.image('assets/muster_station_other.png', 485, 338, {fit: [72, 62]})
    }
    if (isJapan) {
      doc.addPage().image('assets/images/qingdao/page3.png', 19, 0, {fit: [595, 843]})
    } else {
      doc.addPage().image('assets/images/qingdao/page2.png', 19, 0, {fit: [595, 843]})
    }
    doc.image(buf, 388, 36, {width: 200, height: 45})
    // doc.rotate(90)
    // doc.image('assets/muster_station_A.png',0,0,{fit: [72, 62]})
    // doc.rotate(180, {origin: [0, 0]})
    // doc.restore()
    doc.addPage().image('assets/page3.png', 0, 0, {fit: [595, 843]})
    doc.font('assets/SIMHEI.TTF').fontSize(18)
      .text(embarkingInfo.ship_name_en, 226, 500, {width: 169.5, align: 'center'})
    doc.font('assets/SIMHEI.TTF').fontSize(18)
      .text(dayjs.unix(embarkingInfo.date).format('YYYY-MM-DD'), 226, 535,{width: 169.5, align: 'center'})
    doc.font('Helvetica-Bold').fontSize(18)
      .text(embarkingInfo.room_number, 297, 567)
    doc.font('assets/SIMHEI.TTF').fontSize(18)
      .image(lbuf, 261, 621, {width: 113, height: 50})
    doc.font('assets/SIMHEI.TTF').fontSize(18)
      .text(embarkingInfo.last_name + ' ' + embarkingInfo.first_name, 226, 695, {width: 169.5, align: 'center'})
    doc.font('assets/SIMHEI.TTF').fontSize(18)
      .text(embarkingInfo.order_no, 226, 740,{width: 169.5, align: 'center'})

    doc.save()
    doc.rotate(180, {origin: [0, 0]})
    doc.font('assets/SIMHEI.TTF').fontSize(18)
      .text(embarkingInfo.order_no, -396.5, -100,{width: 169.5, align: 'center'})
    doc.font('assets/SIMHEI.TTF').fontSize(18)
      .text(embarkingInfo.last_name + ' ' + embarkingInfo.first_name, -396.5, -146,{width: 169.5, align: 'center'})
    doc.font('assets/SIMHEI.TTF').fontSize(18)
      .image(lbuf, -375, -229, {width: 113, height: 50})
    doc.font('Helvetica-Bold').fontSize(18)
      .text(embarkingInfo.room_number, -324, -277)
    doc.font('assets/SIMHEI.TTF').fontSize(18)
      .text(dayjs.unix(embarkingInfo.date).format('YYYY-MM-DD'), -396.5, -307,{width: 169.5, align: 'center'})
    doc.font('assets/SIMHEI.TTF').fontSize(18)
      .text(embarkingInfo.ship_name_en, -396.5, -342,{width: 169.5, align: 'center'})
    doc.restore()
    doc.end()
  } catch (e) {
    console.log(e.toString())
    let taskmessage = await query("update taskmessage set status = ? where name = ? and status = ? ", ['fail', batch_num+'_create_pdf', 'process'])
    // await client.end()
    process.exit(0)
  }
}

module.exports = template_004
