<script>
import Vue from 'vue'
import hugerte from 'hugerte'
import 'hugerte/models/dom'
import 'hugerte/icons/default'
import 'hugerte/themes/silver'
import 'hugerte/skins/ui/oxide/skin.js'
import 'hugerte/skins/ui/oxide/content.js'
import 'hugerte/skins/content/default/content.js'

import XLSX from 'xlsx'
import { getAudienceList, sentInvitation, getFormList, getFormInfo, importAudience } from '@/api/form'
import { getExpoList, getMyExpoInfo } from '@/api/expo'
import { getTemplateList } from '@/api/template'
import expoPopover from '@/views/components/expoPopover.vue'
export default Vue.extend({
  name: 'Index',
  components: { expoPopover },
  data() {
    return {
      expoList: [],
      userList: [],
      invitation_data: {
        code: '',
        tempIndex: 0,
        data: [],
        exhibitorSetting: {},
        userSetting: {},
        show: false,
        page: 0,
        last_page: 1,
        is_sending: false
      },
      import_data: {
        showImport: false,
        step: 0,
        exhibitor_id: '',
        xlsx: '',
        file: ''
      },
      loading: false,
      searchTimer: null,
      searchWord: '',
      is_export: 0,
      expo_id: 0,
      current_page: 0,
      page_size: 20,
      last_page: 1,
      total: 0,
      ossUrl: process.env.VUE_APP_OSS_DOMAIN
    }
  },
  mounted() {
    this.getAudience()
    this.getExpoList()
    this.getInvitationList()
  },
  methods: {
    creatExcel(exhibitor_id) {
      if (exhibitor_id !== '') {
        if (this.loading) { return }
        this.loading = true
        if (exhibitor_id === 0) {
          getFormList(1, 1)
            .then(res => {
              if (res.data.data.length > 0) {
                return getFormInfo(res.data.data[0].id)
              } else {
                this.$notify({
                  title: '出错了',
                  message: '请先创建至少一个表单模板',
                  type: 'warning'
                })
                this.loading = false
                return
              }
            })
            .then(res2 => {
              const workBook = XLSX.utils.book_new()
              const lineData = []
              res2.data.fields.forEach(field => {
                lineData.push(field.field_label)
              })
              const data = [lineData]
              const workSheet = XLSX.utils.aoa_to_sheet(data)
              XLSX.utils.book_append_sheet(workBook, workSheet, '观众表')
              this.import_data.xlsx = workBook
              this.loading = false
            }).catch(err => {
            this.$notify({
              title: '提示',
              message: '获取表单列表失败：'+err,
              type: 'error'
            })
              this.loading = false
            })
        } else {
          getMyExpoInfo(exhibitor_id).then(res => {
            if (res.data.form_template_id) {
              return getFormInfo(res.data.form_template_id)
            } else {
              this.$notify({
                title: '出错了',
                message: '这个展会没有绑定表单',
                type: 'error'
              })
              this.loading = false
              return
            }
          }).then(res2 => {
            const workBook = XLSX.utils.book_new()
            const lineData = []
            res2.data.fields.forEach(field => {
              lineData.push(field.field_label)
            })
            const data = [lineData]
            const workSheet = XLSX.utils.aoa_to_sheet(data)
            XLSX.utils.book_append_sheet(workBook, workSheet, '观众表')
            this.import_data.xlsx = workBook
            this.loading = false
          }).catch(err => {
            this.$notify({
              title: '提示',
              message: '获取展会信息失败'+err,
              type: 'error'
            })
            this.loading = false
          })
        }
      }
    },
    downloadTemplate() {
      if (this.import_data.xlsx) {
        this.import_data.step = 1
        XLSX.writeFile(this.import_data.xlsx, '观众表.xlsx')
      }
    },
    uploadExcel(event) {
      this.import_data.file = event.target.files[0]
    },
    importData() {
      if (this.loading) { return }
      this.loading = true
      if (this.import_data.file && this.import_data.exhibitor_id !== '') {
        importAudience(this.import_data.file, this.import_data.exhibitor_id).then(res => {
          this.$notify({
            title: '导入完成',
            message: '添加了' + res.data.update_count + '条数据',
            type: 'success'
          })
          this.loading = false
        }).catch(err => {
          this.$notify({
            title: '提示',
            message: '导入观众失败'+err,
            type: 'error'
          })
          this.loading = false
        })
      } else {
        this.$notify({
          title: '出错了',
          message: '请选择文件与展会信息',
          type: 'warning'
        })
        this.loading = false
      }
    },
    getLabelName(key) {
      const name = {
        address: '地址',
        city: '城市',
        company: '公司名称',
        country: '国家',
        create_time: '创建时间',
        department: '部门',
        email: '邮箱',
        end_date: '结束时间',
        expo_name: '展会名称',
        expo_id: '展会ID',
        full_name: '姓名',
        first_name: '姓',
        last_name: '名',
        form_user_id: '表单用户ID',
        id: 'ID',
        id_number: '证件号码',
        id_type: '证件类型',
        industry: '行业',
        ip: 'IP',
        location: '位置',
        mobile: '手机号',
        mobile_country_code: '区号',
        organizer: '展商名称',
        position: '职位',
        province: '省/州',
        send_invitation_id: '发送邀请函ID',
        start_date: '开始时间',
        status: '状态',
        template_id: '表单模板ID',
        template_name: '表单模板名称',
        update_time: '更新时间',
        user_id: '用户ID'
      }
      if (name[key]) {
        return name[key]
      } else {
        return key
      }
    },
    getInvitationList() {
      getTemplateList(++this.invitation_data.page, 10).then(res => {
        this.invitation_data.data = res.data.data || []
        this.last_page = res.data.last_page
        this.page = res.data.current_page
      }).catch(err => {
        this.$notify({
          title: '提示',
          message: '获取邀请函列表失败'+err,
          type: 'error'
        })
      })
    },
    getExpoList() {
      getExpoList(1, 1000).then(res => {
        this.expoList = res.data.data
      }).catch(err => {
        this.$notify({
          title: '提示',
          message: '获取展会列表失败'+err,
          type: 'error'
        })
      })
    },
    search(event) {
      if (this.searchTimer) {
        clearTimeout(this.searchTimer)
      }
      this.searchTimer = setTimeout(() => {
        this.current_page = 1
        this.getAudience()
      }, 500)
    },
    getAudience() {
      if (this.loading) {
        return
      }
      this.loading = true
      getAudienceList(this.current_page, this.page_size, this.searchWord, this.is_export, this.expo_id).then(res => {
        this.current_page = res.data.current_page
        this.last_page = res.data.last_page
        this.total = res.data.total
        this.userList = res.data.data
        this.loading = false
      }).catch(err => {
        this.$notify({
          title: '提示',
          message: '获取观众列表失败'+err,
          type: 'error'
        })
        this.loading = false
      })
    },
    openDialog(row) {
      this.invitation_data.show = true
      this.invitation_data.userSetting = row
      getMyExpoInfo(row.expo_id).then(res => {
        this.invitation_data.exhibitorSetting = res.data
        this.changeTemp(0)
      }).catch(err => {
        this.$notify({
          title: '提示',
          message: '获取展会信息失败'+err,
          type: 'error'
        })
      })
    },
    changeTemp(index) {
      hugerte.init({
        selector: '#editor',
        skin_url: 'default',
        content_css: 'default',
        statusbar: false,
        toolbar: false,
        menubar: false,
        height: '100%',
        width: '100%',
        setup: editor => {
          editor.on('drop', event => {
            event.preventDefault()
            const html = event.dataTransfer.getData('text/html')
            editor.insertContent(html)
          })
        }
      }).then(editor => {
        this.invitation_data.tempIndex = index
        this.parseCode(this.invitation_data.data[index].content)
      })
    },
    dragStart(event, text) {
      console.log(text)
      const html = `<span>${text}</span>`
      event.dataTransfer.setData('text/html', html)
    },
    parseCode(code) {
      const tempDiv = document.createElement('div')
      tempDiv.innerHTML = code
      const variableSpans = tempDiv.querySelectorAll('span[data-v].hugerte-variable')
      variableSpans.forEach(span => {
        const key = span.getAttribute('data-v')
        if (key in this.invitation_data.exhibitorSetting) {
          span.textContent = this.invitation_data.exhibitorSetting[key]
        }
        if (key in this.invitation_data.userSetting) {
          span.textContent = this.invitation_data.userSetting[key]
        }
      })
      this.invitation_data.code = tempDiv.innerHTML
      hugerte.activeEditor.setContent(tempDiv.innerHTML)
    },
    closeDialog() {
      this.invitation_data.show = false
      hugerte.remove('#editor')
    },
    sendInvitation() {
      this.invitation_data.is_sending = true
      const content = hugerte.activeEditor.getContent()
      sentInvitation([this.invitation_data.userSetting.id], content).then(res => {
        this.closeDialog()
        this.$message.success('发送成功')
        this.invitation_data.is_sending = false
      }).catch(err => {
        this.$notify({
          title: '提示',
          message: '邀请函发送失败'+err,
          type: 'error'
        })
      })
    },
    copy(text) {
      navigator.clipboard.writeText(text).then(() => {
        this.$message.success('复制成功')
      }).catch(() => {
        this.$message.error('复制失败')
      })
    }
  }
})
</script>

<template>
  <div class="main-box">
    <div class="head">
      <el-input v-model="searchWord" v-permission="'audience.search'" prefix-icon="el-icon-search" placeholder="搜索观众姓名/手机号/邮箱" class="input" @input="search">
        <el-button v-if="searchWord" slot="append" icon="el-icon-delete" @click="searchWord='';search()" />
      </el-input>
      <el-select v-model="expo_id" v-permission="'audience.select'" class="select" placeholder="请选择参展名称" @change="search()">
        <el-option :value="0" label="全部展会" />
        <el-option v-for="item in expoList" :value="item.id" :label="item.expo_name" />
      </el-select>
      <el-button type="primary" icon="el-icon-download" @click="import_data.showImport = true">导入观众</el-button>
    </div>
    <div class="body">
      <el-table v-loading="loading" :data="userList" height="100%" class="table">
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form class="expand-form" :inline="true" label-position="left">
              <el-form-item v-for="(item,key) in props.row" :key="key" :label="getLabelName(key)+'：'">
                <span>{{ item }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column
          label="姓名"
          prop="full_name"
        />
        <el-table-column
          label="参展名称"
          prop="expo_name"
          width="400"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="props">
            <expo-popover placement="bottom" trigger="click" :expo-id="''+props.row.expo_id">
              <span style="cursor: pointer">{{ props.row.expo_name }}</span>
            </expo-popover>
          </template>
        </el-table-column>
        <el-table-column
          label="邮箱"
          prop="email"
        />
        <el-table-column
          label="区号"
          width="80"
          prop="mobile_country_code"
        />
        <el-table-column
          label="电话"
          prop="mobile"
        />
        <el-table-column
          label="操作"
          fixed="right"
        >
          <template slot-scope="scope">
            <span class="button" @click="openDialog(scope.row)">发送邀请函</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="foot">
      <el-pagination
        background
        :page-size="page_size"
        layout="total"
        :total="total"
      />
      <el-pagination
        v-permission="'audience.changePage'"
        background
        :page-size="page_size"
        layout="prev, pager, next"
        :total="total"
        @current-change="current_page=$event;getAudience()"
      />
    </div>
    <el-dialog
      :visible.sync="import_data.showImport"
      :append-to-body="true"
      title="导入观众"
      custom-class="import-dialog"
      @close="import_data.showImport=false"
    >
      <div class="dialog-body">
        <el-steps :active="import_data.step" align-center finish-status="success">
          <el-step title="下载模板" />
          <el-step title="填写数据" />
          <el-step title="导入数据" />
        </el-steps>
        <div v-if="import_data.step === 0" class="step-cont">
          <div class="info">选择需要导入的展会:</div>
          <el-select v-model="import_data.exhibitor_id" class="select" placeholder="请选择参展名称" @change="creatExcel(import_data.exhibitor_id)">
            <el-option :value="0" label="不选择展会" />
            <el-option v-for="item in expoList" :value="item.id" :label="item.expo_name" />
          </el-select>
          <div class="info">点击下载EXCEL模板:</div>
          <div>
            <el-button v-loading="loading" type="primary" @click="downloadTemplate()">下载模板</el-button>
            <span class="info">或</span>
            <el-button @click="import_data.step = 2">已有文件，直接导入</el-button>
          </div>
        </div>
        <div v-if="import_data.step === 1" class="step-cont">
          <img class="img" src="/static/image/import.webp">
          <div class="info">
            使用Excel拷贝数据到模板中或使用您的管理系统导入数据至模板中。不想繁琐操作？使用
            <router-link to="/exhibitor">展会管理</router-link>
            功能关联表单自动收集！
          </div>
          <el-button @click="import_data.step = 2">已完成，去导入</el-button>
        </div>
        <div v-if="import_data.step === 2" class="step-cont">
          <div class="info">选择需要导入的展会:</div>
          <el-select v-model="import_data.exhibitor_id" class="select" placeholder="请选择参展名称" @change="creatExcel(import_data.exhibitor_id)">
            <el-option :value="0" label="不选择展会" />
            <el-option v-for="item in expoList" :value="item.id" :label="item.expo_name" />
          </el-select>
          <div class="info">上传EXCEL文件:</div>
          <div class="upload">
            {{ import_data.file.name || '点击选择文件或者拖拽文件到这里' }}
            <input ref="file" accept=".xls,.xlsx" type="file" @change="uploadExcel"></input>
          </div>
          <div>
            <el-button v-permission="'audience.import'" v-loading="loading" type="primary" @click="importData">导入数据</el-button>
            <el-button @click="import_data.step = 0">下载其它展会模板</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      top="5vh"
      custom-class="invitation-dialog"
      :append-to-body="true"
      title="发送邀请函"
      :visible.sync="invitation_data.show"
      width="90%"
      @close="closeDialog()"
    >
      <div class="dialog-body">
        <div class="title">模板列表</div>
        <div class="title">邮件编辑器</div>
        <div class="title">观众信息(按住复制按钮可拖拽)</div>
        <div class="temp-list">
          <div
            v-for="(temp,index) in invitation_data.data"
            :key="temp.id"
            class="temp-item"
            :class="index===invitation_data.tempIndex?'active':''"
            @click="changeTemp(index)"
          >
            <img v-if="temp.pic" :src="ossUrl+temp.pic">
          </div>
          <div v-if="invitation_data.data.length===0" class="empty">
            没有模板,
            <router-link to="/invitation/add" @click.native="closeDialog()">去新建</router-link>
          </div>
        </div>
        <div class="view">
          <div id="editor" />
        </div>
        <div class="var-list-cont">
          <div class="var-list">
            <div v-for="(item,key) in invitation_data.userSetting" class="var-item">
              <div class="title">{{ getLabelName(key) }}</div>
              <div>{{ item || '暂无数据' }}</div>
              <el-button-group class="button-list">
                <el-button draggable="true" @dragstart.native="dragStart($event,item)" type="primary" size="mini" icon="el-icon-document-copy" @click="copy(item)"></el-button>
              </el-button-group>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog()">取 消</el-button>
        <el-button v-permission="'audience.sendInvite'" :disabled="invitation_data.is_sending" type="primary" @click="sendInvitation()">
          发 送
          <span v-if="invitation_data.is_sending" class="el-icon-loading" />
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
  @use '@/styles/variables.scss' as *;
  .main-box{
    height: 100%;
    display: grid;
    grid-template-rows: auto 1fr auto;
    grid-gap: 24px;
    .head{
      display: flex;
      .input{
        width: 30%;
        margin-right: 12px;
      }
      .select{
        width: 20%;
        margin-right: auto;
      }
    }
    .body{
      height: 100%;
      position: relative;
      .table{
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        .button{
          cursor: pointer;
          padding: 0 5px;
          color: $menuActiveText;
          &.del{
            color: #DC2626;
          }
        }
        .expand-form{
          display: grid;
          grid-template-columns: 1fr 1fr 1fr;
          .el-form-item{
            margin: 0;
          }
        }
      }
    }
    .foot{
      display: flex;
      justify-content: space-between;
    }
  }
</style>
<style lang="scss">
.import-dialog{
  .dialog-body{
    .step-cont{
      gap: 16px;
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 36px 0;
      .info{
        margin: 8px;
        color: grey;
      }
      .upload{
        display: flex;
        align-items: center;
        justify-content: center;
        color: grey;
        font-size: 24px;
        border-radius: 8px;
        width: 80%;
        height: 240px;
        border: 3px dashed grey;
        position: relative;
        input {
          opacity: 0;
          position: absolute;
          width: 100%;
          height: 100%;
        }
      }
      .img{
        width: 100%;
      }
    }
  }
}
.invitation-dialog{
  .dialog-body{
    overflow: hidden;
    height: 68vh;
    display: grid;
    grid-template-columns: 240px 1fr 240px;
    grid-template-rows: auto 1fr;
    grid-gap: 4px 12px;
    .view{
      width: 100%;
      height: 100%;
    }
    .var-list-cont{
      border: 2px solid #eee;
      border-radius: 10px;
      width: 100%;
      height: 100%;
      position: relative;
      .var-list{
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        overflow: hidden;
        overflow-y: auto;
        .var-item{
          position: relative;
          padding: 2px 6px;
          border-radius: 6px;
          border: 2px solid #409EFF00;
          border-bottom: 2px solid #00000008;
          .button-list{
            opacity: 0;
            position: absolute;
            right: 3px;
            top: 3px;
          }
          .title{
            font-weight: bold;
            font-size: 12px;
          }
          &:hover{
            border: 2px solid #409EFF;
            .button-list{
              opacity: 1;
            }
          }
        }
      }
    }
    .temp-list{
      border: 2px solid #eee;
      border-radius: 10px;
      padding: 6px;
      overflow: hidden;
      overflow-y: auto;
      width: 100%;
      height: 100%;
      .empty{
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .temp-item{
        margin-bottom: 12px;
        width: 100%;
        border-radius: 6px;
        overflow: hidden;
        cursor: pointer;
        &.active,&:hover{
          box-shadow: 0 0 0 2px #FFFFFF,0 0 0 4px #409EFF ;
        }
        img{
          width: 100%;
        }
      }
    }
  }
}
</style>
