<template>
  <div class="preview-content right-preview">
    <el-form ref="addOrUpdateForm" :model="addOrUpdateForm" :rules="rules" :validate-on-rule-change="false" label-width="125px">
      <el-row :gutter="4" style="padding:0 20px">
        <draggable v-bind="{draggable:'.drag-item',animation:500}" :disabled="!isDraggable" @update="datadragEnd">
          <el-col v-for="(item,index) in formPreviewData" v-show="item.fieldName !== 'barcode' && item.fieldName !== 'is_entity'" :key="index" :class="['drag-item',item.fieldName === 'barcode'? 'barcode-input':'']" :span="item.isLine || item.fieldName === 'barcode' ? 24 : 12">
            <el-form-item :label="item.fieldCnName" :prop="item.fieldName">
              <!-- select  :load-options="loadOptions"-->
              <treeselect
                v-if="item.isInputClass === 'select'"
                v-model="addOrUpdateForm[item.fieldName]"
                :options="item.options"
                :normalizer=" isTableType === 1 ? normalizerFonds : (isTableType === 2 ? normalizerClassify : normalizer)"
                :clearable="false"
                placeholder=""
                flat
                :style="{ width: item.editLength+'px'}"
                :disabled="isDisabled"
                :validate-event="!isDisabled"
                no-options-text="无数据"
                @select="selectTree"
                @open="openTree(item)"
              >
                <div slot="value-label" slot-scope="{ node }">{{ getAutoNameUnknown(node.label) }}</div>
              </treeselect>
              <!-- text / number / textarea / popover -->
              <!-- :validate-event="isDisabled" -->
              <el-input
                v-if="item.isInputClass !== 'select' && item.isInputClass !== 'date' && item.fieldName !== 'barcode' "
                v-model="addOrUpdateForm[item.fieldName]"
                :type="item.isInputClass === 'popover'? 'text' : item.isInputClass"
                :rows="item.isInputClass === 'textarea' ? 3 : ''"
                :class="{'input-popover':(item.isInputClass === 'popover')}"
                :style="{ width: item.editLength+'px'}"
                :disabled="isDisabled || (item.fieldName === 'archival_category_code')"
                :validate-event="!isDisabled"
                @keyup.enter.native="isRepeatHandle(item)"
                @input="autoAddZero(item.isFilling, item.fieldName, addOrUpdateForm[item.fieldName], item.fillingDigit)"
                @blur="isRepeatHandle(item)"
              >
                <i v-if="item.isInputClass === 'popover'" slot="suffix" class="el-input__icon iconfont icon-gengduo1" @click="handleCurrentFieldName(item)" />
              </el-input>
              <!-- date -->
              <el-date-picker v-if="item.isInputClass === 'date'" v-model="addOrUpdateForm[item.fieldName]" type="date" align="right" format="yyyy-MM-dd" placeholder="" :clearable="false" :style="{ width: item.editLength+'px'}" :disabled="isDisabled" :validate-event="!isDisabled" />
            </el-form-item>
          </el-col>
        </draggable>
      </el-row>
      <el-row v-if="!isHasCode && isDesFormType !== 'prearchiveLibrary' && isDesFormType !== 'mergeFile'" class="preview-form-bottom">
        <el-col v-for="(item,index) in formPreviewData.slice(formPreviewData.length-1,formPreviewData.length)" :key="'barcode'+index">
          <el-form-item :label="item.fieldCnName" :prop="item.fieldName">
            <el-input v-model="addOrUpdateForm[item.fieldName]" type="text" style="width: 510px" :disabled="isDisabled" :validate-event="!isDisabled" @keyup.enter.native="isRepeatHandle(item)" @blur="isRepeatHandle(item)" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="isDesFormType === 'prearchiveLibrary'" class="preview-form-bottom prearch-bottom">
        <el-col>
          <el-form-item label="电子原件" prop="fileOriginal" class="prearch-upload" :rules="[{ required: true, message: '请上传原文',trigger: 'blur' }]">
            <el-input
              v-model="addOrUpdateForm['fileOriginal']"
              type="text"
              style="width: 446px"
              readonly
            />
            <div class="upload-btn">
              <input id="upFile" type="file" name="upFile" @change="changeFile($event)">
              <el-button size="small" type="primary"><i class="iconfont icon-shangchuan" />上传</el-button>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="isDesFormType !== 'prearchiveLibrary' && isDesFormType !== 'mergeFile'" class="preview-form-bottom  prearch-bottom">
        <el-col v-for="(item,index) in formPreviewData" :key="index">
          <el-form-item v-if="item.fieldName === 'is_entity'" label="有无实体" :prop="item.fieldName" :rules="[{ required: true, message: '请选择',trigger: 'change' }]" class="pbysical-style">
            <el-radio-group v-model="addOrUpdateForm[item.fieldName]">
              <el-radio :label="1">有</el-radio>
              <el-radio :label="0">无</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 弹框形式的内容展示 -->
    <el-dialog class="edit-form-dialog" :append-to-body="true" :visible="popoverVisible" :before-close="handleClose" :close-on-click-modal="false" :title="tableTitle">
      <span class="dialog-right-top" />
      <span class="dialog-left-bottom" />
      <div class="setting-dialog">
        <el-table ref="popoverTable" :data="popoverTableData" highlight-current-row row-key="dictionaryCode" :tree-props="{children: 'childDictionarys', hasChildren: 'hasChildren'}" height="600" style="width: 100%;" @selection-change="handleSelectionChange" @row-click="clickRowHandler">
          <el-table-column :selectable="checkboxT" type="selection" width="55" />
          <el-table-column prop="dictionaryName" label="字典名称" show-overflow-tooltip />
          <el-table-column prop="dictionaryCode" label="字典代码" />
          <el-table-column prop="dictionaryRemarks" label="内容说明" show-overflow-tooltip />
        </el-table>
      </div>
    </el-dialog>
    <el-dialog class="edit-form-dialog" :append-to-body="true" :visible="popoverFondsVisible" :before-close="handleClose" :close-on-click-modal="false" :title="tableTitle">
      <span class="dialog-right-top" />
      <span class="dialog-left-bottom" />
      <div class="setting-dialog">
        <el-table ref="popoverTable" :data="popoverTableDataFonds" highlight-current-row row-key="id" :tree-props="{children: 'childMenus', hasChildren: 'hasChildren'}" height="600" style="width: 100%; he" @selection-change="handleSelectionChange" @row-click="clickRowHandler">
          <el-table-column type="selection" width="55" show-overflow-tooltip />
          <el-table-column prop="fondsNo" label="全宗号" />
          <el-table-column prop="fondsName" label="全宗名称" show-overflow-tooltip />
          <el-table-column prop="fondsOrders" label="排序" width="60" />
        </el-table>
      </div>
    </el-dialog>
    <el-dialog class="edit-form-dialog" :append-to-body="true" :visible="popoverClassifyVisible" :before-close="handleClose" :close-on-click-modal="false" :title="tableTitle">
      <span class="dialog-right-top" />
      <span class="dialog-left-bottom" />
      <div class="setting-dialog">
        <el-table ref="popoverTable" :data="popoverTableDataClassify" highlight-current-row row-key="id" :tree-props="{children: 'childArchivesClass', hasChildren: 'hasChildren'}" height="600" style="width: 100%;" @selection-change="handleSelectionChange" @row-click="clickRowHandler">
          <el-table-column type="selection" width="55" />
          <el-table-column label="分类名称" prop="name" width="130" show-overflow-tooltip />
          <el-table-column label="分类编号" prop="code" />
          <el-table-column label="排序" prop="classSeq" />
          <el-table-column label="所属门类" prop="categoryName" show-overflow-tooltip />
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { crud } from '@crud/crud'
import { FetchDoeditIsRepeat } from '@/api/archivesManage/archivesList'
import { collectAdd, collectEdit } from '@/api/collect/collect'
import { prearchEdit, FetchMergeToFile, FetchReDoeditIsRepeat } from '@/api/prearchiveLibrary/prearchiveLibrary'
import { getNoFormatField } from '@/api/system/category/fileNoFormat'
import draggable from 'vuedraggable'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { FetchSonDictionaryList, FetchDictionaryTree } from '@/api/system/dict'
import { FetchFondsAll } from '@/api/system/fonds'
import { FetchArchivesClassTree, FetchSonArchivesClass } from '@/api/system/archivesClass'
import { parseTime, getCurrentTime } from '@/utils/index'
import { reDocumentUpload } from '@/utils/upload'
import { mapGetters } from 'vuex'

export default {
  name: 'PreviewForm',
  components: { draggable, Treeselect },
  mixins: [crud()],
  inject: ['parentsData'],
  props: {
    isDisabled: {
      type: Boolean,
      required: true
    },
    formPreviewData: {
      type: Array,
      required: true
    },
    selectedCategory: {
      type: Object,
      default: function() {
        return {}
      }
    },
    selectedDocument: {
      type: Object,
      default: function() {
        return {}
      }
    },
    arcId: {
      type: String,
      default: ''
    },
    isHasCode: {
      type: Boolean,
      required: true
    },
    isDraggable: {
      type: Boolean,
      default: false
    },
    isDesFormType: {
      type: String,
      default: ''
    },
    collectLevel: {
      type: Number,
      default: 1
    },
    isTitleType: {
      type: Number,
      default: 2
    }
  },

  data() {
    return {
      fileOriginal: null,
      addOrUpdateForm: {
      },
      rules: {
      },
      isTableType: 1,
      tableTitle: '字典列表',
      popoverTableData: [], // popover - popoverTableData
      popoverVisible: false, // popover - visible
      popoverTableDataClassify: [],
      popoverClassifyVisible: false,
      popoverTableDataFonds: [],
      popoverFondsVisible: false,
      currentFieldName: null, // popover 当前fieldName
      treeCurrentFiled: null,
      categoryId: null,
      result: null,
      autoMatic: null,
      file: null, // 附件 change
      fileNames: '', // 附件 - name
      formatType: '', // 附件 - type
      postfix: '', // 附件 - 文件后缀
      fileSize: '', // 附件 - 大小
      filePath: '', // 附件 - path
      px: '', // 附件 - 分辨率
      nowDate: '', // 当前时间
      fileJsonString: null,
      mergeFileArcIds: null,
      mergeFileCategory: null,
      archivesType: null,
      activeIndex: null
    }
  },
  computed: {
    ...mapGetters([
      'baseApi',
      'user'
    ])
  },
  watch: {
    selectedCategory: function(newValue, oldValue) {
    },
    selectedDocument: function(newValue, oldValue) {
    },
    arcId: function(newValue, oldValue) {
    },
    isDesFormType: function(newValue, oldValue) {
    },
    formPreviewData: function() {
      this.editFormRow()
      // 区分 门类著录项 和 档案管理
      if (this.isDesFormType === 'category') {
        this.FetchNoFormatField(this.selectedCategory.id)
      }
    }
  },
  created() {
    this.editFormRow()
  },
  mounted() {
  },
  methods: {
    checkboxT(row, rowIndex) {
      return row.level ? row.level === 3 : true
    },
    normalizer(node) {
      if ((node.childDictionarys && !node.childDictionarys.length) || node.childDictionarys === null) {
        delete node.childDictionarys
      }
      return {
        id: node.dictionaryName,
        label: node.dictionaryName,
        children: node.childDictionarys,
        isDisabled: node.level && node.level !== 3
      }
    },
    normalizerClassify(node) {
      if ((node.childArchivesClass && !node.childArchivesClass.length) || node.childArchivesClass === null) {
        delete node.childArchivesClass
      }
      return {
        id: node.code,
        label: node.name,
        children: node.childArchivesClass
      }
    },
    normalizerFonds(node) {
      if (node.childMenus == null || node.childMenus === 'null') {
        delete node.childMenus
      }
      return {
        id: node.fondsNo,
        label: node.fondsName,
        children: node.childMenus
      }
    },
    // 处理vue-treeSelect回显出现unknown问题
    getAutoNameUnknown(name) {
      if (name.lastIndexOf('unknown') > -1) {
        // 当treeselect翻译不了值时，name中有id，截取id，去调接口或者字典查询出名字
        return name.split('(')[0]
      } else {
        return name
      }
    },
    getNode(list, dictionaryName) {
      let data;
      (list || []).map(item => {
        if (item.dictionaryName === dictionaryName) {
          data = [item]
        } else {
          const child = this.getNode(item.childMenus, dictionaryName)
          if (child) {
            data = child
          }
        }
      })
      return data
    },
    getFondsNode(list, fondsNo) {
      let data;
      (list || []).map(item => {
        if (item.fondsNo === fondsNo) {
          data = [item]
        } else {
          const child = this.getFondsNode(item.childMenus, fondsNo)
          if (child) {
            data = child
          }
        }
      })
      return data
    },
    getClassfiyNode(list, code) {
      let data;
      (list || []).map(item => {
        if (item.code === code) {
          data = [item]
        } else {
          const child = this.getClassfiyNode(item.childArchivesClass, code)
          if (child) {
            data = child
          }
        }
      })
      return data
    },
    // 自动生成
    handleAuto() {
      let string = ''
      const getAutoFiledVal = []
      this.autoMatic.forEach(async val => {
        if (!this.addOrUpdateForm[val.fieldName]) {
          string += ''
        } else {
          const fieldInfo = this.formPreviewData.find(element => element.fieldName === val.fieldName)
          if (fieldInfo.isInputClass === 'select' || fieldInfo.isInputClass === 'popover') {
            if (fieldInfo.mateData === 3) {
              await FetchSonDictionaryList({ 'pid': fieldInfo.dictionaryId.id }).then(res => {
                const option = this.getNode(res, this.addOrUpdateForm[val.fieldName])
                if (option) {
                  const obj = {}
                  obj.name = val.fieldName
                  obj.val = option[0].dictionaryCode + val.connector
                  obj.sequence = val.sequence
                  getAutoFiledVal.push(obj)
                }
              })
            }
            if (fieldInfo.mateData === 1) {
              await FetchFondsAll().then(res => {
                const option = this.getFondsNode(res, this.addOrUpdateForm[val.fieldName])
                if (option) {
                  const obj = {}
                  obj.name = val.fieldName
                  obj.val = option[0].fondsNo + val.connector
                  obj.sequence = val.sequence
                  getAutoFiledVal.push(obj)
                }
              })
            }
            if (fieldInfo.mateData === 2) {
              let categoryId
              if (this.isDesFormType !== 'mergeFile' && this.isDesFormType !== 'arcives' && this.isDesFormType !== 'manageArcives') {
                categoryId = this.selectedCategory.pid
              } else {
                categoryId = this.selectedCategory.id
              }
              await FetchArchivesClassTree({ 'categoryId': categoryId }).then(res => {
                const option = this.getClassfiyNode(res, this.addOrUpdateForm[val.fieldName])
                if (option) {
                  const obj = {}
                  obj.name = val.name
                  obj.val = option[0].code + val.connector
                  obj.sequence = val.sequence
                  getAutoFiledVal.push(obj)
                }
              })
            }
          } else {
            const obj = {}
            obj.name = val.fieldName
            obj.val = this.addOrUpdateForm[val.fieldName] + val.connector
            obj.sequence = val.sequence
            getAutoFiledVal.push(obj)
          }
        }
        getAutoFiledVal.sort(this.compare('sequence'))
        string = getAutoFiledVal.map((item) => item.val).join('')
        this.formPreviewData.map(item => {
          if (item.isAutomatic) {
            this.$set(this.addOrUpdateForm, item.fieldName, string)
          }
        })
      })
    },
    // 排序
    compare(property) {
      return function(a, b) {
        var value1 = a[property]
        var value2 = b[property]
        return value1 - value2
      }
    },
    // 获取档号组成项
    FetchNoFormatField(categoryId) {
      getNoFormatField({ categoryId: categoryId, categoryLevel: this.collectLevel }).then(res => {
        this.autoMatic = res
        this.handleAuto()
      })
    },
    // 获取对应字典子集数据
    getAllSubset(item) {
      if (item.mateData === 1) {
        this.getFondsDatas(item)
      } else if (item.mateData === 2) {
        if (item.categoryId) {
          this.getClassifyTree(item)
        }
      } else {
        if (item.dictionaryId) {
          const params = {
            'pid': item.dictionaryId.id
          }
          this.isTableType = 3
          this.tableTitle = '字典列表'
          if (this.selectedCategory.arrangeType === 3 && this.collectLevel === 2 && item.dictionaryId.dictionaryCode === 'project_class') {
            this.getDictsList(item)
          } else {
            FetchSonDictionaryList(params).then(res => {
              if (item.isInputClass === 'select') {
                this.$set(item, 'options', res)
              } else if (item.isInputClass === 'popover') {
                this.popoverTableData = res
                this.popoverVisible = true
              }
            })
          }
        }
      }
    },
    getFondsDatas(item) {
      const parent = {}
      parent.id = 0
      parent.fondsName = '全宗选择'
      this.isTableType = 1
      this.tableTitle = '全宗列表'
      FetchFondsAll().then(res => {
        if (item.isInputClass === 'select') {
          this.$set(item, 'options', res)
        } else if (item.isInputClass === 'popover') {
          this.popoverTableDataFonds = res
          this.popoverFondsVisible = true
        }
      })
    },
    getClassifyTree(item) {
      this.isTableType = 2
      this.tableTitle = '分类列表'
      let categoryId
      if (this.isDesFormType !== 'mergeFile' && this.isDesFormType !== 'arcives' && this.isDesFormType !== 'manageArcives') {
        categoryId = this.selectedCategory.pid
      } else {
        categoryId = this.selectedCategory.id
      }
      FetchArchivesClassTree({ 'categoryId': categoryId }).then(res => {
        if (item.isInputClass === 'select') {
          const classifyOptions = res.map(function(obj) {
            if (obj.childArchivesClass !== null) {
              obj.hasChildren = true
            } else {
              obj.hasChildren = false
            }
            if (obj.hasChildren) {
              obj.children = null
            }
            return obj
          })
          this.$set(item, 'options', classifyOptions)
        } else if (item.isInputClass === 'popover') {
          this.popoverTableDataClassify = res
          this.popoverClassifyVisible = true
        }
      })
    },
    getSonClass(tree, treeNode, resolve) {
      setTimeout(() => {
        FetchSonArchivesClass({ pid: tree.id }).then(res => {
          const data = res.map(function(obj) {
            if (obj.sonNum !== 0 && obj.sonNum) {
              obj.hasChildren = true
              obj.children = null
            } else {
              obj.hasChildren = false
            }
            return obj
          })
          resolve(data)
        })
      }, 100)
    },
    // 判断重复api
    handlerIsRepeat(params, item) {
      if (this.isDesFormType !== 'prearchiveLibrary') {
        FetchDoeditIsRepeat(params).then(res => {
          if (res) {
            this.$message.error(item.fieldCnName + '不可重复')
          }
        })
      } else {
        FetchReDoeditIsRepeat(params).then(res => {
          if (res) {
            this.$message.error(item.fieldCnName + '不可重复')
          }
        })
      }
    },
    // input 判断是否重复
    isRepeatHandle(item) {
      // 自动重复字段 - 是否重复
      if (item.isRepeat) {
        let params
        if (this.isDesFormType !== 'prearchiveLibrary' && this.isDesFormType !== 'mergeFile') {
          params = {
            'categoryId': this.selectedCategory.id,
            'archivesId': this.arcId,
            'fieldName': item.fieldName,
            'value': this.addOrUpdateForm[item.fieldName]
          }
        } else {
          params = {
            'documentId': this.selectedCategory.id,
            'archivesId': null,
            'fieldName': item.fieldName,
            'value': this.addOrUpdateForm[item.fieldName]
          }
        }
        this.handlerIsRepeat(params, item)
      }

      if (this.isDesFormType !== 'prearchiveLibrary' && this.isDesFormType !== 'mergeFile') {
        if (!item.isAutomatic) {
          const index = this.autoMatic.findIndex(i => item.fieldName === i.fieldName)
          if (index !== -1) {
            this.handleAuto()
          }
        }
      }
    },
    // tree - open
    openTree(item) {
      this.treeCurrentFiled = item
      this.$set(item, 'options', [])
      this.getAllSubset(this.treeCurrentFiled)
    },
    // tree - select
    selectTree(val) {
      if (val.fondsNo) {
        this.addOrUpdateForm[this.treeCurrentFiled.fieldName] = val.fondsName
      } else if (val.code) {
        this.addOrUpdateForm[this.treeCurrentFiled.fieldName] = val.name
      } else {
        this.addOrUpdateForm[this.treeCurrentFiled.fieldName] = val.dictionaryName
      }
      // 自动重复字段 - 是否重复 - treeSelect方式
      if (this.treeCurrentFiled.isRepeat) {
        let params
        if (this.isDesFormType !== 'prearchiveLibrary' && this.isDesFormType !== 'mergeFile') {
          params = {
            'categoryId': this.selectedCategory.id,
            'archivesId': this.arcId,
            'fieldName': this.treeCurrentFiled.fieldName,
            'value': val.dictionaryName
          }
        } else {
          params = {
            'documentId': this.selectedCategory.id,
            'archivesId': null,
            'fieldName': this.treeCurrentFiled.fieldName,
            'value': val.dictionaryName
          }
        }
        this.handlerIsRepeat(params, this.treeCurrentFiled)
      }
      if (this.isDesFormType !== 'prearchiveLibrary' && this.isDesFormType !== 'mergeFile') {
        if (this.autoMatic) {
          const index = this.autoMatic.findIndex(i => this.treeCurrentFiled.fieldName === i.fieldName)
          if (index !== -1) {
            this.handleAuto()
          }
        }
      }
    },
    // popover - table 单选
    clickRowHandler(row) {
      this.$refs.popoverTable.clearSelection()
      if (!row.level || row.level === 3) {
        this.$refs.popoverTable.toggleRowSelection(row)
      } else {
        return false
      }
    },
    // popover - table 选中得项
    handleSelectionChange(val) {
      if (val.length > 0) {
        if (this.isTableType === 1) {
          this.addOrUpdateForm[this.currentFieldName] = val[0].fondsNo
        } else if (this.isTableType === 2 && this.isDesFormType !== 'prearchiveLibrary') {
          this.addOrUpdateForm[this.currentFieldName] = val[0].code
        } else {
          this.addOrUpdateForm[this.currentFieldName] = val[0].dictionaryName
        }
      }
      this.$refs.popoverTable.clearSelection()
      this.popoverVisible = false
      this.popoverClassifyVisible = false
      this.popoverFondsVisible = false

      if (this.isDesFormType !== 'prearchiveLibrary' && this.isDesFormType !== 'mergeFile') {
        if (this.autoMatic) {
          const index = this.autoMatic.findIndex(i => this.currentFieldName === i.fieldName)
          if (index !== -1) {
            this.handleAuto()
          }
        }
      }
    },
    // popover - 当前选中得
    handleCurrentFieldName(item) {
      this.currentFieldName = item.fieldName
      this.getAllSubset(item)
    },
    // 预览和输入时，自动补零
    autoAddZero(isFilling, fieldName, value, fillingDigit) {
      if (isFilling) {
        this.addOrUpdateForm[fieldName] = value.toString().padStart(fillingDigit, '0').slice(-1 * fillingDigit)
      }
    },
    // 寻找pid档案门类代码
    findNodeById(node, targetId) {
      if (node.id === targetId) {
        return node
      }
      if (node.children && node.children.length > 0) {
        for (const child of node.children) {
          const result = this.findNodeById(child, targetId)
          if (result) {
            return result
          }
        }
      }
      return null
    },
    // 动态生成表单
    editFormRow() {
      this.rules = {}
      this.formPreviewData.map(item => {
        if (item.isInputClass === 'select') {
          this.$set(item, 'options', [])
          this.$set(this.addOrUpdateForm, item.fieldName, null) // 防止unkonwn
        }
        if (item.isDefaultValue !== '') {
          this.$set(this.addOrUpdateForm, item.fieldName, item.isDefaultValue)
        } else {
          this.$set(this.addOrUpdateForm, item.fieldName, '')
          if (item.isInputClass === 'select') {
            this.$set(this.addOrUpdateForm, item.fieldName, null) // 防止unkonwn
          }
        }
        if (item.fieldName === 'archival_category_code') {
          let targetNode
          if (this.isDesFormType !== 'mergeFile' && this.isDesFormType !== 'arcives' && this.isDesFormType !== 'manageArcives') {
            const targetId = this.selectedCategory.pid
            targetNode = this.findNodeById(this.crud.data[0], targetId)
          } else {
            targetNode = this.selectedCategory
          }

          if (targetNode) {
            this.$set(this.addOrUpdateForm, item.fieldName, targetNode.code)
          } else {
            this.$set(this.addOrUpdateForm, item.fieldName, '')
          }
        }

        if (item.fieldName === 'is_entity') {
          this.$set(this.addOrUpdateForm, item.fieldName, 1)
        }

        this.$set(this.rules, item.fieldName, [
          {
            required: !!item.isRequired,
            message: (item.isInputClass === 'text' ? '请输入' : '请选择') + item.fieldCnName,
            trigger: item.isInputClass === 'text' ? 'blur' : 'change'
          }
        ])
      })
    },
    // 预览界面排序
    datadragEnd(event) {
      // 调换顺序
      const oldIndex = event.oldIndex // 移动初始位置
      const newIndex = event.newIndex // 运动终止位置
      const diff = Math.abs(newIndex - oldIndex) // 插值绝对值
      const index = this.formPreviewData[oldIndex]
      if (oldIndex > newIndex) {
        for (let i = 0; i < diff; i++) {
          this.formPreviewData[oldIndex - i] = this.formPreviewData[oldIndex - i - 1]
        }
        this.formPreviewData[newIndex] = index
      } else {
        for (let i = 0; i < diff; i++) {
          this.formPreviewData[oldIndex + i] = this.formPreviewData[oldIndex + i + 1]
        }
        this.formPreviewData[newIndex] = index
      }
    },
    submitForm(formName, categoryId, quickPaperArcId) {
      // 时间格式化
      this.formPreviewData.map(item => {
        if (item.isInputClass === 'date') {
          if (this.addOrUpdateForm[item.fieldName] !== '') {
            this.$set(this.addOrUpdateForm, item.fieldName, parseTime(this.addOrUpdateForm[item.fieldName]).split(' ')[0])
          }
        }
      })
      if (this.archivesType === 'add') {
        this.addOrUpdateForm.fonds_affiliation = this.user.fonds.id
      }
      console.log(this.addOrUpdateForm)
      delete this.addOrUpdateForm.id
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 预归档库
          if (this.isDesFormType === 'prearchiveLibrary') {
            delete this.addOrUpdateForm.fileOriginal
            const params = {
              'id': this.arcId,
              'ids': null,
              'documentId': categoryId,
              'delMan': null,
              'jsonString': JSON.stringify(this.addOrUpdateForm),
              'fileJsonString': this.fileJsonString
            }
            console.log(params)
            prearchEdit(params).then(res => {
              if (res) {
                this.$message.success(res)
                this.$emit('close-dialog')
                this.crud.refresh()
              }
            })
          } else if (this.isDesFormType === 'mergeFile') {
            // 合并成件
            const params = {
              'archivesId': null,
              'archivesIds': this.mergeFileArcIds,
              'documentId': categoryId,
              'categoryId': this.mergeFileCategory,
              'jsonString': JSON.stringify(this.addOrUpdateForm)
            }
            FetchMergeToFile(params).then(res => {
              if (res) {
                this.$message.success(res)
                this.$emit('close-dialog')
                this.crud.refresh()
              }
            })
          } else {
            // 收集库
            let parentsId = null
            // 2 项目  3 案卷 /文件 4 卷内 6 文件
            if (this.isTitleType === 2) {
              parentsId = null
            } else if (this.isTitleType === 3) {
              if (this.selectedCategory.arrangeType === 1) {
                parentsId = null
              } else {
                parentsId = this.parentsData.parentsProjectId
              }
            } else if (this.isTitleType === 4) {
              // 卷内
              parentsId = this.parentsData.parentsAnjuanId
            } else if (this.isTitleType === 6) {
              // 原文
              parentsId = this.parentsData.parentsJuanneiId
            }
            let params
            if (quickPaperArcId && quickPaperArcId.length !== 0 && this.archivesType === 'add') {
              // 快速组卷时，组卷的文件是数组，所以要archivesIds 而不是 archivesId，正好是新增文件，所以this.arcId = null不用担心
              params = {
                'archivesId': this.arcId,
                'archivesIds': quickPaperArcId,
                'categoryId': categoryId,
                'parentsId': parentsId,
                'categoryLevel': 2,
                'jsonString': JSON.stringify(this.addOrUpdateForm)
              }
            } else if (this.selectedCategory.arrangeType === 3 && this.activeIndex === 1 && this.archivesType === 'add') {
              // 在项目下，未整理的文件只属于门类下，不属于任何项目或案卷，所以parentsId === null
              params = {
                'archivesId': this.arcId,
                'archivesIds': null,
                'categoryId': categoryId,
                'parentsId': null,
                'categoryLevel': this.collectLevel,
                'jsonString': JSON.stringify(this.addOrUpdateForm)
              }
            } else {
              params = {
                'archivesId': this.arcId,
                'archivesIds': null,
                'categoryId': categoryId,
                'parentsId': parentsId,
                'categoryLevel': this.collectLevel,
                'jsonString': JSON.stringify(this.addOrUpdateForm)
              }
            }
            console.log(params)
            if (this.archivesType === 'add') {
              collectAdd(params).then(res => {
                if (res.code === 200) {
                  this.$message.success(res)
                  this.$emit('close-dialog', parentsId)
                }
              })
            } else {
              collectEdit(params).then(res => {
                console.log(res)
                if (res.code === 200) {
                  this.$message.success(res)
                  this.$emit('close-dialog', parentsId)
                } else {
                  this.$message.error(res.message)
                  this.$emit('close-dialog', parentsId)
                }
              })
            }
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleClose(done) {
      this.popoverVisible = false
      this.popoverClassifyVisible = false
      this.popoverFondsVisible = false
      this.popoverTableData = []
      this.popoverTableDataClassify = []
      this.popoverTableDataFonds = []
      done()
    },
    // 选择附件
    async changeFile(e) {
      this.file = e.target.files[0]
      this.fileSize = this.file.size
      this.formatType = this.file.type.substring(0, this.file.type.indexOf('/'))
      this.fileNames = this.file.name
      this.postfix = this.file.name.substring(
        this.fileNames.lastIndexOf('.') + 1,
        this.fileNames.length
      )
      if (this.formatType === 'image') {
        const fileBase64 = await this.getBase64(this.file)
        const res = await this.getImgPx(fileBase64)
        this.px = res.width + 'px*' + res.height + 'px'
      } else {
        this.px = ''
      }
      // 上传附件
      reDocumentUpload(this.baseApi + '/api/re-document/uploadFile', this.file, this.selectedDocument.id).then(res => {
        if (res.data.code === 200) {
          this.filePath = res.data.data
          this.uploadSave()
        }
      })
    },
    // 上传附件 - 选择上传即保存
    uploadSave() {
      this.nowDate = getCurrentTime()
      const json = {
        'file_name': this.fileNames,
        'file_size': this.fileSize,
        'file_type': this.postfix,
        'file_path': this.filePath,
        'sequence': null,
        'archive_id': this.arcId,
        'file_dpi': this.px,
        'file_thumbnail': '',
        'create_time': this.nowDate,
        'id': null,
        'is_quote': null
      }
      const arrayUpload = []
      arrayUpload.push(json)
      // this.addOrUpdateForm.fileOriginal = this.fileNames
      this.$set(this.addOrUpdateForm, 'fileOriginal', this.fileNames)
      this.fileJsonString = JSON.stringify(arrayUpload)
    },
    // 将上传的图片转为base64
    getBase64(file) {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      return new Promise((resolve) => {
        reader.onload = () => {
          resolve(reader.result)
        }
      })
    },
    // 获取图片的分辨率
    getImgPx(img) {
      const image = new Image()
      image.src = img
      return new Promise((resolve) => {
        image.onload = () => {
          const width = image.width
          const height = image.height
          resolve({ width, height })
        }
      })
    },
    // 项目级别 - 阶段分类
    getDictsList(item) {
      FetchDictionaryTree().then((res) => {
        const filterCodes = ['project_class']
        let filteredItems = JSON.parse(JSON.stringify(res)).filter(item => filterCodes.includes(item.dictionaryCode))
        filteredItems = this.addLevelToDictionaryList(filteredItems, 1)
        if (item.isInputClass === 'select') {
          this.$set(item, 'options', filteredItems)
        } else if (item.isInputClass === 'popover') {
          this.popoverTableData = filteredItems
          this.popoverVisible = true
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 给筛选出来的数据加level 方便后面是否可点击
    addLevelToDictionaryList(dictionaryList, level) {
      dictionaryList.forEach(dictionary => {
        dictionary.level = level
        if (dictionary.childDictionarys) {
          dictionary.childDictionarys = this.addLevelToDictionaryList(dictionary.childDictionarys, level + 1)
        }
      })
      return dictionaryList
    }
  }
}

</script>
<style lang="scss" scoped>
@import "~@/assets/styles/mixin.scss";
@import "~@/assets/styles/variables.scss";

@mixin preview-border-style{
  [data-theme="dark"] & {
    border: 1px solid #3a99fd;
  }
  [data-theme="light"] & {
    border: 1px solid #EDEFF3;
  }
}

@mixin preview-border-color{
  [data-theme="dark"] & {
    // border-color: #3a99fd;
    border-color: #EDEFF3;
  }
  [data-theme="light"] & {
    border-color: #EDEFF3;
  }
}

.preview-content {
  padding: 20px 0 0 0 !important;
  margin-top: 0 !important;
  border-radius: 4px;
  margin: 0 auto;
  border: 1px solid;
  @include preview-border-color;
  .el-row {
    margin-left: 0 !important;
    margin-right: 0 !important;
  }
  .el-col {
    padding-left: 0 !important;
    padding-right: 0 !important;
  }
  ::v-deep .el-form-item__label{
    @include tree_font_color;
  }
  ::v-deep .el-input__inner,
  ::v-deep .vue-treeselect__control,
  ::v-deep .el-textarea__inner {
    width: 100%;
    background-color: transparent;
    @include input_style;
  }
  ::v-deep .vue-treeselect__control{
    height: 32px !important;
  }
  ::v-deep .el-input__prefix {
    text-align: right;
    right: 5px !important;
    @include tree_font_color;
  }
  .input-popover {
    ::v-deep .el-input__suffix {
      @include tree_font_color;
    }
  }
  ::v-deep .el-date-editor {
    width: 225px;
    .el-input__inner {
      padding-left: 15px;
    }
  }
  ::v-deep .el-form-item--small .el-form-item__content {
    line-height: 30px;
  }
  ::v-deep .el-input.is-disabled .el-input__inner{
    background-color: #f5f7fa;
    color: #c0c4cc;
  }
}
.preview-form-bottom{
  padding: 20px 20px 0 20px;
  border-top: 1px solid;
  @include preview-border-color;

}
.prearch-bottom{
  position: fixed;
  bottom: 72px;
  left: 0;
  background: #fff;
  width: 100%;
  padding: 20px 0 0 20px;
}

.prearch-upload{
  margin-right: 0 !important;
  ::v-deep .el-form-item__content{
    width: 540px !important;
    display: flex;
    justify-content: space-between;
    .upload-btn{
      position: relative;
      width:96px;
      margin-right: 0 !important;
      margin-left: 10px;
      overflow: initial !important;
      #upFile{
        position: absolute;
        left: 0;
        top: 0;
        // opacity: 0;
        width: 84px;
        height: 34px;
      }
      .el-button{
        margin-top: -2px;
        font-weight: bold;
        border-color: #0348f3;
        color: #0348f3;
      }
    }
  }
}
</style>
