<template>
  <div>
    <el-dialog
      title="流程套打配置"
      :visible.sync="dialogVisible"
      width="1206px"
      append-to-body
    >
      <span>
        <el-button
          type="primary"
          size="mini"
          @click="addTemplate"
          style="margin-bottom: 10px"
          ><i class="el-icon-plus"></i>新增</el-button
        >
        <ht-table
          :data="config"
          @load="handleLoad"
          noHeader
          nopagination
          :selectable="false"
        >
          <ht-table-column
            type="index"
            label="序号"
            width="60"
          ></ht-table-column>
          <ht-table-column prop="name" label="模板名称">
            <template slot-scope="scope">
              <el-link
                type="primary"
                @click="editTemplate(scope.row, scope.index)"
                title="编辑流程套打模板"
                >{{ scope.row.name }}</el-link
              >
            </template>
          </ht-table-column>
          <ht-table-column prop="printType" label="打印类型">
            <template slot-scope="scope">
              <el-tag type="success" v-if="scope.row.printType == 'word'"
                >word套打</el-tag
              >
              <el-tag type="warning" v-if="scope.row.printType == 'excel'"
                >excel套打</el-tag
              >
            </template>
          </ht-table-column>
          <ht-table-column label="允许预览">
            <template slot-scope="scope">
              <template v-if="scope.row.printType !== 'form'">
                <el-tag type="success" v-if="scope.row.allowPreview === true"
                  >是</el-tag
                >
                <el-tag type="info" v-if="scope.row.allowPreview === false"
                  >否</el-tag
                >
              </template>
              <template v-else>/</template>
            </template>
          </ht-table-column>
          <ht-table-column label="允许下载">
            <template slot-scope="scope">
              <template v-if="scope.row.printType !== 'form'"
                ><el-tag type="success" v-if="scope.row.allowDownload === true"
                  >是</el-tag
                >
                <el-tag type="info" v-if="scope.row.allowDownload === false"
                  >否</el-tag
                ></template
              >
              <template v-else>/</template>
            </template>
          </ht-table-column>
          <ht-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="text" @click="remove(scope.index)"
                >删除</el-button
              >
              <!-- <el-button
                type="text"
                @click="editTemplate(scope.row, scope.index)"
                >编辑</el-button
              > -->
            </template>
          </ht-table-column>
        </ht-table>
      </span>
      <span slot="footer">
        <el-button @click="dialogVisible = false" size="medium">取消</el-button>
        <el-button type="primary" @click="confirmTable" size="medium"
          >确定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      :title="title"
      :visible.sync="addDialogVisible"
      width="644px"
      append-to-body
    >
      <span>
        <el-form
          :model="addingTemplate"
          ref="form"
          label-width="120px"
          :inline="false"
          size="mini"
        >
          <el-form-item label="选择模板:">
            <el-select v-model="addingTemplate.templateId">
              <el-option
                v-for="item in options"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
          <template v-if="isFile">
            <el-form-item label="允许预览:" required>
              <el-radio v-model="addingTemplate.allowPreview" :label="true"
                >是</el-radio
              >
              <el-radio v-model="addingTemplate.allowPreview" :label="false"
                >否</el-radio
              >
            </el-form-item>
            <el-form-item label="允许下载:" required>
              <el-radio v-model="addingTemplate.allowDownload" :label="true"
                >是</el-radio
              >
              <el-radio v-model="addingTemplate.allowDownload" :label="false"
                >否</el-radio
              >
            </el-form-item>
          </template>
          <el-form-item label="模板描述:">
            <ht-input type="textarea" v-model="addingTemplate.desc"></ht-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer">
        <el-button @click="addDialogVisible = false" size="medium"
          >取消</el-button
        >
        <el-button type="primary" @click="addTemplateConfirm" size="medium"
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import form from '@/api/form.js'
import flow from '@/api/flow.js'
export default {
  name: 'print-template-setting',
  props: {
    defConfigData: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  computed: {
    isFile() {
      let templateId = this.addingTemplate.templateId
      if (!templateId) {
        return false
      }
      let template = this.options.filter(item => item.id === templateId)[0]
      if (!template) {
        return false
      }
      return template['printType'] != 'form'
    }
  },
  data() {
    return {
      dialogVisible: false,
      editingRow: null, //一个指针，指向正在编辑的节点数据
      config: [],
      addDialogVisible: false,
      addingTemplate: {
        templateName: '',
        desc: '',
        allowPreview: true,
        allowDownload: true,
        nodeId: ''
      },
      options: [],
      action: '',
      editingIndex: -1,
      title: ''
    }
  },
  methods: {
    showDialog(obj) {
      this.dialogVisible = true
      this.editingRow = obj
      this.config = obj.printTemplate
        ? // ? JSON.parse(obj.printTemplate.replace(/&quot;/g, '"'))
          JSON.parse(Base64.decode(obj.printTemplate))
        : []
    },
    handleLoad(param, cb) {
      cb && cb.call()
    },
    addTemplate() {
      this.title = '添加流程套打模板'
      this.addingTemplate = {
        templateName: '',
        desc: '',
        allowPreview: true,
        allowDownload: true,
        nodeId: ''
      }
      this.action = 'add'
      this.loadTemplateOptions()
    },
    loadTemplateOptions() {
      const {bpmDefSetting} = this.defConfigData.nodeSetData
      const {nodeId} = this.editingRow
      let formKey = ''
      if (
        bpmDefSetting.formMap[nodeId] &&
        bpmDefSetting.formMap[nodeId].formValue
      ) {
        formKey = bpmDefSetting.formMap[nodeId].formValue
      } else if (
        bpmDefSetting.globalForm &&
        bpmDefSetting.globalForm.formValue
      ) {
        formKey = bpmDefSetting.globalForm.formValue
      } else {
        this.$message.warning('请先绑定表单')
        return
      }
      // const {defId} = this.defConfigData.curEditNode
      const {defId} = this.defConfigData.initData.bpmDefLayout
      flow.getAllFormPrintTemplateByDefId(defId).then(resp => {
        this.options = resp.data || []
        //
        this.addDialogVisible = true
      })
      // form.getPrintListByFormKey(formKey).then(resp => {
      //   this.options = resp.data || []
      //   this.action = 'add'
      //   this.addDialogVisible = true
      // })
    },
    remove(index) {
      this.$confirm('是否确认删除？', '提示', {
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          type: 'warning',
          closeOnClickModal: false
        })
        .then(() => {
          this.config.splice(index, 1)
        })
      
    },
    addTemplateConfirm() {
      if (!this.addingTemplate.templateId) {
        this.$message.warning('请选择模板')
        return
      }
      const {addingTemplate} = this
      const template = this.options.filter(
        item => item.id == addingTemplate.templateId
      )[0]
      if (!template) {
        this.$message.warning('请选择模板')
        return
      } else {
        const {fileJson} = template
        if (!fileJson || fileJson == '[]') {
          this.$message.warning('模板文件不存在，请前往套打模板设置打印模板')
          return
        }
        const file = JSON.parse(fileJson)[0]
        addingTemplate.fileId = file.id
        const fileName = file.name
        addingTemplate.fileName = fileName || ''
        if (fileName && fileName.includes('.')) {
          let extName = fileName.substr(fileName.indexOf('.') + 1)
          if (['docx', 'doc'].includes(extName)) {
            addingTemplate.printType = 'word'
          } else if (['xlsx', 'xls'].includes(extName)) {
            addingTemplate.printType = 'excel'
          }
        }
      }
      const syncKeys = ['name']
      syncKeys.forEach(key => {
        addingTemplate[key] = template[key]
      })
      if (this.action === 'edit') {
        //this.config[this.editingIndex] = addingTemplate
        this.$set(this.config, this.editingIndex, addingTemplate)
      } else {
        this.config.push(this.addingTemplate)
      }

      this.addDialogVisible = false
    },
    editTemplate(row, index) {
      this.title = '编辑流程套打模板'
      this.addingTemplate = {...row}
      this.action = 'edit'
      this.editingIndex = index
      this.addDialogVisible = true
      if (!this.options.length) {
        this.loadTemplateOptions()
      }
    },
    confirmTable() {
      // this.$set(this.editingRow, 'printTemplate', JSON.stringify(this.config))
      // //this.editingRow.printTemplate = JSON.stringify(this.config)
      this.$emit('confirm', Base64.encode(JSON.stringify(this.config)))
      this.dialogVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.el-button {
  i {
    margin-right: 5px;
  }
}
</style>
