<template>
  <el-dialog custom-class="custom-dialog" class="border" :border="false" closeFree width="1000px" style="height: 676px"
             :title="title" :visible.sync="visible" v-model="visible" append-to-body :close-on-click-modal="true"
             :destroy-on-close="true">
    <div class="picker">
      <div class="candidate" v-loading="loading">
        <el-input v-model="filterText" @change="getList(1)"
                  clearable placeholder="输入昵称进行搜索">
          <template #append>
            <el-button @click="getList(1)">搜索</el-button>
          </template>
        </el-input>
        <!-- 人员选择 -->
        <el-empty :image-size="100" description="似乎没有数据" v-show="dataList.length === 0"/>
        <el-scrollbar style="height:90%;">
          <div class="tree">
            <el-tree :data="dataList" ref="tree" :props="defaultProps" empty-text="" node-key="value"
                     :default-expanded-keys="expandedKeys" default-expand-all 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-icon :color="data.accountType==='0'?'#95d475':'#409eff'">
                      <UserFilled/>
                    </el-icon>
                    {{ node.label }}-{{ data.companyName }}
                  </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">
          <el-empty :image-size="100" description="请点击左侧列表选择数据" v-show="selectList.length === 0"/>
          <div v-for="(selectItem, selectIndex) in selectList" :key="selectIndex" class="org-item">
            <el-icon :color="selectItem.accountType==='0'?'#95d475':'#409eff'" size="20">
              <UserFilled/>
            </el-icon>
            {{ selectItem.name }}-{{ selectItem.companyName }}
            <el-icon @click="noSelected(selectItem)" size="20" style="margin-left: 10px;cursor: pointer;">
              <CircleClose/>
            </el-icon>
          </div>
        </div>
      </div>
    </div>
    <div class="footer">
      <el-button size="mini" @click="visible = false">取 消</el-button>
      <el-button size="mini" color="#DED0B2" @click="selectConfirm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script setup>
import {ElMessageBox, ElNotification} from "element-plus";
import {getMosrUser} from "@/api/workflow/process-user";
import {checkMatrix} from "@/api/user/user";

const props = defineProps({
  value: {
    type: Array,
    default: () => {
      return [];
    }
  },
  multiple: { //是否多选
    default: true,
    type: Boolean
  },
  showCheckbox: { //是否显示左侧选择框
    default: true,
    type: Boolean
  },
  //打开弹窗时是否重置选中数据
  setNullToSelectList: {
    default: false,
    type: Boolean
  },
  checkMatrix: {
    default: false,
    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 isSearch = ref(false);
const expandedKeys = ref([]);
const defaultProps = {
  value: "value",
  label: "name",
  children: "children",
  isLeaf: (data) => {
    if (data.type === 0) {
      return true
    }
  }
};
const emit = defineEmits();

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

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

const getList = (flag) => {
  let params = {}
  if (flag === 1) {
    isSearch.value = true;
    params = {
      chooseId: 0,
      chooseName: filterText.value
    }
    selectItem = {
      type: -1,
      value: "0"
    };
  } else {

    params = {
      chooseId: radio.value,
      chooseName: filterText.value
    }
  }
  getMosrUser(params).then(res => {
    // if (res.data) {
    if (selectItem.type === -1) {
      dataList.value = res.data;
    } else if (selectItem.type === 1) {
      selectItem.children = res.data;
      if (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 = [];
  // console.log('_value.value',_value.value)
  // if(props.setNullToSelectList){
  //   selectList.value = []
  // }else {

    selectList.value =_value.value
  // }
  chooseId.value = 0;
  radio.value = 0;
  visible.value = true;
  expandedKeys.value = [];
  filterText.value = ''
  getList();
};
const handleChange = (item, data) => {
  selectItem = item;
  if (isSearch.value && item.type !== 0) {
    filterText.value = ""
    radio.value = item.id;
    getList();
    return;
  } else if (!isSearch.value) {
    //渲染子节点用户或部门及用户数据
    if (data.expanded) {
      if (expandedKeys.value.indexOf(item.value) === -1) {
        expandedKeys.value.push(item.value);
        if (item.type !== 0) {
          radio.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 = () => {
  //确定按钮
  if (props.checkMatrix){
    checkMatrix(selectList.value[0].id).then(res=>{
      console.log(res)
      if (res.code === 2000){
        ElNotification({
          title: '提示',
          message: res.msg,
          type: 'error'
        })
      }else {
        emit("ok", selectList.value);
        dataList.value = []
        visible.value = false;
      }
    })
  }else {
    emit("ok", selectList.value);
    dataList.value = []
    visible.value = false;
  }
};
defineExpose({
  showUserPicker
});
</script>

<style lang="scss" scoped>
$containWidth: 480px;
:deep(.tree) {
  .el-tree-node__content {
    height: 34px;

    .tree-node {
      font-size: 18px;
    }
  }

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

.footer {
  float: right;
}

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

  .candidate {
    position: absolute;
    display: inline-block;
    width: $containWidth;
    height: 98%;
    border: 1px solid #e8e8e8;

    :deep(.el-input) {
      height: 40px;

      .el-input__inner, .el-input-group__append {
        font-size: 16px;
      }
    }
  }

  .selected {
    right: 0;
    top: 0;
    position: absolute;
    display: inline-block;
    width: 450px;
    height: 98%;
    border: 1px solid #e8e8e8;

    .count {
      width: 100%;
      padding: 10px;
      display: inline-block;
      border-bottom: 1px solid #e8e8e8;
      margin-bottom: 5px;
      font-size: 16px;

      > span:nth-child(2) {
        float: right;
        color: #c75450;
        cursor: pointer;
        margin-left: 10px;
      }
    }

    .org-items {
      overflow-y: auto;
      height: 90%;

      .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;
        font-size: 16px;

        &: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>
