<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" v-if="leftTab == 1">
            <!-- <el-input
              v-model="queryFrom.nickName"
              placeholder="搜索成员"
              type="text"
              prefix-icon="Search"
              @change="searchList"
            /> -->
            <el-select
                v-model="participant_user"
                multiple
                filterable
                clearable
                remote
                reserve-keyword
                placeholder="搜索成员"
                :remote-method="remoteMethod"
                :loading="loading" 
                collapse-tags
                collapse-tags-tooltip
                style="width: 100%" 
                @change="searchList"
            >
                <el-option
                    v-for="item in userList"
                    :key="item.uid"
                    :label="item.name"
                    :value="item.uid"
                    />
            </el-select>
          </div>
          <div class="content-top-input" v-if="leftTab == 2">
            <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"
            >
            <!-- @click="updateDetail(item)" -->
              <div
                v-for="(item, index) in dataList"
                :key="index"
                class="content-list-item"
                @click="updateDetail(item)"
                :style="
                  item.id == assistanceId
                    ? 'border-color: #409EFF; '
                    : ''
                "
              >
                <div class="list-item-top">
                  <span>
                    {{ parseTime(item.created_at, '{m}月{d}日') }}
                    {{ weekName[new Date(item.created_at).getDay()] }}
                  </span>
                  <span>
                    {{ parseTime(item.created_at, '{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.all_participants"
                        :key="indexs"
                      >
                        {{
                          (items.display_name || items.user_uid) +
                          (indexs + 1 == item.all_participants.length
                            ? ''
                            : '、')
                        }}
                      </span>
                    </div>
                    <span>
                      发起人：{{ item.all_participants.find(item => item.participant_role == 'moderator')?.display_name || ''}}
                    </span>
                    <span>
                      时间：{{
                        parseTime(item.created_at, '{h}:{i}') +
                        ' ~ ' +
                        (item.updated_at ? parseTime(item.updated_at, '{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,
    getParticipantsHistoryApi,
    getDirectories,
    getDirectoriesUsers,
    getInfo,
} from '@/api/coordinate.js'
import { nextTick, reactive, toRefs, watch, onMounted } from 'vue'
import { deepClone,parseTime ,createThrottle} from '@/utils/ruoyi.js'
import { getUserInfo } from '@/utils/auth.js'

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

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

// state
const state = reactive({
  isFirst: true,
  leftTab: 1,
  queryFrom: {
    page_size: 10,
    page: 1,
    nickName: '',
    leftDatePicker: null, 
    participant_user_uids:''
  },
  participant_user:[],
  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: '',
  userList:[],  
})  
// state.loading = true;
const remoteMethod = createThrottle(async (query) => {
    if (!query || query.trim() === '') {
        state.userList = [];
        return;
    }  
    try {
        const res = await getInfo(query, { search_type: 'name' });
        state.userList = res.data || [];
    } catch (error) {
        console.error('搜索用户失败:', error);
        state.userList = [];
    }  
}, 500);

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

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

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

/**
 * 触底加载
 */
const infinite = () => { 
    console.log('外面的加载')
  if (state.more) {
    console.log(state.more,'state.more执行了')
    state.queryFrom.page++
    getList()
  }
}

/**
 * 协作记录
 */
const getList = async () => {
  try { 
    state.leftListLoading = true 
    let query = deepClone(state.queryFrom)
    // if (query.leftDatePicker?.length) { 
    //   query.beginSignTime = query.leftDatePicker[0]
    //   query.endSignTime = query.leftDatePicker[1]
    // }

    if (query.leftDatePicker?.length) { 
        const startTime = new Date(query.leftDatePicker[0]);
        const endTime = new Date(query.leftDatePicker[1]);
        
        // 添加日期有效性验证
        if (!isNaN(startTime.getTime())) {
            query.start_time = Math.floor(startTime.getTime());
        } else {
            console.error('开始时间格式无效:', query.leftDatePicker[0]);
            query.start_time = '';
        }
        
        if (!isNaN(endTime.getTime())) {
            query.end_time = Math.floor(endTime.getTime());
        } else {
            console.error('结束时间格式无效:', query.leftDatePicker[1]);
            query.end_time = '';
        }
    }

    delete query.leftDatePicker 
    const userData = await getUserInfo() 
    if(!userData) return 
    let infoData = await getParticipantsHistoryApi( userData?.uid ,{ ...query })  
    state.dataList = infoData.data.history?.length
      ? state.dataList.concat(infoData.data.history)
      : []

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

    state.more = state.dataList?.length < infoData.data.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
    }
}  

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 = {
      page_size: 10,
      page: 1,
      nickName: '',
      participant_user_uids:'',
      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,userList,participant_user
} = 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>