<template>
  <!-- 文件名称下拉选择框 -->
  <div>
    <!-- 普通选择框 -->
    <base-select v-if="!isAll && !disabled" v-model="currentValue"
               :clearable="clearable"
               :filterable="filterable "
               :multiple="multiple"
               :api="api"
               :options.sync="options"
               :queryParas="queryParasValue"
               :collapsetags="collapsetags"
               :disabled="disabled"
               :reload="reload"
               :selectedField="selectedField"
               @loaded="loaded"
               :placeholder="placeholder"
               @select-changed="selectChanged"
               no-data-text="数据加载中或加载失败">
    </base-select>
    <!-- 查看 -->
    <el-input v-if="disabled && !isAll" :disabled="disabled" v-model="checkValue"></el-input>
    <!-- 树形选择框 -->
    <el-select v-if="isAll" v-model="currentValues" value-key="fileName" :multiple="multiple" :collapse-tags="true" placeholder="请选择" size="medium" @change="handleChange">
      <el-option
        :value="currentList" style="height: auto">
        <el-tree
          ref="tree"
          :data="options"
          show-checkbox
          highlight-current
          node-key="fileType"
          :default-expanded-keys="['0','10','20']"
          @check="handleCheckChange"
          :props="{
            children: 'children',
            label: 'fileName'
          }">
        </el-tree>
      </el-option>
    </el-select>
  </div>
</template>

<script>
import componentsApi from '@/api/assetoutfeedback/componentsApi'
import components from 'newepoch-components'
export default {
  name: 'fileSelectList',
  components: {
    BaseSelect: components.BaseSelect
  },
  props: {
    // v-model绑定的数据
    value: {
      type: [Array, String, Number],
      default: function () {
        return ''
      }
    },
    // 是否禁用修改
    disabled: {
      type: Boolean,
      default: function () {
        return false
      }
    },
    // 是否可多选
    multiple: {
      type: Boolean,
      default: function () {
        return false
      }
    },
    // 重新加载数据（每次取非即可）
    reload: {
      type: Boolean,
      default: function () {
        return false
      }
    },
    // 是否可搜索
    filterable: {
      type: Boolean,
      default: function () {
        return false
      }
    },
    // 是否可清除
    clearable: {
      type: Boolean,
      default: function () {
        return true
      }
    },
    // 多选折叠
    collapsetags: {
      type: Boolean,
      default: function () {
        return false
      }
    },
    // 默认提示语
    placeholder: {
      type: String,
      default: function () {
        return '请选择'
      }
    },
    name: {
      type: String,
      default: 'file',
      require: false
    },
    // 列表请求参数
    queryParas: {
      type: Object,
      default: function () {
        return {}
      }
    },
    // 文件查询类型(1.抽样，2.确权，3.其他，4.全部)
    fileQueryType: {
      type: [String, Number],
      default: function () {
        return '4' // 默认全部
      }
    },
    // 电子章印区分(1.电子章，2.鲜章)
    stampWay: {
      type: [String, Number],
      default: function () {
        return '' // 默认为空
      }
    },
    // 是否显示全部
    isAll: {
      type: [Boolean],
      default: function () {
        return false
      }
    }
  },
  watch: {
    fileQueryType: function () {
      // console.log(this.stampWay)
      this.queryParasValue = Object.assign({
        fileQueryType: this.fileQueryType,
        stampWay: this.stampWay
      }, this.defaultQueryParas, this.queryParas)
    },
    stampWay: function () {
      this.queryParasValue = Object.assign({
        fileQueryType: this.fileQueryType,
        stampWay: this.stampWay
      }, this.defaultQueryParas, this.stampWay)
      // console.log(this.stampWay)
    },
    currentValue (e) {
      // console.log(e)
      this.$nextTick(() => {
        this.init()
      })
    }
  },
  data () {
    return {
      // 下拉列表数据
      'options': [],
      currentList: [],
      currentValues: '',
      list: [],
      // 自定义键名
      selectedField: ['fileType', 'fileName'],
      // 列表请求参数
      queryParasValue: Object.assign({
        fileQueryType: this.fileQueryType,
        stampWay: this.stampWay
      }, this.defaultQueryParas, this.queryParas)
    }
  },
  mounted () {
    let $this = this
    if (this.disabled) {
      $this.api['getList'](this.queryParasValue).then(res => {
        if (res && res.success && res.data) {
          this.options = res.data
        }
      })
    }
    if (this.isAll) {
      $this.api['getList'](this.queryParasValue).then(res => {
        if (res && res.success && res.data) {
          let tree = [
            {
              fileName: '全部',
              fileType: '0',
              children: []
            }
          ]
          let sample = /^10/
          let confirm = /^20/
          let other = /^30/
          let sampleOptions = {
            fileName: '抽样文件',
            fileType: '10',
            children: []
          }
          let confirmOptions = {
            fileName: '确权文件',
            fileType: '20',
            children: []
          }
          let otherOptions = {
            fileName: '其他文件',
            fileType: '30',
            children: []
          }
          this.list = res.data
          for (let index in res.data) {
            let item = res.data[index]
            for (let index2 in this.currentValue) {
              let item2 = this.currentValue[index2]
              if (item.fileType === item2) {
                this.currentList.push({
                  fileName: item.fileName,
                  fileType: item.fileType
                })
              }
            }
            if (sample.test(item.fileType)) {
              sampleOptions.children.push(item)
            } else if (confirm.test(item.fileType)) {
              confirmOptions.children.push(item)
            } else if (other.test(item.fileType)) {
              otherOptions.children.push(item)
            }
          }
          if (sampleOptions.children.length > 0) {
            tree[0].children.push(sampleOptions)
          }
          if (confirmOptions.children.length > 0) {
            tree[0].children.push(confirmOptions)
          }
          if (otherOptions.children.length > 0) {
            tree[0].children.push(otherOptions)
          }
          $this.options = tree
          if (res.data.length === 0) {
            $this.noDataText = '无数据'
          }
          this.init()
        } else {
          this.noDataText = '加载失败'
        }
      })
    } else {
      this.noDataText = '加载失败'
    }
  },
  computed: {
    // 转换绑定的选中数据，与v-model同步
    currentValue: {
      get: function () {
        return this.value
      },
      set: function (value) {
        this.$emit('input', value)
      }
    },
    api () {
      return componentsApi.fileList
    },
    checkValue () {
      return this.options.length > 0 ? this.options.filter(item => {
        return item.fileType === this.currentValue
      })[0].fileName : ''
    }
  },
  methods: {
    init () {
      if (this.isAll) {
        var arrNew = []
        var arrNews = []
        var dataLength = this.currentList.length
        var e = this.currentValue
        var eleng = e.length
        for (let i = 0; i < dataLength; i++) {
          for (let j = 0; j < eleng; j++) {
            if (e[j] === this.currentList[i].fileType) {
              arrNew.push(this.currentList[i])
              arrNews.push(this.currentList[i].fileName)
            }
          }
        }
        this.currentValues = arrNews
        this.$nextTick(() => {
          this.$refs.tree.setCheckedNodes(arrNew) // 设置勾选的值
        })
      }
    },
    handleChange (e) {
      var arrNew = []
      var dataLength = this.currentList.length
      var eleng = e.length
      for (let i = 0; i < dataLength; i++) {
        for (let j = 0; j < eleng; j++) {
          if (e[j] === this.currentList[i].fileName) {
            arrNew.push(this.currentList[i])
          }
        }
      }
      // 表单值
      this.currentValue = arrNew.map(item => {
        return item.fileType
      })
      this.$refs.tree.setCheckedNodes(arrNew) // 设置勾选的值
    },
    // 选择节点
    handleCheckChange (a, b) {
      let res = this.$refs.tree.getCheckedNodes(true, false)
      let arrLabel = []
      res.forEach(item => {
        arrLabel.push(item)
      })
      // 显示值
      this.currentValues = arrLabel.map(item => {
        return item.fileName
      })
      // 表单值
      this.currentValue = arrLabel.map(item => {
        return item.fileType
      })
      this.currentList = arrLabel
    },
    selectChanged (val, row) {
      this.$emit('selectChanged', val, this.name, row)
    },
    loaded (val) {
      let $this = this
      let selectItemts = null
      if (val.length > 0) {
        if (!this.multiple) {
          selectItemts = val.find(it => {
            return $this.currentValue === it[$this.selectedField[0]]
          })
        } else {
          selectItemts = val.filter(it => {
            var isTrue = false
            $this.currentValue.forEach(kit => {
              if (kit === it[$this.selectedField[0]]) {
                isTrue = true
              }
            })
            return isTrue
          })
        }
        this.$emit('selectChanged', '', this.name, selectItemts)
      }
    }
  }
}
</script>
