<template>
  <el-dialog custom-class="custom-dialog" class="border" :border="false" closeFree width="1000px" style="height: 676px"
             :title="title" :show-close="false"  :visible.sync="visible" v-model="visible" append-to-body :close-on-click-modal="false"
             >
    <div class="picker">
      <div class="candidate" v-loading="loading">
        <el-input v-model="filterText" @change="getList"
                  clearable placeholder="输入昵称进行搜索">
          <template #append>
            <el-button @click="getList">搜索</el-button>
          </template>
        </el-input>
        <!-- 人员选择 -->
        <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" lazy :load="loadNode" accordion
                     @node-click="handleClickTreeNode">
              <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="removeSingleSelected(selectItem)" size="20" style="margin-left: 10px;cursor: pointer;">
              <CircleClose/>
            </el-icon>
          </div>
        </div>
      </div>
    </div>
    <div class="footer">
      <el-button size="mini" @click="cancelUserPicker">取 消</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
  },
  isResearch: {
    default: false,
    type: Boolean
  },
});
const radio = ref(0);
let selectItem = reactive({
  type: -1,
  value: "0"
});
const visible = ref(false);
const loading = ref(false);
const title = ref("请选择");
const selectList = ref([]);
const filterText = ref("");
const dataList = ref([]);
const isRemoveSingleSelected = ref(false);
const originallySelectedList = 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 = () => {
  let params = {
    chooseId: 0,
    chooseName: filterText.value,
    isResearch: props.isResearch
  }
  getMosrUser(params).then(res => {
    dataList.value = res.data;
  });
};
//用于用户选择
const showUserPicker = () => {
  selectItem = {
    type: -1,
    value: "0"
  };
  dataList.value = [];
  selectList.value = _value.value
  radio.value = 0;
  visible.value = true;
  expandedKeys.value = [];
  filterText.value = ''
  getList()
};

async function loadNode(node, resolve) {
  let data = node.data
  let params = {}
  if (data.id) {
    params = {
      chooseId: data.id,
      isResearch: props.isResearch
    }
  } else {
    params = {
      chooseId: 0,
      isResearch: props.isResearch
    }
  }
  let result = await getMosrUser(params).then(res => {
    if (res.data.length === 0) {
      return []
    } else {
      return res.data
    }
  })
  resolve(result)
}


const handleClickTreeNode = (item, data) => {
  selectItem = item;
  if (isSearch.value && item.type !== 0) {
    filterText.value = ""
    radio.value = item.id;
    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;
          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];
    }
  }
  // localStorage.setItem('originallySelectedList', JSON.stringify(selectList.value))
};

const removeSingleSelected = (selectItem) => {
  //右侧的x
  for (let i = 0; i < selectList.value?.length; i++) {
    if (selectItem.value) {
      if (selectList.value[i].value === selectItem.value) {
        selectList.value.splice(i, 1);
        break;
      }
    } else {
      if (selectList.value[i].id === selectItem.id) {
        selectList.value.splice(i, 1);
        break;
      }
    }
  }
  isRemoveSingleSelected.value = true
  selectItem.selected = false;
};
const clearSelected = () => {
  //清空
  ElMessageBox.confirm("您确定要清空已选中的项?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    isRemoveSingleSelected.value = true
    selectList.value = [];
    emit("cancelOrClear", selectList.value);
  });
};
const cancelUserPicker = () => {
  if (localStorage.getItem('originallySelectedList')) {
    selectList.value = JSON.parse(localStorage.getItem('originallySelectedList'))
  }else{
    if(_value.value?.length>0){
      selectList.value=_value.value
    }else {
      selectList.value = []
    }
  }
  emit("cancelOrClear", selectList.value);
  visible.value = false;
  nextTick(()=>{
    isRemoveSingleSelected.value=false
  })
}
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;
  }
  localStorage.setItem('originallySelectedList', JSON.stringify(selectList.value))
};
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>
