<template>
  <div>
    <!-- 批量成件 -->
    <el-dialog class="batch-form" append-to-body :modal-append-to-body="false" :close-on-click-modal="false" :before-close="handleClose" :visible="batchVisible" title="批量成件">
      <span class="dialog-right-top" />
      <span class="dialog-left-bottom" />
      <div class="setting-dialog">
        <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="130px">
          <el-form-item label="对应规则" prop="rules">
            <el-select v-model="form.ruleName" placeholder="请选择" style="width: 225px;" @change="selectRules">
              <el-option
                v-for="item in rulesOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="归档范围" prop="scope">
            <el-input v-model="form.scope" type="text" readonly>
              <i slot="suffix" class="el-input__icon iconfont icon-sousuo" @click="selectScope" />
            </el-input>
          </el-form-item>
          <el-form-item label="源分类" prop="documentName">
            <el-input v-model="form.documentName" type="text" disabled />
          </el-form-item>
          <el-form-item label="目标门类" prop="categoryId">
            <treeselect
              v-model="form.categoryId"
              :options="categoryTree"
              flat
              :multiple="false"
              :normalizer="normalizer"
              :default-expand-level="6"
              placeholder="请选择目标门类（整理库/管理库门类）"
              @select="handleSelectCategory"
            />
          </el-form-item>
        </el-form>
        <div v-loading="fieldLoading" class="corres-field-main">
          <div class="corres-field-list corres-field-left">
            <div class="corres-field-title">
              <p>字段取值</p>
            </div>
            <div class="field-list">
              <div v-for="(item, index) in selectStatus" :key="index" class="field-item">
                <el-select :key="index" v-model="item.fiedType" @change="selectChangeFiedType(index)">
                  <el-option
                    v-for="v in fiedOption"
                    :key="v.value"
                    :label="v.label"
                    :value="v.value"
                  />
                </el-select>
              </div>
            </div>
          </div>
          <div class="corres-field-list corres-field-middle">
            <div class="corres-field-title">
              <p>源分类（文件库-文件表）</p>
              <span>{{ form.documentName }}</span>
            </div>
            <div v-loading="leftLoading" class="field-list">
              <div v-for="(item, index) in selectStatus" :key="index" class="field-item">
                <el-select v-if="item.mode" :key="index" v-model="item.value" @change="selectChange(index)">
                  <el-option value="">请选择</el-option>
                  <el-option
                    v-for="v in options"
                    :key="v.id"
                    :label="v.fieldCnName"
                    :value="v.fieldCnName"
                  />
                </el-select>
                <p v-if="!item.mode" @click="textMode(index)">
                  {{ item.value }}
                </p>
              </div>
            </div>
          </div>
          <div class="corres-field-list corres-field-right">
            <div class="corres-field-title">
              <p>目标门类（整理库/管理库-文件表）</p>
              <span>{{ selectedCategoryName }}</span>
            </div>
            <div v-loading="rightLoading" class="field-list">
              <div v-if="isCorrField">
                <div v-for="(item,index) in allFieldData" :key="index" class="field-item">
                  <p>{{ item.categoryFieldId.fieldCnName }}</p>
                  <div class="field-state"><span :class=" item.categoryFieldId.isInput ? 'is-select' : 'is-hide'">{{ item.categoryFieldId.isInput ? '显示': '隐藏' }}</span></div>
                </div>
              </div>
              <div v-else>
                <div v-for="(item,index) in allCorrField" :key="index" class="field-item">
                  <p>{{ item.fieldCnName }}</p>
                  <div class="field-state"><span :class=" item.isInput ? 'is-select' : 'is-hide'">{{ item.isInput ? '显示': '隐藏' }}</span></div>
                </div>
              </div>
            </div>
          </div>
          <div v-if="allFieldData.length === 0 && allCorrField.length === 0" class="empty-data" />
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleComfirmBatchToFile">确定</el-button>
        </div>
      </div>
    </el-dialog>
    <ScopeModule ref="scopeModule" @getScope="hanleScopeSelect" />
  </div>
</template>

<script>
import { preLibraryCrud } from '../mixins/index'
import { FetchInitFieldMate, FetchMateByDocumentId, FetchDetailsByDocumentIdAndCategoryId } from '@/api/system/fieldMate'
import { FetchInitDocumentFieldByPid } from '@/api/system/fileLibrary/fileLibrary'
import { FetchCategoryMenu, FetchInitCategoryFieldByPid } from '@/api/system/category/category'
import { FetchArchivesScopeByCategoryId } from '@/api/system/archivesScope'
import { FetchCheckRepeat } from '@/api/system/fieldMate'
import { FetchBatchToFile } from '@/api/prearchiveLibrary/prearchiveLibrary'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
// import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import ScopeModule from './scope'
export default {
  name: 'BatchFile',
  components: { Treeselect, ScopeModule },
  mixins: [preLibraryCrud],
  props: {
    selectedDocument: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  data() {
    return {
      selectionsArc: [],
      batchVisible: false,
      rulesOptions: [],
      categoryTree: [],
      form: {
        ruleName: null,
        scope: null,
        documentId: null,
        documentName: '',
        categoryId: null
      },
      batchCategory: {},
      selectedCategoryName: null,
      scopeVisible: false,
      loadSource: [],
      rules: {
        categoryId: [
          { required: true, message: '请选择档案门类', trigger: 'change' }
        ]
      },
      fiedOption: [{
        'label': '默认值',
        'value': 2
      }, {
        'label': '字段值',
        'value': 1
      }],
      fiedType: null,
      selectStatus: [],
      selectOptions: [],
      options: [],
      fieldLoading: false,
      allFieldData: [],
      targetData: [],
      leftLoading: false,
      rightLoading: false,
      isCorrField: true,
      allCorrField: [],
      isTest: false
    }
  },
  watch: {
    selectedDocument: function(newValue, oldValue) {
      this.form.documentName = newValue.cnName
      this.getMateByDocumentId()
      this.getCategoryDataTree()
    }
  },
  created() {
  },
  mounted() {
  },
  methods: {
    // 根据预归档库获取对应规则
    getMateByDocumentId() {
      const params = {
        'documentId': this.selectedDocument.id
      }
      FetchMateByDocumentId(params).then(res => {
        this.rulesOptions = res.map(item => {
          const json = {}
          json.label = item.ruleName
          json.value = item.id
          return json
        })
      })
    },
    getInitDetail(id) {
      FetchInitFieldMate({ 'id': id }).then((res) => {
        this.selectedCategoryName = res.categoryName
        this.batchCategory = res.fieldMateDetails[0].pid.categoryId
        this.form.categoryId = res.fieldMateDetails[0].pid.categoryId.pid
        this.getArchivesScopeByCategoryId()
      }).catch(err => {
        console.log(err)
      })
    },
    selectRules(val) {
      this.getInitDetail(val)
      this.selectStatus = []
      this.allFieldData = []
      this.allCorrField = []
      this.isCorrField = true
      this.isTest = false
    },
    // 目标门类
    getCategoryDataTree() {
      FetchCategoryMenu().then(res => {
        this.categoryTree = this.filterData(res)
      })
    },
    // 根据pid获取门类字段
    initDocunmentFiledList(documentId) {
      // 文件库字段
      this.leftLoading = true
      FetchInitDocumentFieldByPid({ documentId: documentId, isType: 2 }).then((res) => {
        this.options = res.sort((a, b) => {
          if (a.isInput !== b.isInput) {
            return a.isInput ? -1 : 1
          } else {
            return a.isSequence - b.isSequence
          }
        })
        this.leftLoading = false
      })
    },
    // 根据pid获取门类字段
    initCategoryFiledList(categoryId) {
      // 门类字段
      this.rightLoading = true
      FetchInitCategoryFieldByPid({ categoryId: categoryId, isType: 2 }).then((res) => {
        this.allCorrField = res.sort((a, b) => {
          if (a.isInput !== b.isInput) {
            return a.isInput ? -1 : 1
          } else {
            return a.isSequence - b.isSequence
          }
        })
        res.forEach((item, index) => {
          this.selectStatus.push({ mode: true, fiedType: 1, value: '', field: item, isInput: item.isInput })
        })
        this.rightLoading = false
      })
    },
    // 根据预归档库和门类获取详情
    getDetailsByDocumentIdAndCategoryId() {
      this.fieldLoading = true
      const params = {
        'categoryId': this.form.categoryId,
        'documentId': this.selectedDocument.id
      }
      this.initDocunmentFiledList(this.selectedDocument.id,)
      FetchDetailsByDocumentIdAndCategoryId(params).then(res => {
        this.allFieldData = res
        res.forEach((item, index) => {
          this.selectStatus.push({ mode: false, fiedType: item.categoryFieldId.isDefaultValue === '' ? 1 : 2, value: item.categoryFieldId.isDefaultValue === '' ? item.documentFieldId.fieldCnName : item.categoryFieldId.isDefaultValue, field: item.documentFieldId, isInput: item.documentFieldId.isInput })
        })
        this.fieldLoading = false
      })
    },
    // 根据子门类id获取档案归档范围
    getArchivesScopeByCategoryId() {
      const params = {
        'categoryId': this.form.categoryId
      }
      FetchArchivesScopeByCategoryId(params).then(res => {
        console.log(res)
        if (Array.isArray(res) && res.length === 1) {
          this.form.scope = res[0].scopeName
        } else {
          this.form.scope = null
          console.log('有多个“归档范围”')
        }
        this.getDetailsByDocumentIdAndCategoryId()
      })
    },
    handleSelectCategory(val) {
      console.log(val)
      this.selectedCategoryName = val.cnName
      this.form.categoryId = val.id
      this.batchCategory = val
      // this.getArchivesScopeByCategoryId()
      const params = {
        'categoryId': this.form.categoryId
      }
      FetchArchivesScopeByCategoryId(params).then(res => {
        if (Array.isArray(res) && res.length === 1) {
          this.form.scope = res[0].scopeName
        } else {
          this.form.scope = null
          console.log('有多个“归档范围”')
        }
        this.getCheckRepeat()
      })
    },
    // 归档范围选择
    selectScope() {
      this.$refs.scopeModule.scopeVisible = true
      this.$nextTick(() => {
        if (this.form.categoryId) {
          this.$refs.scopeModule.$refs.tree2.setCurrentKey(this.form.categoryId)
          this.$refs.scopeModule.handleNodeClick2(this.batchCategory)
        }
      })
    },
    hanleScopeSelect(val, category) {
      if (val.length !== 0) {
        this.form.scope = val[0].scopeName
        this.form.categoryId = category.id
        this.batchCategory = category
        this.selectedCategoryName = category.cnName
        this.$nextTick(() => {
          this.getCheckRepeat()
        })
      }
    },
    getCheckRepeat() {
      const params = {
        'categoryId': this.form.categoryId,
        'documentId': this.selectedDocument.id
      }
      this.fieldLoading = true
      FetchCheckRepeat(params).then((res) => {
        if (JSON.stringify(res) === JSON.stringify({})) {
          console.log('不存在对应关系')
          this.isCorrField = false
          this.$message({
            message: '目标门类与当前源分类不存在对应关系',
            type: 'warning'
          })
          this.form.ruleName = null
          this.selectStatus = []
          this.initDocunmentFiledList(this.selectedDocument.id)
          this.initCategoryFiledList(this.form.categoryId)
        } else {
          console.log('存在对应关系')
          this.isCorrField = true
          this.selectStatus = []
          this.allFieldData = []
          this.form.ruleName = res.id

          this.getDetailsByDocumentIdAndCategoryId()
        }
        this.fieldLoading = false
      })
    },
    // 切换 "字段值" / "默认值"
    selectChangeFiedType(index) {
      this.options.forEach((item) => {
        if (this.selectStatus[index].fiedType === 2) {
          if (!this.isCorrField) {
            this.selectStatus.splice(index, 1, { mode: false, fiedType: this.selectStatus[index].fiedType, value: this.selectStatus[index].fiedType === 1 ? this.selectStatus[index].value : this.allCorrField[index].isDefaultValue, field: item, isInput: item.isInput })
          } else {
            this.selectStatus.splice(index, 1, { mode: false, fiedType: this.selectStatus[index].fiedType, value: this.allFieldData[index].categoryFieldId.isDefaultValue, field: item, isInput: item.isInput })
          }
        } else {
          if (!this.isCorrField) {
            this.isTest = true
          } else {
            this.isTest = false
          }
          this.selectStatus.splice(index, 1, { mode: true, fiedType: this.selectStatus[index].fiedType, value: '', field: item, isInput: item.isInput })
        }
      })
    },
    selectChange(index) {
      this.options.forEach((item) => {
        if (!this.isCorrField && this.allCorrField[index].isDefaultValue !== '') {
          if (this.isTest) {
            this.selectStatus.splice(index, 1, { mode: false, fiedType: 1, value: this.selectStatus[index].value, field: item, isInput: item.isInput })
          } else {
            this.selectStatus.splice(index, 1, { mode: false, fiedType: 2, value: this.allCorrField[index].isDefaultValue === '' ? this.selectStatus[index].value : this.allCorrField[index].isDefaultValue, field: item, isInput: item.isInput })
          }
        } else {
          if (this.selectStatus[index].fiedType === 1) {
            this.selectStatus.splice(index, 1, { mode: false, fiedType: 1, value: this.selectStatus[index].value, field: item, isInput: item.isInput })
          } else {
            if (item.fieldCnName === this.selectStatus[index].value) {
              this.selectStatus.splice(index, 1, { mode: false, fiedType: this.allFieldData[index].categoryFieldId.isDefaultValue === '' ? 1 : 2, value: this.allFieldData[index].categoryFieldId.isDefaultValue === '' ? this.selectStatus[index].value : this.allFieldData[index].categoryFieldId.isDefaultValue, field: item, isInput: item.isInput })
            }
          }
        }
      })
    },
    textMode(index) {
      if (this.selectStatus[index].fiedType === 1) {
        this.selectStatus.splice(index, 1, { mode: true, fiedType: 1, value: this.selectStatus[index].value, field: null, isInput: this.selectStatus[index].isInput })
      }
    },
    handleClose(done) {
      this.batchVisible = false
      Object.assign(this.form, {
        ruleName: null,
        scope: null,
        documentId: null,
        categoryId: null
      })
      this.selectedCategoryName = null
      this.allFieldData = []
      this.allCorrField = []
      this.isTest = false
      this.batchCategory = {}
      // done()
    },
    handleComfirmBatchToFile() {
      // const getIndicesByMode = (modeValue) => {
      //   return this.selectStatus.reduce((indices, item, index) => {
      //     if (item.mode === modeValue) {
      //       indices.push(index)
      //     }
      //     return indices
      //   }, [])
      // }
      // const indices = getIndicesByMode(false)
      // const arrAL = this.selectStatus.map(item => {
      //   if (item.hasOwnProperty('field')) {
      //     return {
      //       documentValue: item['field'].fieldName,
      //       getType: item.fiedType // 在field字段中添加getType字段并赋值
      //     }
      //   } else {
      //     return item
      //   }
      // })
      // console.log(arrAL)
      const dtos = this.allFieldData.map((item, index) => {
        return {
          'categoryValue': item.categoryFieldId.fieldName,
          'documentValue': this.selectStatus[index].fiedType === 2 ? item.categoryFieldId.isDefaultValue : this.selectStatus[index].field.fieldName,
          'getType': this.selectStatus[index].fiedType,
          'isRequired': item.categoryFieldId.isRequired
        }
      })
      const archivesIds = this.selectionsArc.map(item => {
        return item.id
      })
      const params = {
        'archivesIds': archivesIds,
        'documentId': this.selectedDocument.id,
        'categoryId': this.form.categoryId,
        'dtos': dtos
      }
      console.log(params)
      FetchBatchToFile(params).then((res) => {
        console.log(res)
        if (res === 'SUCCESS') {
          this.$emit('refresh')
          this.batchVisible = false
          Object.assign(this.form, {
            ruleName: null,
            scope: null,
            documentId: null,
            categoryId: null
          })
          this.selectedCategoryName = null
          this.allFieldData = []
        }
      })
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.cnName,
        children: node.children,
        isDisabled: node.isType !== 2
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/prearchive-library.scss";
.batch-form{
  ::v-deep .el-dialog{
    width: 828px !important;
  }
  .corres-field-left{
    width: 146px;
    .corres-field-title{
      p{
        padding-top: 0 !important;
        line-height: 60px;
      }
    }
    .field-list{
      .field-item{
        width: 146px;
        ::v-deep .el-select{
          width: 145px !important;
          border-right: none;
        }
      }
    }
  }
  .corres-field-middle{
    .field-list{
      .field-item{
        width: 315px;
        ::v-deep .el-select{
          width: 314px !important;
          border-right: none;
        }
      }
    }
  }
}
.corres-field-main{
  position: relative;
}
.empty-data{
  position: absolute;
  top: 60px;
  left: 0;
  width: 100%;
  height: calc(100% - 60px);
  background: url('~@/assets/images/system/zwsj.png') no-repeat center center #fff;
  background-size: 282px 182px;
}
</style>
