<template>
    <el-dialog :visible.sync ="value"
               :before-close="handleCloseDialog"
               :width="width"
               class="cbim-person-select"
               :close-on-click-modal="false"
               :title="title">
        <el-input v-model="search.input" size="mini" clearable :placeholder="placeHolder" @change="getSearchValue"></el-input>
        <div class="cbim-person-select__content">
            <div class="cbim-person-select__content-left">
                <div class="cbim-person-select__content-title">
                    人员选择
                </div>
                <el-tree v-if="search.show"
                         ref="tree0"
                         v-loading="search.loading"
                         class="cbim-person-select__content-value"
                         show-checkbox
                         :node-key="nodeKey"
                         :default-checked-keys="defaultCheckedKeys"
                         :default-expanded-keys="defaultExpandedKeys"
                         :props="defaultProps"
                         :data="search.result"
                         @check-change="handleCheckChange">
                </el-tree>
                <el-tree v-else
                     ref="tree1"
                     v-loading="search.loading"
                     class="cbim-person-select__content-value"
                     show-checkbox
                     :node-key="nodeKey"
                     :default-checked-keys="defaultCheckedKeys"
                     :default-expanded-keys="defaultExpandedKeys"
                     :props="defaultProps"
                     :data="allUsers"
                     @check-change="handleCheckChange">
                </el-tree>
            </div>
            <div class="cbim-person-select__content-right">
                <div class="cbim-person-select__content-title">
                    人员确认（共{{rightData.length}}人）
                </div>
                <div class="cbim-person-select__content-value">
                    <slot :data="rightData"></slot>
                </div>
            </div>
        </div>
        <el-footer class="cbim-person-select__footer">
            <el-button size="small" style="float: right" @click="handleCheckedUsers">确定</el-button>
            <el-button size="small" style="float: right;margin-right: 15px" @click="handleCloseDialog">取消</el-button>
        </el-footer>
    </el-dialog>
</template>

<script>
import SearchMixin from './mixins/search'
import TreeMethodsMixin from './mixins/treeRefMethods'

export default {
  name: 'CbimPersonSelect',
  mixins: [SearchMixin, TreeMethodsMixin],
  props: {
    title: {
      type: String,
      default: () => '添加管理员账号'
    },
    value: {
      type: Boolean,
      default: () => false
    },
    width: {
      default: () => '600px'
    },
    placeHolder: {
      type: String,
      default: () => '请输入姓名'
    },
    emptyText: {
      type: String,
      default: () => '查无数据'
    },
    nodeKey: {
      default: () => 'id'
    },
    nodeId: { // 左右两栏的人员关联id
      default: () => 'id'
    },
    defaultProps: {
      default: () => ({
        children: 'children',
        label: 'title',
        disabled: 'disabled',
      })
    },
    selectedUsers: {
      type: Array,
      default: () => []
    },
    allUsers: {
      type: Array,
      default: () => []
    },
    relationKey: {
      default: () => 'id' // 左右两部分数据的关联字段
    },
    userType: {
      type: String,
      default: () => 'user' // 左右两部分数据的关联字段
    },
    parentId: {
      type: String,
      default: () => 'depId' // 左右两部分数据的关联字段
    }
  },
  data() {
    return {
      rightData: [],
      defaultExpandedKeys: []
    }
  },
  watch: {
    selectedUsers: {
      handler() {
        this.rightData = JSON.parse(JSON.stringify(this.selectedUsers || []))
        this.defaultExpandedKeys = []
        const keys = this.rightData.map(r => r[this.nodeKey])
        this.setDisabled(this.allUsers, keys)
        this.defaultExpandedKeys.push(...keys)
      },
      immediate: true
    },
    'allUsers.length': {
      handler() {
        this.setDisabled(this.allUsers, this.rightData.map(r => r[this.nodeKey]))
      }
    },
    allUsers: {
      handler() {
        this.setDisabled(this.allUsers, this.rightData.map(r => r[this.nodeKey]))
      }
    },
    value: {
      handler() {
        if (this.value && this.allUsers.length) {
          this.setDisabled(this.allUsers, this.rightData.map(r => r[this.nodeKey]))
        }
      },
      immediate: true
    }
  },
  computed: {
    selectedUserIds() {
      return (this.selectedUsers || []).map(s => s[this.nodeKey])
    },
    defaultCheckedKeys() {
      // 右侧传入的数据中id跟左侧协同的数据中的id不一致，但userName（部门没有该字段）是一致的
      return this.rightData.map(r => r[this.nodeKey]).filter(f => ![null, undefined].includes(f))
    }
  },
  methods: {
    handleCloseDialog() {
      this.rightData = JSON.parse(JSON.stringify(this.selectedUsers || []))
      this.search.input = ''
      this.search.show = false
      this.$emit('input', false)
    },
    handleCheckedUsers() {
      this.$emit('change', this.rightData)
      this.search.input = ''
      this.search.show = false
      this.$emit('input', false)
    },
    handleCheckChange(...args) {
      if (!this.value || args[0].type !== this.userType) {
        return
      }
      if (args[1]) { // false -> true
        this.rightData.push(args[0])
      } else { // true -> false
        this.rightData = this.rightData.filter(f => f[this.nodeKey] !== args[0][this.nodeKey])
      }
    }
  }
}
</script>
