<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: `<table width="100%" cellpadding="0" cellspacing="0" align="center" bgcolor="#84C0F2" width="600">
    <tbody>
        <tr>
            <td></td>
            <td style="height: 82px"></td>
            <td></td>
        </tr>
        <tr>
            <td></td>
            <td align="center" style="font: bold 64px/1.1 Arial, sans-serif;color: white">
                驾驭未来<br/>
                新能源时代
            </td>
            <td></td>
        </tr>
        <tr>
            <td></td>
            <td style="height: 8px"></td>
            <td></td>
        </tr>
        <tr>
            <td width="100"></td>
            <td align="center" bgcolor="#ffffff" style="font: 24px Arial, sans-serif;color: #84C0F2">
                {{expo_name}}
            </td>
            <td  width="100"></td>
        </tr>
        <tr>
            <td></td>
            <td style="height: 8px">

            </td>
            <td></td>
        </tr>
        <tr>
            <td></td>
            <td align="center" style="font: 18px Arial, sans-serif;color: #FFFFFF">
                {{start_date}} - {{end_date}}
            </td>
            <td></td>
        </tr>
        <tr>
            <td></td>
            <td style="height: 8px">

            </td>
            <td></td>
        </tr>
        <tr>
            <th colspan="3">
                <img style="width: 100%;display:block" src="https://matchexpo.obs.cn-north-1.myhuaweicloud.com/common/2025/0915/68c7713a49819.jpg" />
            </th>
        </tr>
        <tr>
            <td bgcolor="#ffffff"></td>
            <td align="center" bgcolor="#ffffff">
                {{contact_phone}} | {{location}}
            </td>
            <td bgcolor="#ffffff"></td>
        </tr>
        <tr>
            <td bgcolor="#ffffff"></td>
            <td bgcolor="#ffffff" height="12px"></td>
            <td bgcolor="#ffffff"></td>
        </tr>
    </tbody>
</table>`,
      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-model="templateInfo.name" class="name" />
        <el-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-model="templateInfo.name" placeholder="请输入模板名称" />
          <span class="label">模板描述</span>
          <el-input v-model="templateInfo.description" type="textarea" rows="6" placeholder="请输入模板描述" />
          <el-button 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 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>
