<template>
  <div>
    <a-popover v-model:visible="visible"  placement="bottom" trigger="click">
      <template #content v-if="!disabled">
        <div class="pover">
          <div class="search">
            <a-select
              v-model:value="selectName"
              style="width: 100%"
              placeholder="请查询姓名或工号"
              :options="isOpen?options:selectOptions"
              :filter-option="false"
              allowClear
              showSearch
              :open="isOpen"
              :defaultOpen="false"
              @search="searchMembers"
              @change="handleChange"
              @blur="blur"
            >
              <template #suffixIcon><ZoomInOutlined twoToneColor="#eb2f96" /></template>
              <template v-if="loading" #notFoundContent>
                <a-spin size="small"/>
              </template>
            </a-select>
          </div>
          <div class="tree">
            <a-tree show-icon allow-clear tree-default-expand-all :tree-data="treeData" :loading="orgLoading"
              :load-data="onLoadData" v-model:selectedKeys="stuTreeSelectKeys"
              v-model:expandedKeys="stuTreeExpandedKeys" :fieldNames="{
                children: 'treeChildList',
                key: 'id',
                title: 'name',
                value: 'name',
              }" @select="stuStuOrgSelect" style="max-height: 260px;overflow-y: auto;width: 250px;">
              <template #smile>
                <UserOutlined />
              </template>
            </a-tree>
          </div>
          <div class="btn">
            <div class="btn0 btn1" @click="notChange">取消</div>
            <!-- <div class="btn0 btn2" @click="changeOut">确定</div> -->
            <a-button :loading="loadingChange" @click="changeOut" class="btn0 btn2" type="primary">确定</a-button>
          </div>
        </div>
      </template>
      <a-select
        v-model:value="selectData"
        style="width: 100%"
        placeholder="请选择讲师"
        :options="selectOptions"
        :filter-option="false"
        :open="false"
        :defaultOpen="false"
        :disabled="disabled"
      >
        <template v-if="loading" #notFoundContent>
          <a-spin size="small"/>
        </template>
      </a-select>
    </a-popover>
  </div>
</template>

<script setup>
import { ref,defineProps,defineEmits,watch,onMounted } from 'vue';
import { request, useRequest} from "@/api/request";
import { message } from "ant-design-vue"
import { ORG_CHILD_LIST, ORG_LIST,USER_LIST_PAGE} from "@/api/apis";
import { getTeacherByDepartId,getTeacherByNameOrUserNo,getSystemInfoByUserId,getTeacherList } from "@/api/Lecturer";
import { ZoomInOutlined,UserOutlined } from '@ant-design/icons-vue';
const props = defineProps({
  value:{
    type: String,
    default: '',
  },
  lable:{
    type: String,
    default: '',
  },
  newlable:{
    type: String,
    default: '',
  },
  system:{
    type: Object,
    default: ()=>{},
  },
  level:{
    type: String,
    default: '',
  },
  orgId:{
    type: String,
    default: '',
  },
  id:{
    type: String,
    default: '',
  },
  payrollPlaceCode: {
    type: String,
    default: '',
  },
  payrollPlaceName: {
    type: String,
    default: '',
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  lecturer: {
    type: Boolean,
    default: false,
  }
})
const emit = defineEmits(['update:value','update:lable','update:system','update:level','update:newlable','update:orgId','update:id','update:payrollPlaceCode','update:payrollPlaceName'])
const visible = ref(false);
const selectData = ref(null);
watch(()=>props.value,(val)=>{
  if(val){
    selectData.value = val
  }else{
    selectData.value = null
  }
},{immediate:true})
const teacherName = ref('')
const selectName = ref(null)
const options = ref([]);
const selectOptions = ref([])
const isOpen = ref(false);
const loading = ref(false);
function blur() {
  isOpen.value = false
}
const orgName = ref('')
const orgId = ref('')
const payrollPlaceCode = ref('')
const payrollPlaceName = ref('')
const systemName = ref(null)
const levelName = ref('')
const neworgName = ref('')
const teacherId = ref('')
const handleChange = (e,l) => {
  isOpen.value = false
  // emit('update:value',e)
  teacherName.value = e
  orgName.value = l.orgName
  // systemName.value = l.systemName
  levelName.value = l.levelName
  teacherId.value = l.key
  orgId.value = l.orgId
  payrollPlaceCode.value = l.payrollPlaceCode
  payrollPlaceName.value = l.payrollPlaceName
  if( l.orgName !==null ){
          neworgName.value= orgName.value.split('/')
          neworgName.value=  neworgName.value[ neworgName.value.length-1]
        } 
  emit('tlevel',l)
};
function debounce(func, wait) {
  let timeout;
  return function(...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(this, args), wait);
  };
}
const searchMembers = (keyword) => {
  isOpen.value = true
  options.value = []
  loading.value = true
  if(keyword == '' || keyword == null){
    isOpen.value = false
    loading.value = false
    options.value = []
  }else{
    debounceObject(keyword)
  }
};
const searchMember = (keyword) => {
  const obj = {
    keyword,
    pageNo:'1',
    pageSize:'50',
    departId:'',
  }
  props.lecturer && getTeacherByNameOrUserNo(obj).then((res) => {
    if(res.data.status == 200){
      loading.value = false
      options.value = res.data.result.list.map((item) => {
        return {
          value: item.realName+'/'+item.userNo,
          label: item.realName+'('+item.userNo+')'+item.orgName,
          system: item.realName+'('+item.userNo+')'+item.tSystemName,
          level:  item.realName+'('+item.userNo+')'+item.sLevelName,
          key: item.id,
          orgName: item.orgName,
          orgId: item.departId,
          tSystemName:item.tSystemName,
          sLevelName:item.sLevelName,
          payrollPlaceCode: item.payrollPlaceCode,
          payrollPlaceName:item.payrollPlaceName,
        }
      })
    }else{
      loading.value = false
    }
  }).catch(()=>{
    loading.value = false
  })
  const params = {
    pageNo: 1,
    pageSize: 50,
    name: keyword
  }
  !props.lecturer && getTeacherList(params).then(res=>{
    console.log(res,'ressss')
    if(res.data.code == 200){
      loading.value = false
      options.value = res.data.data.records.map((item) => {
        return {
          value: item.name+'/'+item.userNo,
          label: item.name+'('+item.userNo+')'+item.tsystemName,
          system: item.name+'('+item.userNo+')'+item.tsystemName,
          level:  item.name+'('+item.userNo+')'+item.sLevelName,
          key: item.id,
          orgName: item.orgName,
          orgId: item.departId,
          tSystemName:item.tsystemName,
          sLevelName:item.sLevelName,
          payrollPlaceCode: item.salaryId,
          payrollPlaceName:item.salaryName,
          tlevelName: item.tlevelName,  //讲师级别
          tlevelId: item.tlevelId,      //讲师级别id
          // salaryName: item.salaryName,    //发薪地
          // salaryId: item.salaryId,
          levelPay: item.levelPay
        }
      })
    }
  }).catch(()=>{
    loading.value = false
  })
};
const debounceObject = debounce(searchMember, 1500);
const filterOption = (input, option) => {
  console.log(input,option,'xixixixi')
};

const stuTreeSelectKeys = ref([]);
const stuTreeExpandedKeys = ref([]);
const teacherById = ref(null)
const { data: treeData, loading: orgLoading } = useRequest(
  ORG_LIST,
  { keyword: "" },
);
function onLoadData(treeNode) {
  teacherById.value = treeNode.id
  const promises = [];
  const childDatas = []
  promises.push(
    getTeacherByDepartId({organizationId:teacherById.value}).then((res) => {
      if(res.data.code == 200){
        res.data.data.list.map(item=>{
          return (
            item.isLeaf = true,
            item.name = item.realName + '/' + item.userNo,
            item.slots = {icon:'smile'}
          )
        })
        childDatas.unshift(...res.data.data.list)
      }
    }).catch((err)=>{
      console.log(err,'err')
    })
  );
  promises.push(
    request(ORG_CHILD_LIST, { keyword: "", orgId: treeNode.id }).then((r) => {
      // treeNode.dataRef.treeChildList = r.data;
      childDatas.push(...r.data)
      treeData.value = [...treeData.value];
    })
  );

  return Promise.all(promises).then(() => {
    treeNode.dataRef.treeChildList = childDatas;
      treeData.value = [...treeData.value];
  });
}
function stuStuOrgSelect(e, {selected: bool, selectedNodes, node, event}) {
  console.log(selectedNodes)
  teacherName.value = ''
  orgName.value = ''
  orgId.value = ''
  systemName.value = null
  levelName.value = ''
  teacherId.value = ''
  payrollPlaceCode.value = ''
  payrollPlaceName.value = ''
  if(selectedNodes[0].isLeaf){
    teacherName.value = selectedNodes[0].name
    orgName.value = selectedNodes[0].orgName
    orgId.value = selectedNodes[0].departId
    // systemName.value = selectedNodes[0].systemName
    levelName.value = selectedNodes[0].levelName
    teacherId.value = selectedNodes[0].id
    // emit('update:value',selectedNodes[0].realName)
    payrollPlaceCode.value = selectedNodes[0].payrollPlaceCode
    payrollPlaceName.value = selectedNodes[0].payrollPlaceName
  }
}
watch(()=>visible.value,(val)=>{
  if(val){
    stuTreeSelectKeys.value = []
    stuTreeExpandedKeys.value = []
    teacherName.value = ''
    orgName.value = ''
    orgId.value = ''
    systemName.value = null
    levelName.value = ''
    neworgName.value=''
    selectName.value = null
    // selectData.value = ''
    teacherId.value = ''
    loadingChange.value = false
    // teacherId.value = '1012311820121276416'
    // changeneworg()
    payrollPlaceCode.value = ''
    payrollPlaceName.value = ''
  }
})
const notChange = () => {
  visible.value = false
  teacherName.value = ''
  orgName.value = ''
  orgId.value = ''
  systemName.value = null
    levelName.value = ''
  neworgName.value=''
  teacherId.value = ''
  loadingChange.value = false
  payrollPlaceCode.value = ''
  payrollPlaceName.value = ''
}
const loadingChange = ref(false)
watch(()=>teacherId.value,(val)=>{
  if(val){
    loadingChange.value = true
    getSystemInfoByUserId(teacherId.value).then(res=>{
      if(res.data.code == 200){
        systemName.value = {
          systemId:res.data.data?.id,
          systemName:res.data.data?.systemName,
          systemCode:res.data.data?.systemCode,
          levelVoList: res.data.data?.levelVoList?.map(item=>{
            return (
              item.label = item.levelName,
              item.value = item.id,
              item
            )
          })
        }
      }
      loadingChange.value = false
      emit('update:system',systemName.value)
    }).catch(err=>{
      message.error('讲师体系获取失败，请重新选择')
      loadingChange.value = false
    })
  }
})
const changeOut = () => {
  if(!teacherName.value){
    message.error('请选择讲师')
    return
  }
  const neworgName = ref('')
  // const changeneworg= ()=>{
  //   if( orgName !==null ){
  //             neworgName=orgName.split('/')
              
  //             neworgName= neworgName[neworgName.length-1]
  // }
  selectData.value = teacherName.value
  emit('update:value',teacherName.value)
  emit('update:lable',orgName.value)
  emit('update:orgId',orgId.value)
  emit('update:system',systemName.value)
  emit('update:level',levelName.value)
  emit('update:newlable',neworgName.value)
  emit('update:id',teacherId.value)
  emit('update:payrollPlaceCode',payrollPlaceCode.value)
  emit('update:payrollPlaceName',payrollPlaceName.value)
  notChange()
}
</script>

<style lang="scss" scoped>
.pover{
  .search{
    margin-top: 10px;
  }
  .tree{
    margin-top: 5px;
    border: 1px solid rgba(215, 215, 215, 1);
  }
  .btn{
    margin-top: 10px;
    display: flex;
    justify-content: flex-end;
    .btn0{
      width: 70px;
      height: 25px;
      color: #FFFFFF;
      text-align: center;
      line-height: 25px;
      cursor: pointer;
    }
    .btn1{
      margin-right: 10px;
      background-color: rgba(170, 170, 170, 1);
    }
    .btn2{
      background-color: rgba(50, 107, 250, 1);
      padding: 0;
    }
  }
}

</style>