<template>
    <div>
         
      <div class="left-list" v-loading="leftListLoading || loading">
        <div class="list-tab">
          <div
            :class="'list-tab-item ' + (leftTab == 1 ? 'pitch-on' : '')"
            @click="() => (leftTab = 1)"
          >
            <img src="@/assets/images/Gc_114_line-Level-action.png" v-if="leftTab == 1" />
            <img src="@/assets/images/Gc_114_line-Level.png" v-else />
          </div>
          <div
            :class="'list-tab-item ' + (leftTab == 2 ? 'pitch-on' : '')"
            @click="() => (leftTab = 2)"
          >
            <img src="@/assets/images/book-read-fill-action.png" v-if="leftTab == 2" />
            <img src="@/assets/images/book-read-fill.png" v-else />
          </div>
        </div>
        <div class="list-content">
          <div class="content-top-input">
            <el-input
              v-model="queryFrom.nickName"
              placeholder="搜索成员"
              type="text"
              prefix-icon="Search"
              @change="searchList"
            />
          </div>
          <div class="content-datapicker" v-if="leftTab == 1">
            <el-date-picker
              v-model="queryFrom.leftDatePicker"
              type="datetimerange"
              :shortcuts="shortcuts"
              range-separator="到"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm"
              @change="searchList"
            />
          </div>
          <el-scrollbar class="left-list-scrollbar" v-if="isShow && leftTab == 1">
            <div
              class="content-list"
              v-infinite-scroll="infinite"
              v-if="dataList?.length"
            >
              <div
                v-for="(item, index) in dataList"
                :key="index"
                class="content-list-item"
                @click="updateDetail(item)"
                :style="
                  item.assistanceId == assistanceId
                    ? 'border-color: #409EFF; '
                    : ''
                "
              >
                <div class="list-item-top">
                  <span>
                    {{ parseTime(item.beginTime, '{m}月{d}日') }}
                    {{ weekName[new Date(item.beginTime).getDay()] }}
                  </span>
                  <span>
                    {{ parseTime(item.beginTime, '{y}年') }}
                  </span>
                </div>
                <div class="list-item-content"> 
                  <div class="list-item-content-text">
                    <div style="display: flex; flex-wrap: wrap">
                      <span
                        v-for="(items, indexs) in item.assistanceMemberList"
                        :key="indexs"
                      >
                        {{
                          items.nickName +
                          (indexs + 1 == item.assistanceMemberList.length
                            ? ''
                            : '、')
                        }}
                      </span>
                    </div>
                    <span>
                      发起人：{{ item.initiatorName ? item.initiatorName : '' }}
                    </span>
                    <span>
                      时间：{{
                        parseTime(item.beginTime, '{h}:{i}') +
                        ' ~ ' +
                        (item.endTime ? parseTime(item.endTime, '{h}:{i}') : '')
                      }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
            <div style="text-align: center" v-if="dataList?.length">
              <p v-if="more">Loading...</p>
              <p v-else>No more</p>
            </div>
            <div v-else class="list-empty">
              <el-empty description="暂无记录" />
            </div>
          </el-scrollbar>
          <div v-if="!isShow && leftTab == 1" class="list-empty">
            <el-empty description="暂无记录" />
          </div>
  
          <el-scrollbar
            class="left-list-scrollbar1"
            height="calc(100vh - 120px)"
            v-if="leftTab == 2"
          >
            <el-tree
              ref="treeRef"  
              lazy
             :load="HandleLoadNode"
              :filter-node-method="filterNode"
              highlight-current 
              :props="treeProps"
              style="width: 100%"
              @node-click="updateDetail"
            >
              <template #default="{ data }"> 
                <div class="tree-item">  
                    {{ data.name }} 
                </div>
              </template>
            </el-tree>
          </el-scrollbar>
        </div>
      </div>
    </div>
</template>

<script setup>
import {
//   getAssistanceList,
    getDirectories,
    getDirectoriesUsers
} from '@/api/coordinate.js'
import { nextTick, reactive, toRefs, watch, onMounted } from 'vue'

// 接收 props
const props = defineProps({
  loading: {
    type: Boolean,
    default: true,
  },
})

// 定义 emit
const emit = defineEmits(['updateDetail', 'updateTab'])

// state
const state = reactive({
  isFirst: true,
  leftTab: 2,
  queryFrom: {
    pageNum: 1,
    pageSize: 10,
    nickName: '',
    leftDatePicker: null,
  },
  leftListLoading: true,
  loading: false,
  dataList: [],
  more: false,
  isShow: false,
  shortcuts: [
    {
      text: '本周',
      value: () => {
        const now = new Date()
        const nowDaty = now.getDay()
        const start = new Date(now)
        start.setDate(now.getDate() - nowDaty)
        const end = new Date(start)
        end.setDate(start.getDate() + 6)
        return [start, end]
      },
    },
    {
      text: '最近三周',
      value: () => {
        const now = new Date()
        const nowDaty = now.getDay()
        let end = new Date(now)
        end.setDate(now.getDate() + (6 - nowDaty))
        const start = new Date(end)
        start.setDate(start.getDate() - 20)
        return [start, end]
      },
    },
    {
      text: '本月',
      value: () => {
        const now = new Date()
        const start = new Date(now.getFullYear(), now.getMonth(), 1)
        const end = new Date(now.getFullYear(), now.getMonth() + 1, 0)
        return [start, end]
      },
    },
  ],
  weekName: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
  treeRef: null,

  treeProps: {
    children: 'users',
    label: 'name',
    value: 'uid',
    isLeaf: (node) => {
        if(node.uid) return true
    },
    },
  assistanceId: '',
})

/**
 * 树状列表筛选
 */
const filterNode = (value, data) => { 
  if (!value) return true
  return data.name.includes(value)
}

/**
 * 搜索框变化
 */
const searchList = () => {
  if (state.leftTab == 1) {
    state.queryFrom.pageNum = 1
    state.dataList = []
    getList()
  } else {
    // console.log('treeRef.filter',state.treeRef)
    state.treeRef.filter(state.queryFrom.nickName)
  }
}

/**
 * 变更详情
 */
const updateDetail = (item) => { 
  if (state.leftTab == 1) {
    state.assistanceId = item.assistanceId
    emit('updateDetail', item)
  } else { 
    if (item.uid) { 
      emit('updateDetail', item)
    }
  }
}

/**
 * 触底加载
 */
// const infinite = () => {
//   if (state.more) {
//     state.queryFrom.pageNum++
//     getList()
//   }
// }

/**
 * 协作记录
 */
const getList = async () => {
  try {
    state.leftListLoading = true

    let query = structuredClone(state.queryFrom)
    if (query.leftDatePicker?.length) {
      query.beginSignTime = query.leftDatePicker[0]
      query.endSignTime = query.leftDatePicker[1]
    }
    delete query.leftDatePicker

    let infoData = await getAssistanceList({ ...query })

    state.dataList = infoData.rows.length
      ? state.dataList.concat(infoData.rows)
      : []

    if (state.isFirst) {
      emit('updateDetail', state.dataList.length ? state.dataList[0] : null)
      state.assistanceId = state.dataList.length
        ? state.dataList[0].assistanceId
        : ''
      state.isFirst = false
    }

    state.more = state.dataList.length < infoData.total
    state.isShow = Boolean(state.dataList.length)
    state.leftListLoading = false
  } catch (err) {
    console.log(err)
    state.leftListLoading = false
  }
}

/**
 * 通讯录  人员信息树
 */
const HandleLoadNode = async (node, resolve) => {   
    if(node?.level === 0){
        loadNode(resolve,'',node?.level)
    }else if(node?.level > 0){ 
        if(node.data.directory_uid){
            loadUserNode(resolve,node.data.directory_uid,node?.level)
        }else{
            resolve(resolve)
        }
        
    }
}

const loadNode = async(resolve,id,level)=>{
    try {
        state.leftListLoading = true  
        let res = await getDirectories({level:1})
        if(res.meta.code == 200){ 
            resolve(res.data)
        } 
        state.leftListLoading = false
    } catch (error) {
        console.log(error)
        state.leftListLoading = false
    }
}

const loadUserNode = async(resolve,id,level)=>{
    try {
        state.leftListLoading = true 
        let userData = []
        let orgData = []
        const resOrg  = await getDirectories({level: 1,parent_uuid:id})
        if(resOrg?.data){ 
            orgData = resOrg.data
        }
        if(id){
            const res = await getDirectoriesUsers(id,{directory_uuid:id})
            userData = res.data 
        } 
        resolve([...orgData, ...userData]) 
        state.leftListLoading = false
    } catch (error) {
        console.log(error)
        state.leftListLoading = false
    }
}

//   try {  
//     if (userList.data.sub_units?.length) {
//       state.dataList = userList.data.sub_units
//       let user = getUser(state.dataList)
//       emit('updateDetail', user) 
//     } else {
//       emit('updateDetail', null)
//     }
//     state.leftListLoading = false
//   } 



const getUser = (list) => {
  for (let i = 0; i < list.length; i++) {
    if (list[i].type == 2) {
      return list[i]
    } else if (list[i].children?.length) {
      let user = getUser(list[i].children)
      if (user != null) {
        return user
      }
    }
  }
}

/**
 * 监听 props.loading
 */
watch(
  () => props.loading,
  (newValue) => {
    state.loading = newValue
  }
)

/**
 * 监听 tab 切换
 */
watch(
  () => state.leftTab,
  (newValue) => {
    emit('updateTab', newValue)
    state.dataList = []
    state.isFirst = true
    state.queryFrom = {
      pageNum: 1,
      pageSize: 10,
      nickName: '',
      leftDatePicker: null,
    }

    if (newValue == 1) {
      state.isShow = false
    //   getList()
    } else {
        HandleLoadNode()
    }
  }
)

onMounted(() => {
  state.dataList = []
  state.isFirst = true
//   getList()
})

/**
 * 暴露给模板
 */
const { 
  isFirst, leftTab, queryFrom, leftListLoading, loading,
  dataList, more, isShow, shortcuts, weekName,
  treeRef, treeProps, assistanceId
} = toRefs(state)
</script>


<style lang="scss" scoped>
.flex {
  display: flex;
  justify-content: center;
  align-items: center;
}

.left-list {
  display: flex;
  height: calc(100vh - 40px);

  .list-tab {
    @extend .flex;
    justify-content: flex-start;
    flex-direction: column;
    margin-right: 6px;

    .list-tab-item {
      width: 50px;
      height: 50px;
      cursor: pointer;

      img {
        width: 40px;
        height: 40px;
      }
    }
  }
  .list-content {
    @extend .flex;
    justify-content: flex-start;
    flex-direction: column;
    width: calc(100% - 56px);
    box-shadow: 0px 5px 15px 0px rgba(153, 153, 153, 0.3);

    .content-top-input {
      @extend .flex;
      width: 100%;
      height: 50px;
      padding: 6px 20px;
      background: #666666;
    }

    .content-datapicker {
      width: 100%;
    }

    .left-list-scrollbar {
      width: 100%;
      height: calc(100vh - 170px);
      padding: 15px 0;
    }

    .left-list-scrollbar1 {
      width: 100%;
      height: calc(100vh - 120px);
      margin: 15px 0;
    }

    .content-list {
      width: 100%;
      padding: 0 15px;
    }

    .content-list-item {
      width: 100%;
      margin-bottom: 15px;
      background: #f5f7fa;
      border: 1.5px solid #c9d4e6;
      cursor: pointer;

      .list-item-top {
        @extend .flex;
        justify-content: space-between;
        width: 100%;
        height: 50px;
        padding: 0 13px;
        background: #c9d4e6;

        span {
          color: #333333;
          font-size: 16px;
        }
      }

      .list-item-content {
        @extend .flex;
        justify-content: flex-start;
        align-items: flex-start;
        padding: 13px;
        background: #f5f7fa;

        img {
          width: 27px;
          height: 27px;
          border-radius: 50%;
          margin-right: 10px;
        }

        .list-item-content-text {
          @extend .flex;
          flex-direction: column;
          align-items: flex-start;

          div {
            @extend .flex;
            justify-content: flex-start;

            span {
              margin: 0;
              color: #333;
              font-size: 16px;
            }
          }

          span {
            display: inline-block;
            margin-top: 6px;
            color: #999;
            font-size: 14px;
          }
        }
      }
    }
  }
}
.list-empty {
  @extend .flex;
  width: 100%;
  height: calc(100vh - 170px);
}

.tree-item {
  @extend .flex;
  justify-content: flex-start;
  height: 45px;
  font-size: 18px;


  .tree-item-img1 {
    width: 22px;
    height: 22px;
  }

  .tree-item-text1 {
    margin-left: 10px;
    color: #333333;
    font-size: 18px;
    font-weight: 600;
  }
  .tree-item-text2 {
    color: #333333;
    font-size: 18px;
  }
  .tree-item-text3 {
    margin-left: 15px;
    color: #999999;
    font-size: 18px;
  }
}

::v-deep .el-tree-node__content {
  @extend .flex;
  justify-content: flex-start;
  height: 45px;
}

::v-deep .list-content .el-input__wrapper {
  height: 38px;
  border-radius: 19px;
}

::v-deep .content-datapicker .el-date-editor {
  width: 100%;
  height: 50px;
  background: #e6f1ff;
  border-radius: 0;
  border: none;
  box-shadow: none;
}

::v-deep .left-list-scrollbar .el-scrollbar__wrap {
  height: calc(100vh - 170px);
}

::v-deep .left-list-scrollbar1 .el-scrollbar__wrap {
  height: calc(100vh - 120px);
}
</style>