<!-- 负责模板/工作模板 组件 -->
<template>
  <el-tooltip placement="top" :disabled="showTipDisabled" style="padding: 0">
    <div slot="content" style="max-height: 100px; overflow-y: auto;margin: -10px">
      <div style="margin: 10px"><span v-html="this.tipTxtValue"></span></div>
    </div>
    <div class="block">
      <el-cascader
        ref="cascader"
        @change="changeMethod"
        @visible-change="onBlurAddressFun"
        :options="options"
        v-model="selectedOptions"
        :key="isResouceShow"
        :separator="separator"
        :disabled="disabled"
        :clearable="clearable"
        :show-all-levels="showAllLevels"
        :debounce="debounce"
        :collapse-tags="collapseTags"
        :props="cascaderProps"
        :filterable="filterable"
        class="component-width">
      </el-cascader>
    </div>
  </el-tooltip>
</template>

<script>
import vueCompApi from '@/api/enterpriseInfoManage/vueCompApi.js'
export default {
  name: 'SelectWorkTemplate',
  props: {
    isSelectAll: {
      type: Boolean,
      default () {
        return true
      }
    },
    cascaderProps: {
      type: Object,
      default: function () {
        return {
          // 是否多选
          multiple: true,
          // 是否严格的遵守父子节点不互相关联
          checkStrictly: false
        }
      }
    },
    value: {
      type: [String, Number, Array],
      default: function () {
        return null
      }
    },
    // 分隔符
    separator: {
      type: String,
      default: function () {
        return '/'
      }
    },
    // 是否禁用修改
    disabled: {
      type: Boolean,
      default: function () {
        return false
      }
    },
    // 是否可清除
    clearable: {
      type: Boolean,
      default: function () {
        return true
      }
    },
    // 输入框是否展示完整路径
    showAllLevels: {
      type: Boolean,
      default: function () {
        return true
      }
    },
    // 是否开启搜索功能 默认 是
    // filterable: {
    //   type: Boolean,
    //   default: function () {
    //     return true
    //   }
    // },
    // 搜索关键词输入的去抖延迟，毫秒
    debounce: {
      type: Number,
      default: function () {
        return 300
      }
    },
    // 多选模式下 是否折叠展示
    collapseTags: {
      type: Boolean,
      default: function () {
        return true
      }
    },
    queryParas: {
      type: Object,
      default: function () {
        return {}
      }
    },
    index: {
      type: Number,
      default: function () {
        return null
      }
    },
    name: {
      type: String,
      default: function () {
        return ''
      }
    },
    // 重新加载数据（每次取非即可）
    reload: {
      type: Boolean,
      default: function () {
        return false
      }
    },
    optionList: {
      type: Array,
      default: function () {
        return []
      }
    }
  },
  data () {
    return {
      // 选择数据的长度，用于判断是否全选
      len: 0,
      // 下拉数据
      options: [],
      tipTxtValue: '',
      isResouceShow: 0,
      filterable: true
    }
  },
  mounted () {
    // 加载数据
    this.afterLoadOptions()
    // this.loadOptions().then(() => {
    //   let obj = []
    //   // 全选所有
    //   if (!this.value && this.isSelectAll) {
    //     obj = this.selectAll()
    //   } else {
    //     // 选择已有数据
    //     obj = this.value
    //   }
    //   this.selectedOptions = obj
    //   if (obj) {
    //     this.filterable = false
    //     let dataList = this.getDataInfo(obj)
    //     this.$emit('selectChanged', this.index, name, dataList, obj)
    //   }
    //   this.len = obj.length
    //   // 判断是否全选
    //   setTimeout(() => {
    //     this.onBlurAddressFun(false)
    //   }, 50)
    // })

    // this.loadOptions()
  },
  computed: {
    showTipDisabled () {
      if (!this.tipTxtValue) return true
      return this.$attrs.tipdisabled || this.tipTxtValue.replace('<br/>', '').length === 0
    },
    // 转换绑定的选中数据，与v-model同步
    selectedOptions: {
      get: function () {
        return this.value
      },
      set: function (value) {
        this.$emit('input', value)
        try {
          this.tipTxtValue = this.showTipView(value)
        } catch (e) {}
      }
    },
    // 总长度
    optionsLen () {
      return this.selectAll().length
    },
    api () {
      return vueCompApi.selectWorkTemplate
    }
  },
  methods: {
    // 处理当前数据信息 获取数据对象
    getDataInfo (val) {
      let $this = this
      let dataList = []
      val.forEach(item => {
        let dto = {
          children: []
        }
        let child = {
          children: []
        }
        if (item.length === 3) {
          item.forEach((it, index) => {
            let data = $this.getNodeById($this.options, it)
            if (data && index === 0) {
              // 判断已有对象中是否存在当前keyId
              let newData = $this.getNodeById(dataList, it)
              // 删除数组中已存在当前keyId的数据重新构造
              if (newData) {
                dataList.forEach((newItem, index1) => {
                  dto = newItem
                  if (newItem.value === it) {
                    // 删除
                    dataList.splice(index1, 1)
                  }
                })
              } else {
                dto.value = data.value
                dto.label = data.label
                dto.children = []
              }
            }
            if (data && index === 1) {
              let newChild = {}
              // 判断已有对象子节点中是否存在当前keyId
              let newData1 = $this.getNodeById(dto.children, it)
              if (newData1) {
                dto.children.forEach((newItem, index1) => {
                  newChild = newItem
                  if (newItem.value === it) {
                    // 删除
                    dto.children.splice(index1, 1)
                    // dto.children.push(newChild)
                    child = newChild
                  }
                })
              } else {
                child.value = data.value
                child.label = data.label
                child.children = []
                // 向子节点中构造值
                // dto.children.push(child)
              }
            }
            if (data && index === 2) {
              let child1 = {}
              child1.value = data.value
              child1.label = data.label
              child.children.push(child1)
              dto.children.push(child)
            }
          })
        }
        if (item.length === 2) {
          item.forEach((it, index) => {
            let data = $this.getNodeById($this.options, it)
            if (data && index === 0) {
              // 判断已有对象中是否存在当前keyId
              let newData = $this.getNodeById(dataList, it)
              // 删除数组中已存在当前keyId的数据重新构造
              if (newData) {
                dataList.forEach((newItem, index1) => {
                  dto = newItem
                  if (newItem.value === it) {
                    // 删除
                    dataList.splice(index1, 1)
                  }
                })
              } else {
                dto.value = data.value
                dto.label = data.label
                dto.children = []
              }
            }
            if (data && index === 1) {
              let newChild = {}
              // 判断已有对象子节点中是否存在当前keyId
              let newData1 = $this.getNodeById(dto.children, it)
              if (newData1) {
                dto.children.forEach((newItem, index1) => {
                  newChild = newItem
                  if (newItem.value === it) {
                    // 删除
                    dto.children.splice(index1, 1)
                    // dto.children.push(newChild)
                    child = newChild
                  }
                })
              } else {
                child.value = data.value
                child.label = data.label
                child.children = []
                // 向子节点中构造值
                dto.children.push(child)
              }
            }
          })
        }
        dataList.push(dto)
      })
      return dataList
    },
    // 当前所有节点的长度
    changeMethod (val) {
      let $this = this
      // var selectItemts = null
      $this.len = val.length
      let dataList = $this.getDataInfo(val)
      $this.$emit('selectChanged', $this.index, name, dataList, val)
    },
    // 显示tip
    showTipView (selectValue) {
      var txt = ''
      if (this.UtilJs.isEmpty(selectValue)) return txt
      if (!this.cascaderProps.multiple) selectValue = [selectValue]
      selectValue.forEach(it => {
        this.options.some(it1 => {
          if (!it1.children) {
            if (it1.value === it[0]) {
              txt += (!it1.label ? '' : it1.label)
              return true
            }
          } else {
            return it1.children.some(it2 => {
              if (!it2.children) {
                if (it2.value === it[1] && it1.value === it[0]) {
                  txt += it1.label + '|' + (!it2.label ? '' : it2.label)
                  return true
                }
              } else {
                return it2.children.some(it3 => {
                  if (it3.value === it[2] && it2.value === it[1] && it1.value === it[0]) {
                    txt += it1.label + '|' + it2.label + '|' + (!it3.label ? '' : it3.label)
                    return true
                  }
                })
              }
            })
          }
        })
        txt += '<br/>'
      })
      return txt
    },
    getNodeById (nodes, keyId) {
      let result
      if (nodes && nodes.length) {
        for (let i = 0, len = nodes.length; i < len; i++) {
          let node = nodes[i]
          result = node.value === keyId ? node : this.getNodeById(node.children, keyId)
          if (result) break
        }
      }
      return result
    },
    // 选择所有的数据
    selectAll () {
      let obj = []
      this.options.forEach(item => {
        let children = item.children
        // obj.push(item.value)
        if (children && children.length > 0) {
          children.forEach(it => {
            if (it.children && it.children.length > 0) {
              it.children.forEach(it2 => {
                let child = []
                child.push(item.value)
                child.push(it.value)
                child.push(it2.value)
                obj.push(child)
              })
            } else {
              let child = []
              child.push(item.value)
              child.push(it.value)
              obj.push(child)
            }
          })
        }
      })
      return obj
    },
    // 全选所有修改label
    onBlurAddressFun (val) {
      if (!val && this.len !== 0 && this.optionsLen === this.len) {
        if (this.$refs['cascader'].presentTags && this.$refs['cascader'].presentTags.length > 0) {
          this.$refs['cascader'].presentTags = this.$refs['cascader'].presentTags.slice(0, 1)
          this.$refs['cascader'].presentTags[0].closable = false
          this.$refs['cascader'].presentTags[0].text = '全部区域'
        }
      }
    },
    // 加载数据
    loadOptions () {
      let $this = this
      return new Promise((resolve, reject) => {
        if ($this.optionList.length > 0) {
          $this.optionList.forEach((it, index) => {
            $this.deleteNodes(it)
          })
          this.options = this.optionList
          resolve()
        } else {
          $this.api.getList(this.queryParas).then(res => {
            if (res && res.success && res.data) {
              res.data.forEach(it => {
                $this.deleteNodes(it)
              })
              $this.options = res.data
              resolve()
            }
          }).catch(error => {
            reject(error)
          })
        }
      })
    },
    deleteChild (child) {
      if (child.children && child.children.length === 0) {
        delete child.children
      } else {
        this.deleteNodes(child)
      }
    },
    deleteNodes (nodes) {
      if (nodes.children && nodes.children.length === 0) {
        delete nodes.children
      } else {
        if (nodes.children) {
          for (let i = 0; i < nodes.children.length; i++) {
            let child = nodes.children[i]
            this.deleteChild(child)
          }
        }
      }
    },
    // 初始加载后处理数据
    afterLoadOptions () {
      this.loadOptions().then(() => {
        let obj = []
        // 全选所有
        if (!this.value && this.isSelectAll) {
          obj = this.selectAll()
        } else {
          // 选择已有数据
          obj = this.value
        }
        this.selectedOptions = obj
        if (obj) {
          // this.filterable = false
          let dataList = this.getDataInfo(obj)
          this.$emit('selectChanged', this.index, name, dataList, obj)
        }
        this.len = obj.length
        // 判断是否全选
        setTimeout(() => {
          this.onBlurAddressFun(false)
        }, 50)
      })
    }
  },
  watch: {
    optionList () {
      if (this.optionList.length > 0) {
        this.optionList.forEach(it => {
          this.deleteNodes(it)
        })
        ++this.isResouceShow
        this.options = this.optionList
        // 加载数据
        this.loadOptions()
        this.afterLoadOptions()
      }
    },
    reload () {
      // this.loadOptions ()
      // if (this.optionList.length > 0) {
      //   this.optionList.forEach(it => {
      //     this.deleteNodes(it)
      //   })
      //   ++this.isResouceShow
      //   this.options = this.optionList
      // }
      // 加载数据
      this.loadOptions()
      this.afterLoadOptions()
    },
    selectedOptions (val) {
      if (val) {
        // 加载数据
        this.loadOptions()
        this.afterLoadOptions()
        let dataList = this.getDataInfo(val)
        this.$emit('selectChanged', this.index, this.name, dataList, val)
        // this.filterable = false
      } else {
        // this.filterable = true
      }
    }
  }
}
</script>

<style scoped lang="scss">
  @import '~@/styles/enterpriseInfoManage/supplierInfoManage/SelectWorkTemplate.scss';
</style>
