<template>
  <el-dialog custom-class="custom-dialog" class="border" :border="false" closeFree width="600px"
             :title="title" :visible.sync="visible" v-model="visible" append-to-body :close-on-click-modal="true"
             :destroy-on-close="true">
    <div>
      <div class="picker">
        <div class="candidate" v-loading="loading">
          <div style="padding: 5px 8px;">
            <el-input v-model="filterText" style="width: 100%;" size="small"
                      clearable placeholder="输入关键字进行过滤" prefix-icon="el-icon-search"/>
            <div style="margin-top: 5px">
              <el-radio-group v-model="radio" size="mini" @change="radioChange">
                <el-radio-button :label="0">角色</el-radio-button>
                <el-radio-button :label="1">部门</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <!-- 人员选择 -->
          <el-empty :image-size="100" description="似乎没有数据" v-show="dataList.length === 0"/>
          <el-scrollbar style="height:317px">
            <div class="tree">
              <el-tree :data="dataList" ref="tree" :props="defaultProps" empty-text="" node-key="value"
                       :default-expanded-keys="expandedKeys" lazy accordion
                       @node-click="handleChange" @node-expand="handleChange"
              >
                <template #default="{ node, data }">
                  <div class="tree-node">
                    <div v-if="data.type === 0" style="display: flex;align-items: center;padding: 3px 0">
<!--                      <el-avatar :src="data.avatar"></el-avatar>-->
                      {{ node.label }}
                    </div>
                    <div v-else-if="data.type ===1">
                      <el-icon>
                        <UserFilled/>
                      </el-icon>
                      {{ node.label }}
                    </div>
                    <div v-else>
                      <el-icon>
                        <FolderOpened/>
                      </el-icon>
                      {{ node.label }}
                    </div>
                  </div>
                </template>
              </el-tree>
            </div>
          </el-scrollbar>
        </div>
        <div class="selected">
          <div class="count">
            <span>已选 {{ selectList.length }} 项</span>
            <span @click="clearSelected">清空</span>
          </div>
          <div class="org-items" style="height: 350px;">
            <el-empty :image-size="100" description="请点击左侧列表选择数据" v-show="selectList.length === 0"/>
            <div v-for="(selectItem, selectIndex) in selectList" :key="selectIndex" class="org-item">
<!--              <el-avatar :src="selectItem.avatar" style="margin-right: 5px;"></el-avatar>-->
              {{ selectItem.name}}
              <i class="el-icon-close" @click="noSelected(selectItem)"></i>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div slot="footer">
      <el-button size="mini" @click="visible = false">取 消</el-button>
      <el-button size="mini" type="primary" @click="selectConfirm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script setup>
import {getUserTree} from "@/api/workflow/process-user";
import {computed, defineProps, defineExpose} from "vue";
import {ElMessageBox} from "element-plus";

const props = defineProps({
  value: {
    type: Array,
    default: () => {
      return [];
    }
  },
  multiple: { //是否多选
    default: true,
    type: Boolean
  },
  showCheckbox: { //是否显示左侧选择框
    default: true,
    type: Boolean
  }
});
const radio = ref(0);
const chooseId = ref(0);
let selectItem = reactive({
  type: -1,
  value: "0"
});
const activeNames = ref(["1"]);
const visible = ref(false);
const loading = ref(false);
const title = ref("请选择");
const selectList = ref([]);
const filterText = ref("");
const dataList = ref([]);
const tree = ref([]);
const expandedKeys = ref([]);
const defaultProps = {
  value: "value",
  label: "name",
  children: "children",
  isLeaf:(data, node) => {
    if (node.level === 2) {
      return true
    }
  }

};
const emit = defineEmits();

const _value = computed({
  get() {
    return props.value;
  },
  set(val) {
    emit("input", val);
  }
});

watch(() => filterText, (newVal, oldVal) => {
  tree.value.filter(newVal);
});


const radioChange = (e) => {
  selectItem.type = -2;
  chooseId.value = 0;
  radio.value = e;
  expandedKeys.value = [];
  getList();
};

const getList = () => {
  getUserTree(radio.value, chooseId.value).then(res => {
    // if (res.data) {
    if (selectItem.type === -1 || selectItem.type === -2) {//角色/部门
      dataList.value = res.data;
    } else if (selectItem.type === 1) {
      selectItem.children = res.data;
      if(chooseId.value!==0&&res.data.length===0){
        selectItem.children=[{
          type:1,
          name:'暂无数据'
        }]
      }
    } else if (selectItem.type === 2) {
      selectItem.children = res.data;
    }
    // }
  });
};

const setData = (source) => {
  // for (let item of source) {
  //   this.$set(item, "value", selectItem.value + "-" + item.id)
  // }
  return source;
};

//通过关键字过滤树节点
// filterNode(value, data) {
//   if (!value) return true;
//   return data.name.indexOf(value) !== -1;
// },
//用于用户选择
const showUserPicker = () => {
  selectItem = {
    type: -1,
    value: "0"
  };
  dataList.value = [];
  selectList.value = []
  chooseId.value = 0;
  radio.value = 0;
  visible.value = true;
  expandedKeys.value = [];
  getList();
};
const handleChange = (item, data, node) => {
  //渲染子节点用户或部门及用户数据
  selectItem = item;
  if (data.expanded) {
    if(expandedKeys.value.indexOf(item.value)===-1){
      expandedKeys.value.push(item.value);
      if (item.type !== 0) {
        chooseId.value = item.id;
        getList();
        return;
      }
    }
  }

  // if(expandedKeys.value.indexOf(item.value)==-1){
  //   expandedKeys.value.push(item.value);
  // }else {
  //   if (data.expanded === true) {
  //     if (item.type !== 0) {
  //       chooseId.value = item.id;
  //       getList();
  //       return;
  //     }
  //   }
  // }

  //仅选择用户
  if (item.type === 0) {
    if (props.multiple) {
      //不添加重复的数据到右边
      for (let i = 0; i < selectList.value.length; i++) {
        if (selectList.value[i].id === item.id) {
          selectList.value.splice(i, 1);
          break;
        }
      }
      selectList.value.push(item);
    } else {
      selectList.value = [item];
    }
  }
  // _value = selectList.value
};

const noSelected = (selectItem) => {
  //右侧的x
  for (let i = 0; i < selectList.value.length; i++) {
    if (selectList.value[i].value === selectItem.value) {
      selectList.value.splice(i, 1);
      break;
    }
  }
  selectItem.selected = false;
};
const clearSelected = () => {
  //清空
  ElMessageBox.confirm("您确定要清空已选中的项?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    selectList.value = [];
  });
};
const selectConfirm = () => {
  //确定按钮
  emit("ok", selectList.value);
  dataList.value = []
  visible.value = false;
};
defineExpose({
  showUserPicker
});
</script>

<style lang="scss" scoped>
$containWidth: 264px;
:deep(.tree) {
  .el-tree {
    .el-tree-node {
      .el-tree-node__children {
        .el-tree-node {
          .el-tree-node__content {
            //height: 45px !important;

            .tree-node {
            }
          }
        }
      }
    }
  }

  .el-tree-node {
    .is-leaf + .el-checkbox .el-checkbox__inner {
      display: inline-block;
    }

    .el-checkbox .el-checkbox__inner {
      display: none;
    }
  }

  .tree-node {
    div {
      .el-avatar {
        width: 40px;
        height: 40px;
        margin-right: 5px;
      }
    }
  }
}


.el-dialog__body {
  padding: 10px 20px;
}

.picker {
  height: 402px;
  position: relative;
  text-align: left;

  .candidate {
    left: 0;
    top: 0;
  }
}

.candidate, .selected {
  position: absolute;
  display: inline-block;
  width: $containWidth;
  height: 400px;
  border: 1px solid #e8e8e8;
}

.selected {
  border-left: none;
  right: 0;
  top: 0;

  .count {
    width: calc(var($containWidth) - 20px);
    padding: 10px;
    display: inline-block;
    border-bottom: 1px solid #e8e8e8;
    margin-bottom: 5px;

    & > span:nth-child(2) {
      float: right;
      color: #c75450;
      cursor: pointer;
    }
  }
}

.org-items {
  overflow-y: auto;
  height: 350px;

  .el-icon-close {
    position: absolute;
    right: 5px;
    cursor: pointer;
    font-size: larger;
  }

  .org-item {
    margin: 0 5px;
    border-radius: 5px;
    position: relative;
    padding: 7px 5px;
    display: flex;
    align-items: center;

    cursor: pointer;

    &:hover {
      background: #f1f1f1;
    }

    > span {
      margin-left: 5px;
    }
  }
}

.el-scrollbar .el-scrollbar__wrap {
  overflow-x: hidden;
}

::-webkit-scrollbar {
  float: right;
  width: 4px;
  height: 4px;
  background-color: white;
}

::-webkit-scrollbar-thumb {
  border-radius: 16px;
  background-color: #efefef;
}

</style>
