<script>
import Vue from 'vue'
import domtoimage from 'dom-to-image-more'
import * as monaco from 'monaco-editor'
import { upload } from '@/api/system'
import { saveTemplate } from '@/api/template'
import { getExpoList } from '@/api/expo'
export default Vue.extend({
  name: 'Index',
  components: {
  },
  props: [
    'isCompletionInit'
  ],
  data() {
    return {
      code: `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>邀请函</title>
</head>
<body style="padding: 48px 32px;">
  <div class="invitation-letter-container"
    style="border: 1px solid #E5E7EB;
    border-radius: 12px;
    padding: 32px;"
  >
    <div class="head-box"
      style="display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 32px;"
    >
      <div class="head-left-box"
        style="display: flex;
        align-items: center;
        grid-gap: 16px;"
      >
        <div class="img-box"
          style="width: 96px;
          height: 48px;"
        >
          <img src="https://oss.starify.cn/matchpages/share_center/2025/0910/8401/68c0de742aa57/logo.png" alt="logo.png" style="width: 100%;height: 100%;">
        </div>
        <div class="head-title-box"
          style="color: #1A4789;
          font-weight: bold;"
        >
          <div class="head-english-head"
            style="font-size: 24px;
            line-height: 1.3;"
          >
            CHINAPLAS 2024
          </div>
          <div class="head-chinese-head"
            style="font-size: 18px;
            line-height: 1.6;"
          >
            {{expo_name}}
          </div>
        </div>
      </div>
      <div class="head-right-box"
        style="color: #4B5563;
        font-size: 16px;
        line-height: 1.5;"
      >
        <div class="head-date" style="text-align: end;">
          日期 / Date：2023年8月16日
        </div>
        <div class="head-serial-number" style="text-align: end;">
          文件编号 / Ref No.：PR-CPS24-35913
        </div>
      </div>
    </div>
    <div class="content-box-1"
      style="font-weight: bold;
      font-size: 20px;
      line-height: 1.4;
      margin-bottom: 16px;"
    >
      <div class="chinese-content">
        致相关人士：
      </div>
      <div class="english-content" style="color: #4B5563;">
        To Whom It May Concern:
      </div>
    </div>
    <div class="content-box-2"
      style="font-weight: bold;
      font-size: 18px;
      line-height: 1.6;
      margin-bottom: 24px;"
    >
      <div class="chinese-content">
        关于：{{expo_name}}
      </div>
      <div class="english-content" style="color: #4B5563;">
        Re: The 36th International Exhibition on Plastics and Rubber Industries
      </div>
    </div>
    <div class="content-box-3"
      style="font-size: 16px;
      line-height: 1.5;
      margin-bottom: 32px;"
    >
      <div class="chinese-content">
        我们很高兴邀请以下代表于2024年4月23日至26日访问上海，{{expo_name}}。
      </div>
      <div class="english-content" style="color: #4B5563;">
        We are pleased to invite the following representative to visit Shanghai from April 23-26, 2024, to attend CHINAPLAS 2024.
      </div>
    </div>
    <div class="info-list" style="margin-bottom: 32px;">
      <div class="info-item" style="display: flex; align-items: center;">
        <div class="label-box" style="padding: 12px 16px; width: 24%; background-color: #F9FAFB; height: 46px; border-bottom: 1px solid #F9FAFB; display: flex; flex-direction: column; justify-content: space-between;">
          <div class="chinese-label">姓名</div>
          <div class="english-label" style="color: #6B7280;">Name</div>
        </div>
        <div class="value-box" style="flex: 1; padding: 12px 16px; border-bottom: 1px solid #e8eaed; height: 46px; display: flex; flex-direction: column; justify-content: space-between;">
          <div class="chinese-value">{{full_name}}</div>
          <div class="english-value" style="color: #6B7280;">Zhang Xiaoming</div>
        </div>
      </div>
      <div class="info-item" style="display: flex; align-items: center;">
        <div class="label-box" style="padding: 12px 16px; width: 24%; background-color: #F9FAFB; height: 46px; border-bottom: 1px solid #F9FAFB; display: flex; flex-direction: column; justify-content: space-between;">
          <div class="chinese-label">性别</div>
          <div class="english-label" style="color: #6B7280;">Gender</div>
        </div>
        <div class="value-box" style="flex: 1; padding: 12px 16px; border-bottom: 1px solid #e8eaed; height: 46px; display: flex; flex-direction: column; justify-content: space-between;">
          <div class="chinese-value">男</div>
          <div class="english-value" style="color: #6B7280;">Male</div>
        </div>
      </div>
      <div class="info-item" style="display: flex; align-items: center;">
        <div class="label-box" style="padding: 12px 16px; width: 24%; background-color: #F9FAFB; height: 46px; border-bottom: 1px solid #F9FAFB; display: flex; flex-direction: column; justify-content: space-between;">
          <div class="chinese-label">出生日期</div>
          <div class="english-label" style="color: #6B7280;">Date of Birth</div>
        </div>
        <div class="value-box" style="flex: 1; padding: 12px 16px; border-bottom: 1px solid #e8eaed; height: 46px; display: flex; flex-direction: column; justify-content: space-between;">
          <div class="chinese-value">1985年6月15日</div>
          <div class="english-value" style="color: #6B7280;">June 15, 1985</div>
        </div>
      </div>
      <div class="info-item" style="display: flex; align-items: center;">
        <div class="label-box" style="padding: 12px 16px; width: 24%; background-color: #F9FAFB; height: 46px; border-bottom: 1px solid #F9FAFB; display: flex; flex-direction: column; justify-content: space-between;">
          <div class="chinese-label">国籍</div>
          <div class="english-label" style="color: #6B7280;">Nationality</div>
        </div>
        <div class="value-box" style="flex: 1; padding: 12px 16px; border-bottom: 1px solid #e8eaed; height: 46px; display: flex; flex-direction: column; justify-content: space-between;">
          <div class="chinese-value">中国香港特别行政区</div>
          <div class="english-value" style="color: #6B7280;">Hong Kong SAR, China</div>
        </div>
      </div>
      <div class="info-item" style="display: flex; align-items: center;">
        <div class="label-box" style="padding: 12px 16px; width: 24%; background-color: #F9FAFB; height: 46px; border-bottom: 1px solid #F9FAFB; display: flex; flex-direction: column; justify-content: space-between;">
          <div class="chinese-label">护照号码</div>
          <div class="english-label" style="color: #6B7280;">Passport No.</div>
        </div>
        <div class="value-box" style="flex: 1; padding: 12px 16px; border-bottom: 1px solid #e8eaed; height: 46px; display: flex; flex-direction: column; justify-content: center;">
          <div class="chinese-value">{{id_number}}</div>
          <div class="english-value" style="color: #6B7280;"></div>
        </div>
      </div>
      <div class="info-item" style="display: flex; align-items: center;">
        <div class="label-box" style="padding: 12px 16px; width: 24%; background-color: #F9FAFB; height: 46px; border-bottom: 1px solid #F9FAFB; display: flex; flex-direction: column; justify-content: space-between;">
          <div class="chinese-label">签发日期</div>
          <div class="english-label" style="color: #6B7280;">Date of Issue</div>
        </div>
        <div class="value-box" style="flex: 1; padding: 12px 16px; border-bottom: 1px solid #e8eaed; height: 46px; display: flex; flex-direction: column; justify-content: space-between;">
          <div class="chinese-value">2021年3月15日</div>
          <div class="english-value" style="color: #6B7280;">March 15, 2021</div>
        </div>
      </div>
      <div class="info-item" style="display: flex; align-items: center;">
        <div class="label-box" style="padding: 12px 16px; width: 24%; background-color: #F9FAFB; height: 46px; border-bottom: 1px solid #F9FAFB; display: flex; flex-direction: column; justify-content: space-between;">
          <div class="chinese-label">有效期至</div>
          <div class="english-label" style="color: #6B7280;">Date of Expiry</div>
        </div>
        <div class="value-box" style="flex: 1; padding: 12px 16px; border-bottom: 1px solid #e8eaed; height: 46px; display: flex; flex-direction: column; justify-content: space-between;">
          <div class="chinese-value">2031年3月14日</div>
          <div class="english-value" style="color: #6B7280;">March 14, 2031</div>
        </div>
      </div>
      <div class="info-item" style="display: flex; align-items: center;">
        <div class="label-box" style="padding: 12px 16px; width: 24%; background-color: #F9FAFB; height: 46px; border-bottom: 1px solid #F9FAFB; display: flex; flex-direction: column; justify-content: space-between;">
          <div class="chinese-label">签发地点</div>
          <div class="english-label" style="color: #6B7280;">Place of Issue</div>
        </div>
        <div class="value-box" style="flex: 1; padding: 12px 16px; border-bottom: 1px solid #e8eaed; height: 46px; display: flex; flex-direction: column; justify-content: space-between;">
          <div class="chinese-value">中国香港特别行政区</div>
          <div class="english-value" style="color: #6B7280;">Hong Kong SAR, China</div>
        </div>
      </div>
      <div class="info-item" style="display: flex; align-items: center;">
        <div class="label-box" style="padding: 12px 16px; width: 24%; background-color: #F9FAFB; height: 46px; border-bottom: 1px solid #F9FAFB; display: flex; flex-direction: column; justify-content: space-between;">
          <div class="chinese-label">公司名称</div>
          <div class="english-label" style="color: #6B7280;">Company Name</div>
        </div>
        <div class="value-box" style="flex: 1; padding: 12px 16px; border-bottom: 1px solid #e8eaed; height: 46px; display: flex; flex-direction: column; justify-content: space-between;">
          <div class="chinese-value">{{company}}</div>
          <div class="english-value" style="color: #6B7280;">Hong Kong International Trading Co., Ltd.</div>
        </div>
      </div>
      <div class="info-item" style="display: flex; align-items: center;">
        <div class="label-box" style="padding: 12px 16px; width: 24%; background-color: #F9FAFB; height: 46px; border-bottom: 1px solid #F9FAFB; display: flex; flex-direction: column; justify-content: space-between;">
          <div class="chinese-label">职务</div>
          <div class="english-label" style="color: #6B7280;">Position</div>
        </div>
        <div class="value-box" style="flex: 1; padding: 12px 16px; border-bottom: 1px solid #e8eaed; height: 46px; display: flex; flex-direction: column; justify-content: space-between;">
          <div class="chinese-value">{{position}}</div>
          <div class="english-value" style="color: #6B7280;">Sales Director</div>
        </div>
      </div>
      <div class="info-item" style="display: flex; align-items: center;">
        <div class="label-box" style="padding: 12px 16px; width: 24%; background-color: #F9FAFB; height: 46px; border-bottom: 1px solid #F9FAFB; display: flex; flex-direction: column; justify-content: space-between;">
          <div class="chinese-label">城市</div>
          <div class="english-label" style="color: #6B7280;">City</div>
        </div>
        <div class="value-box" style="flex: 1; padding: 12px 16px; border-bottom: 1px solid #e8eaed; height: 46px; display: flex; flex-direction: column; justify-content: space-between;">
          <div class="chinese-value">{{city}}</div>
          <div class="english-value" style="color: #6B7280;">Hong Kong</div>
        </div>
      </div>
      <div class="info-item" style="display: flex; align-items: center;">
        <div class="label-box" style="padding: 12px 16px; width: 24%; background-color: #F9FAFB; height: 46px; border-bottom: 1px solid #F9FAFB; display: flex; flex-direction: column; justify-content: space-between;">
          <div class="chinese-label">邮编</div>
          <div class="english-label" style="color: #6B7280;">Postal Code</div>
        </div>
        <div class="value-box" style="flex: 1; padding: 12px 16px; border-bottom: 1px solid #e8eaed; height: 46px; display: flex; flex-direction: column; justify-content: center;">
          <div class="chinese-value">999077</div>
          <div class="english-value" style="color: #6B7280;"></div>
        </div>
      </div>
      <div class="info-item" style="display: flex; align-items: center;">
        <div class="label-box" style="padding: 12px 16px; width: 24%; background-color: #F9FAFB; height: 46px; border-bottom: 1px solid #F9FAFB; display: flex; flex-direction: column; justify-content: space-between;">
          <div class="chinese-label">联系电话</div>
          <div class="english-label" style="color: #6B7280;">Phone</div>
        </div>
        <div class="value-box" style="flex: 1; padding: 12px 16px; border-bottom: 1px solid #e8eaed; height: 46px; display: flex; flex-direction: column; justify-content: center;">
          <div class="chinese-value">{{mobile_country_code}} {{mobile}}</div>
          <div class="english-value" style="color: #6B7280;"></div>
        </div>
      </div>
      <div class="info-item" style="display: flex; align-items: center;">
        <div class="label-box" style="padding: 12px 16px; width: 24%; background-color: #F9FAFB; height: 46px; border-bottom: 1px solid #F9FAFB; display: flex; flex-direction: column; justify-content: space-between;">
          <div class="chinese-label">Email</div>
          <div class="english-label" style="color: #6B7280;">Email</div>
        </div>
        <div class="value-box" style="flex: 1; padding: 12px 16px; border-bottom: 1px solid #e8eaed; height: 46px; display: flex; flex-direction: column; justify-content: center;">
          <div class="chinese-value">{{email}}</div>
          <div class="english-value" style="color: #6B7280;"></div>
        </div>
      </div>
    </div>
    <div class="chinese-text" style="line-height: 1.5;">
      请为上述代表安排相关签证。我们确认所有机票费用、住宿机票和旅程期间的保险费用将由上述公司承担或由上述代表自行承担。如果您需要任何进一步的信息，请随时与我们联系。
    </div>
    <div class="english-text" style="color: #4B5563; line-height: 1.5; margin-bottom: 48px;">
      Please arrange the relevant visa for the above representative. We confirm that all airfare, accommodation, and travel insurance costs during the journey will be borne by the above company or the representative. If you need any further information, please feel free to contact us.
    </div>
    <div class="bottom-box" style="display: flex; justify-content: space-between; align-items: end; position: relative;">
      <div class="bottom-left-box">
        <div style="line-height: 1.5;">北京雅展展览服务有限公司</div>
        <div style="line-height: 1.5; color: #4B5563;">Beijing Adsale Exhibition Services Co., Ltd.</div>
        <div style="line-height: 1.5;">电话 / Tel：+86 10 8460 0789</div>
        <div style="line-height: 1.5;">邮箱 / Email：info@adsale.com.cn</div>
      </div>
      <div class="bottom-right-box">
        <div style="line-height: 1.5; text-align: end;">此致</div>
        <div style="line-height: 1.5; color: #4B5563; text-align: end;">Yours sincerely,</div>
        <div style="line-height: 1.5; text-align: end;">张淑娴 女士</div>
        <div style="line-height: 1.5; color: #4B5563; text-align: end;">Ms. Zhang Shuxian</div>
        <div style="line-height: 1.5; text-align: end;">展会负责人</div>
        <div style="line-height: 1.5; text-align: end;">Exhibition Director</div>
      </div>
      <img src="https://oss.starify.cn/matchpages/share_center/2025/0910/2919/68c11d315441d/DIV%401x.png" alt="DIV@1x.png" style="position: absolute; top: -110px; right: 0;">
    </div>
  </div>
</body>
</html>`,
      viewCode: '',
      exhibitorSetting: {},
      userSetting: {
        first_name: '张',
        last_name: '三',
        full_name: '张三',
        id_type: '中国居民身份证',
        id_number: '430111200001011111',
        mobile: '18888888888',
        mobile_country_code: '+86',
        email: 'zhansan@gmail.com',
        company: '北京某某有限公司',
        department: '销售部门',
        position: '客户专员',
        country: '中国',
        province: '北京市',
        city: '北京',
        address: '烟袋斜街',
        interested_products: '预制菜',
        business_type: '销售'
      },
      expoList: [],
      expoId: 0,
      timer: null,
      editor: null,
      templateInfo: {
        id: '',
        name: '未命名表单',
        description: '',
        pic: ''
      },
      loading: false
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      if (this.$route.params.id) {
        this.loading = true
        this.templateInfo.id = this.$route.params.id
        const templateInfo = JSON.parse(sessionStorage.getItem('invitationInfo'))
        this.templateInfo.name = templateInfo.name
        this.templateInfo.description = templateInfo.description
        this.code = templateInfo.content
        console.log(templateInfo)
        this.loading = false
      }
      getExpoList(1, 1000).then(res => {
        this.expoList = res.data.data
        for (var i = 0; i < this.expoList.length; i++) {
          if (this.expoList[i].status === 0) {
            this.expoId = 0
            this.exhibitorSetting = this.expoList[i]
            break
          }
        }
        this.initEditor()
        this.parseCode()
      }).catch(err => {
        this.loading = false
      })
    },
    changeExpo(index) {
      this.exhibitorSetting = this.expoList[index]
      this.parseCode()
    },
    saveTemp() {
      if (this.loading) { return }
      this.loading = true
      domtoimage
        .toPng(document.querySelector('#invitation-viewer'))
        .then((dataUrl) => {
          var arr = dataUrl.split(','); var mime = arr[0].match(/:(.*?);/)[1]
          var bstr = atob(arr[1]); var n = bstr.length; var u8arr = new Uint8Array(n)
          while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
          }
          const picFile = new File([u8arr], 'invitation.png', { type: mime })
          upload(picFile).then(res => {
            saveTemplate(this.templateInfo.id, this.templateInfo.name, this.templateInfo.description, this.code, res.data.file)
              .then(res => {
                console.log(res)
                this.$router.push('/invitation/list')
                this.loading = false
              }).catch(err => {
                this.loading = false
              })
          }).catch(err => {
            this.loading = false
          })
        })
    },
    parseCode() {
      if (this.timer) { clearTimeout(this.timer) }
      this.timer = setTimeout(() => {
        let processedCode = this.code
        const regex = /\{\{([^}]+)\}\}/g
        processedCode = processedCode.replace(regex, (match, key) => {
          const trimmedKey = key.trim()
          if (Object.prototype.hasOwnProperty.call(this.exhibitorSetting, trimmedKey)) {
            return this.exhibitorSetting[trimmedKey]
          }
          if (Object.prototype.hasOwnProperty.call(this.userSetting, trimmedKey)) {
            return this.userSetting[trimmedKey]
          }
          return match
        })
        this.viewCode = processedCode
      }, 500)
    },
    initEditor() {
      console.log(this.$isCompletionInit)
      if (this.$getIsInit() === false) {
        this.$setIsInit()
        monaco.languages.registerCompletionItemProvider('html', {
          triggerCharacters: ['{'],
          provideCompletionItems: (model, position) => {
            const textUntilPosition = model.getValueInRange({
              startLineNumber: position.lineNumber,
              startColumn: 1,
              endLineNumber: position.lineNumber,
              endColumn: position.column
            })
            const match = textUntilPosition.match(/\{\{$/)
            if (!match) {
              return { suggestions: [] }
            }
            const suggestions = Object.keys(this.exhibitorSetting).map(key => {
              return {
                label: key,
                kind: monaco.languages.CompletionItemKind.Field,
                insertText: key,
                detail: `插入展会数据: ${key}`,
                range: {
                  startLineNumber: position.lineNumber,
                  startColumn: position.column,
                  endLineNumber: position.lineNumber,
                  endColumn: position.column
                }
              }
            })
            const suggestions_2 = Object.keys(this.userSetting).map(key => {
              return {
                label: key,
                kind: monaco.languages.CompletionItemKind.Field,
                insertText: key,
                detail: `插入用户信息: ${key}`,
                range: {
                  startLineNumber: position.lineNumber,
                  startColumn: position.column,
                  endLineNumber: position.lineNumber,
                  endColumn: position.column
                }
              }
            })
            console.log(this.userSetting, this.exhibitorSetting)
            return { suggestions: [...suggestions, ...suggestions_2] }
          }
        })
      }
      this.editor = monaco.editor.create(document.getElementById('editor'), {
        value: this.code,
        language: 'html',
        theme: 'vs-light',
        automaticLayout: true,
        minimap: {
          enabled: false
        }
      })
      this.editor.onDidChangeModelContent(() => {
        this.code = this.editor.getValue()
        this.parseCode()
      })
    },
    popoverOpen() {

    }
  }
})
</script>

<template>
  <div v-loading="loading" class="main-box">
    <div class="head">
      <div class="head-left">
        <el-input v-permission="'invitation.rename'" v-model="templateInfo.name" class="name" />
        <el-select v-permission="'invitation.select'" v-model="expoId" @change="changeExpo">
          <el-option v-for="(expo,index) in expoList" :key="expo.id" :label="expo.expo_name" :value="index" />
        </el-select>
      </div>

      <el-popover
        popper-class="invitation-popover"
        placement="left-start"
        width="500"
        trigger="click"
        @after-enter="popoverOpen"
      >
        <div class="body">
          <span class="label">模板名称</span>
          <el-input v-permission="'invitation.rename'" v-model="templateInfo.name" placeholder="请输入模板名称" />
          <span class="label">模板描述</span>
          <el-input v-permission="'invitation.desc'" v-model="templateInfo.description" type="textarea" rows="6" placeholder="请输入模板描述" />
          <el-button v-permission="'invitation.save'" class="button" type="primary" @click="saveTemp()">保存</el-button>
        </div>
        <el-button slot="reference" icon="el-icon-plus" type="primary">保存模板</el-button>
      </el-popover>

    </div>
    <div class="body">
      <div class="editor">
        <div v-permission="'invitation.editor'" id="editor" class="editor-box" />
      </div>
      <div class="viewer">
        <div class="viewer-box">
          <div id="invitation-viewer" v-html="viewCode" />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.main-box{
  height: 100%;
  width: 100%;
  display: grid;
  grid-template-rows: auto 1fr;
  grid-gap: 24px;
  .body{
    height: 100%;
    position: relative;
    display: grid;
    grid-gap: 16px;
    grid-template-columns: 1fr 1fr;
    .editor{
      border: 1px lightgray solid;
      border-radius: 8px;
      overflow: hidden;
      position: relative;
      .editor-box{
        position: absolute;
        top: 0;
        left: 0;
        height: 100%;
        width: 100%;
      }
    }
    .viewer{
      overflow: hidden;
      border: 1px lightgray solid;
      border-radius: 8px;
      position: relative;
      .viewer-box{
        overflow: hidden;
        overflow-y: auto;
        position: absolute;
        top: 0;
        left: 0;
        height: 100%;
        width: 100%;
        div{
          background: white;
        }
      }
    }
  }
  .head{
    display: flex;
    justify-content: space-between;
    .head-left{
      width: 50%;
      display: flex;
      gap: 8px;
      .name{
        flex: 1;
      }
    }

  }
}
</style>
<style>
.invitation-popover{
  .body{
    display: flex;
    flex-direction: column;
    gap: 8px;
    .button{
      margin-top: 16px;
    }
  }
}
</style>
