<template>
  <el-dialog title="批量生成" width="80%" :visible.sync="editor.showBatch" custom-class="batch-dialog" @open="openDialog">
    <div class="batch-container">

      <div class="batch-preview">
        <img :src="poster.preview" />
        <fp-empty :data="poster.preview" size="60" />
      </div>

      <div class="batch-form">

        <el-form :inline="true" ref="form" :model="form" label-width="100px">

          <div>
            <el-form-item label="海报">
              <el-select v-model="form.posterId" placeholder="请选择海报" @change="changeHandler" style="width: 200px;">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="类型">
              <el-radio-group v-model="form.type">
                <el-radio value="jpeg" label="jpeg"></el-radio>
                <el-radio value="png" label="png"></el-radio>
                <el-radio value="pdf" label="pdf"></el-radio>
              </el-radio-group>
            </el-form-item>
          </div>

          <el-form-item label="数据">
            <div style="display: flex; justify-content: left; align-items: flex-start; width: 200px;">
              <fp-button v-if="showDownTemplate" @click="downTemplateHandler">1.下载模板</fp-button>
              <fp-button style="color: #d84689" disabled v-else>{{ temlateTipText }}</fp-button>
              <fp-file-upload v-show="showDownTemplate" buttonText="2.导入数据" style="margin-left: 12px;"
                accept=".xls,.xlsx,.csv" :auto-upload="false" @change="importHandler" />
            </div>
          </el-form-item>

          <el-form-item label="数量">
            <el-input-number style="width: 100px;" size="small" v-model="form.num" controls-position="right" :min="0"
              :max="raw.length" />
          </el-form-item>

          <el-form-item>
            <el-button :loading="fullscreenLoading" type="primary" @click="onSubmit">
              生成
            </el-button>
          </el-form-item>
        </el-form>


        <div style="height: 46.8vh">

          <el-table :data="raw" height="100%" stripe border style="width: 100%">
            <el-table-column v-for="t in table" :key="t.key" :prop="t.prop" :label="t.label">
            </el-table-column>
          </el-table>

        </div>
      </div>

    </div>

  </el-dialog>
</template>

<script>
import { isEmpty } from 'lodash'
import { mapActions, mapState } from "vuex"
import * as XLSX from 'xlsx'
import FpButton from "../common/FpButton"
import FpEmpty from "../common/FpEmpty"
import FpFileUpload from "../common/FpFileUpload"


export default {
  name: "FpPatch",
  components: {
    FpEmpty,
    FpButton,
    FpFileUpload
  },
  data() {
    return {
      poster: {},
      row: [],
      table: [],
      raw: [],
      fullscreenLoading: false,
      form: {
        'id': '',
        'name': '',
        'type': 'jpeg',
        'posterId': '',
        'num': 0,
        'doneNum': 0,
        'path': '',
        'status': 0
      }
    }
  },
  computed: {
    ...mapState({
      'editor': state => state.editor,
      'panelposter': state => state.panelposter,
      'p': state => state.poster.p
    }),
    options() {
      return this.panelposter.items.map(a => {
        return { 'value': a.id, 'label': a.name }
      })
    },
    showDownTemplate() {
      return !isEmpty(this.row)
    },
    temlateTipText() {
      return '无法生成模板' + (!this.poster.id ? '，请先选择海报' : '，请先设置海报参数')
    }
  },
  methods: {
    ...mapActions({
      'getPoster': 'poster/getPoster',
      'saveOrUpdate': 'batch/saveOrUpdate',
      'loadBatch': 'batch/loadBatch',
      'getItems': 'batch/getItems',
    }),
    openDialog() {
      this.getBatch(this.editor.batchId)
    },
    getBatch(v) {
      this.fullscreenLoading = false
      this.raw = []
      if (v === 0) {
        // 重置数据
        this.row = {}
        this.poster = {}
        this.table = []
        this.form = {
          'id': '',
          'name': '',
          'type': 'jpeg',
          'posterId': '',
          'num': 0,
          'doneNum': 0,
          'path': '',
          'status': 0
        }
      }
      if (v) {
        // 加载批量
        this.loadBatch(v).then(r => {

          let raw = r.raw
          delete r['raw']
          this.form = {
            ...this.form,
            ...r
          }

          this.getPoster(r.posterId).then(r0 => {
            this.loadPoster(r0)
            this.raw = JSON.parse(raw)
            this.form.num = this.raw.length
          })
        })
      }else{
        //默认加载当前的海报
        this.p.id&&this.changeHandler(this.p.id)
      }
    },
    loadPoster(r) {
      this.poster = this.panelposter.items.filter(a => a.id === r.id)[0]
      let row = {}
      let table = []
      r.items.forEach(a => {
        if (a.vd) {
          row[a.vd] = a.v
          table.push({
            key: a.uuid,
            prop: a.vd,
            label: a.vd
          })
        }
      })
      this.row = row
      this.table = table
      // this.raw = [];  // 切换海报，不重置数据
      this.form.name = this.poster.name
      this.form.posterId = this.poster.id
    },
    changeHandler(id) {
      this.getPoster(id).then(r => this.loadPoster(r))
    },
    onSubmit() {
      if (!this.form.posterId) {
        this.$message.warning('请先选择海报')
        return
      }
      if (isEmpty(this.raw)) {
        this.$message.warning('请先导入数据')
        return
      }
      // 处理批量数据
      let params = {
        ...this.form,
        raw: JSON.stringify(this.raw),
      }
      this.fullscreenLoading = true
      this.saveOrUpdate(params).then(r => {
        this.form = {
          ...this.form,
          ...r
        }
        this.fullscreenLoading = false
        this.$message.success('处理成功，请稍后')
        this.editor.showBatch = false
        this.editor.batchPosterId = 0
        this.getItems().then(r => console.info("重新加载"))
      })
    },
    // 下载模板
    downTemplateHandler() {
      let raw = [this.row]
      const worksheet = XLSX.utils.json_to_sheet(raw)
      const workbook = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(workbook, worksheet, "sheet")
      XLSX.writeFile(workbook, `${this.poster.name}-模板.xlsx`)
    },

    // 导入模板
    async importHandler(ev) {
      let file = ev.raw
      const data = await file.arrayBuffer()
      const workbook = XLSX.read(data)
      let worksheet = workbook.Sheets[workbook.SheetNames[0]]
      this.raw = XLSX.utils.sheet_to_json(worksheet)
      this.form.num = this.raw.length
    }
  }
}
</script>

<style scoped>
.batch-container {
  display: flex;
  height: 58vh;
}

.batch-form {
  width: 67%;
  min-width: 660px;
  padding-left: 4px;
}

.batch-preview {
  width: 33%;
  text-align: center;
  background-color: #eef2f8;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.batch-preview img {
  max-width: 22vw;
  max-height: 50vh;
  box-shadow: 1px 1px 15px #9da3ac88;
}
</style>


<style>
.batch-dialog {
  min-width: 900px;
  height: 74vh;
  overflow: hidden;
}

.batch-dialog .el-tag {
  user-select: none;
  cursor: pointer;
}
</style>
