<template>
  <!--批量修改-->
  <el-dialog class="fileUpload-dialog" title="批量修改" :close-on-click-modal="false" :modal-append-to-body="false" append-to-body :visible.sync="bulkEditingVisible" :before-close="handleCloseDialog">
    <div class="setting-dialog">
      <div class="bulk-editing-container">
        <el-form ref="editForm" :model="editForm" :rules="editRules" label-width="100px">
          <el-form-item label="修改字段" prop="updateField">
            <el-select v-model="editForm.updateField" value-key="id" placeholder="请选择" style="width: 360px;" @change="selectField">
              <el-option
                v-for="item in fieldItemOptions"
                :key="item.id"
                :label="item.fieldCnName"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="修改方式" prop="updateType">
            <el-select v-model="editForm.updateType" placeholder="请选择" style="width: 360px;">
              <el-option
                v-for="item in editTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="editForm.updateType === 2" label="查询内容" prop="oldContext">
            <el-input v-model="editForm.oldContext" style="width: 360px;" />
          </el-form-item>
          <el-form-item label="更新内容" prop="updateContext">
            <!-- <el-select v-if="editForm.updateField.mateData === 3" v-model="editForm.updateContext" placeholder="请选择" style="width: 360px;">
              <el-option
                v-for="item in dictionaryOptions"
                :key="item.dictionaryId"
                :label="item.dictionaryName"
                :value="item.dictionaryName"
              />
            </el-select> -->

            <treeselect
              v-if="editForm.updateField.mateData === 3"
              v-model="editForm.updateContext"
              :options="dictionaryOptions"
              style="width: 360px;"
              flat
              :multiple="false"
              :normalizer="normalizerProject"
              placeholder="请选择"
            ><div slot="value-label" slot-scope="{ node }">{{ getAutoNameUnknown(node.label) }}</div></treeselect>

            <el-select v-else-if="editForm.updateField.mateData === 1" v-model="editForm.updateContext" placeholder="请选择" style="width: 360px;">
              <el-option
                v-for="item in fondsOptions"
                :key="item.fondsNo"
                :label="item.fondsName"
                :value="item.fondsNo"
              />
            </el-select>
            <treeselect
              v-else-if="editForm.updateField.mateData === 2"
              v-model="editForm.updateContext"
              :options="classifyOptions"
              style="width: 360px;"
              flat
              :multiple="false"
              :normalizer="normalizer"
              placeholder="请选择"
            ><div slot="value-label" slot-scope="{ node }">{{ getAutoNameUnknown(node.label) }}</div></treeselect>
            <el-date-picker
              v-else-if="editForm.updateField.isInputClass === 'date'"
              v-model="editForm.updateContext"
              type="date"
              placeholder="选择日期"
              style="width: 360px;"
            />
            <el-input-number
              v-else-if="editForm.updateField.isInputClass === 'number'"
              v-model.number="editForm.initialValue"
              :min="0"
              :max="999"
              controls-position="right"
              style="width: 360px;"
            />
            <el-input v-else v-model="editForm.updateContext" style="width: 360px;" />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="handleCloseDialog">取消</el-button>
        <el-button type="primary" @click.native="onSubmitBlukEditing('editForm')">确定</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { FetchInitCategoryInputFieldByPid } from '@/api/system/category/category'
import { FetchSonDictionaryList, FetchDictionaryTree } from '@/api/system/dict'
import { FetchFondsAll } from '@/api/system/fonds'
import { FetchArchivesClassTree } from '@/api/system/archivesClass'
import { FetchBatchUpdate } from '@/api/collect/collect'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  name: 'BlukEditing',
  components: { Treeselect },
  mixins: [],
  props: {
    selectedCategory: {
      type: Object,
      default: function() {
        return {}
      }
    },
    collectLevel: {
      type: Number,
      default: function() {
        return null
      }
    },
    selections: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      // 批量修改
      bulkEditingVisible: false,
      editForm: {
        updateField: '',
        updateType: 1,
        oldContext: '',
        updateContext: ''
      },
      fieldItemOptions: [],
      editTypeOptions: [{
        value: 1,
        label: '填充'
      }],
      dictionaryOptions: [],
      fondsOptions: [],
      classifyOptions: []
    }
  },
  computed: {
    editRules() {
      const validateRule = {
        updateField: [
          { required: true, message: '请选择修改字段', trigger: 'change' }
        ],
        updateType: [
          { required: true, message: '请选择修改方式', trigger: 'change' }
        ],
        oldContext: [
          { required: true, message: '请输入查询的内容', trigger: 'blur' }
        ],
        updateContext: [
          { required: true }
        ]
      }
      if (this.editForm.updateField.mateData !== null) {
        this.$set(validateRule, 'updateContext', [
          { required: true, message: '请选择更新内容', trigger: 'change' }
        ])
      } else if (this.editForm.updateField.isInputClass === 'date') {
        this.$set(validateRule, 'updateContext', [
          { type: 'date', required: true, message: '请选择日期', trigger: 'change' }
        ])
      } else {
        this.$set(validateRule, 'updateContext', [
          { required: true, message: '请输入更新内容', trigger: 'blur' }
        ])
      }
      return validateRule
    }
  },
  watch: {
    'editForm.updateField'(newVal) {
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate()
        this.editForm.updateContext = ''
        this.editForm.updateType = 1
        if (newVal.mateData !== null || newVal.isInputClass === 'date') {
          this.editTypeOptions = [{
            value: 1,
            label: '填充'
          }]
        } else if (newVal.isInputClass === 'number') {
          this.editTypeOptions = [{
            value: 1,
            label: '填充'
          },
          {
            value: 2,
            label: '替换'
          },
          {
            value: 3,
            label: '增加'
          },
          {
            value: 4,
            label: '减少'
          }]
        } else {
          this.editTypeOptions = [{
            value: 1,
            label: '填充'
          },
          {
            value: 2,
            label: '替换'
          }]
        }
      })
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.getInitCategoryInputFieldByPid()
    })
  },
  methods: {
    // 处理vue-treeSelect回显出现unknown问题
    getAutoNameUnknown(name) {
      if (name.lastIndexOf('unknown') > -1) {
        // 当treeselect翻译不了值时，name中有id，截取id，去调接口或者字典查询出名字
        return name.split('(')[0]
      } else {
        return name
      }
    },
    getInitCategoryInputFieldByPid() {
      const params = {
        'categoryId': this.selectedCategory.id,
        'categoryLevel': this.collectLevel
      }
      console.log(params)
      FetchInitCategoryInputFieldByPid(params).then(data => {
        this.fieldItemOptions = data
      })
    },
    selectField(val) {
      console.log(val)
      if (val.mateData === 3) {
        if (this.selectedCategory.arrangeType === 3 && val.fieldName === 'project_class') {
          this.getDictsList()
        } else {
          this.getSonDictionaryList(val.dictionaryId.id)
        }
      } else if (val.mateData === 1) {
        this.getFondsDatas()
      } else {
        this.getInitArchivesClass()
      }
    },
    getSonDictionaryList(dictionaryId) {
      FetchSonDictionaryList({ 'pid': dictionaryId }).then(res => {
        this.dictionaryOptions = res
      })
    },
    // 项目级别 - 阶段分类
    getDictsList() {
      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 (this.selectedCategory.arrangeType === 3 && this.collectLevel !== 1) {
          this.dictionaryOptions = filteredItems
        } else {
          this.dictionaryOptions = this.filterData(filteredItems, filteredItems[0].id)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 显示第一级和第二级
    filterData(data, targetId) {
      return data.filter(item => {
        if (item.id === targetId || item.dictionaryParents === targetId) {
          if (item.childDictionarys && item.childDictionarys.length > 0) {
            item.childDictionarys = this.filterData(item.childDictionarys, targetId)
          }
          return true
        }
        return false
      })
    },
    // 给筛选出来的数据加level 方便后面是否可点击
    addLevelToDictionaryList(dictionaryList, level) {
      dictionaryList.forEach(dictionary => {
        dictionary.level = level
        if (dictionary.childDictionarys) {
          dictionary.childDictionarys = this.addLevelToDictionaryList(dictionary.childDictionarys, level + 1)
        }
      })
      return dictionaryList
    },
    normalizerProject(node) {
      if ((node.childDictionarys && !node.childDictionarys.length) || node.childDictionarys === null) {
        delete node.childDictionarys
      }
      return {
        id: node.dictionaryName,
        label: node.dictionaryName,
        children: node.childDictionarys,
        isDisabled: (this.collectLevel !== 1 && node.level && node.level !== 3) || (this.collectLevel === 1 && node.level === 1)
      }
    },
    getFondsDatas() {
      FetchFondsAll().then(res => {
        this.fondsOptions = res
      })
    },
    getInitArchivesClass() {
      this.classifyOptions = []
      const params = {
        'categoryId': this.selectedCategory.id
      }
      FetchArchivesClassTree(params).then((res) => {
        this.classifyOptions = JSON.parse(JSON.stringify(res))
      }).catch(err => {
        console.log(err)
      })
    },
    normalizer(node) {
      if (node.childArchivesClass === null) {
        delete node.childArchivesClass
      }
      return {
        id: node.code,
        label: node.name,
        children: node.childArchivesClass
      }
    },
    onSubmitBlukEditing(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const archivesIds = this.selections.map(item => item.id)
          console.log(this.editForm)
          const params = {
            'archivesIds': archivesIds,
            'categoryId': this.selectedCategory.id,
            'categoryLevel': this.collectLevel,
            'updateField': this.editForm.updateField.fieldName,
            'oldContext': this.editForm.oldContext,
            'updateContext': this.editForm.updateContext,
            'updateType': this.editForm.updateType
          }
          console.log(params)
          FetchBatchUpdate(params).then(res => {
            this.$emit('close-dialog')
            this.handleCloseDialog()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleCloseDialog(done) {
      // 重置表单数据
      this.$refs.editForm.resetFields()
      this.bulkEditingVisible = false
      // 关闭弹框
      // done()
    }
  }
}
</script>

<style lang='scss' scoped>

</style>
