<template>
  <!-- 搜索 -->
  <div class="search-one" v-if="showType == 1">
    <div style="text-align: right;" class="search-input">
      <el-input v-model="queryParams.mobile" placeholder="用户手机号" clearable @keyup.enter="handleQuery">
        <template #suffix>
          <Icon class="mr-5px" icon="ep:search" @click="handleQuery" style="cursor: pointer;" />
        </template>
        <template #append>
          <el-button :icon="Operation" @click="showSearchMore" />
        </template>
      </el-input>
    </div>
  </div>
  <div class="search-one" v-else>
    <div style="text-align: right;" class="search-input">
      <el-input v-model="treeParams.mobile" placeholder="用户手机号" clearable @keyup.enter="treeHandleQuery">
        <template #suffix>
          <Icon class="mr-5px" icon="ep:search" @click="treeHandleQuery" style="cursor: pointer;" />
        </template>
        <template #append>
          <el-button :icon="Operation" @click="showSearchMore" />
        </template>
      </el-input>
    </div>
  </div>
  <div style="width: 100%;position: relative;">
  <div class="searchMore" v-show="searchMoreShow" :style="{ width: (mobile ? '88.7%' : '96%') }">
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="108px" @submit.prevent="handleFormSubmit">
      <template v-if="showType == 1">
        <el-form-item label="用户昵称" prop="name">
          <el-input
v-model="queryParams.nickName" placeholder="请输入用户昵称"  clearable @keyup.enter="handleQuery"
            class="!w-240px" />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input
v-model="queryParams.username" placeholder="请输入用户名"  clearable @keyup.enter="handleQuery"
            class="!w-240px" />
        </el-form-item>
      </template>
      <template v-else>
        <el-form-item label="用户昵称" prop="mobile">
            <el-input
v-model="treeParams.nickName" placeholder="请输入用户昵称" clearable @keyup.enter="treeHandleQuery"
              class="!w-240px" />
        </el-form-item>
        <el-form-item label="用户名" prop="name">
          <el-input
v-model="queryParams.username" placeholder="请输入用户名"  clearable @keyup.enter="handleQuery"
            class="!w-240px" />
        </el-form-item>
      </template>
      <el-row>
        <el-col>
          <el-form-item>
            <el-button @click="hideSearchMore">
              收起
            </el-button>
            <el-button @click="handleQuery" v-if="showType == 1">
              <Icon icon="ep:search" class="mr-5px" /> 搜索
            </el-button>
            <el-button @click="treeHandleQuery" v-else>
              <Icon icon="ep:search" class="mr-5px" /> 搜索
            </el-button>
            <el-button @click="resetQuery" v-if="showType == 1">
              <Icon icon="ep:refresh" class="mr-5px" /> 重置
            </el-button>
            <el-button @click="treeResetQuery" v-if="showType == 2">
              <Icon icon="ep:refresh" class="mr-5px" /> 重置
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</div>
  
  <el-tabs v-model="showType" @tab-click="handleTabClick" class="parent-tabs" v-if="isAdmin">
    <el-tab-pane label="列表模式" :name="1" />
    <el-tab-pane label="树状图" :name="2" />
  </el-tabs>


  <!-- 列表 -->
  <ContentWrap style="margin-top:10px;padding: 10px;" v-if="showType == 1">
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="头像" align="center" prop="ancName">
          <template #default="scope">
            <span><img :src="scope.row.avatar"  style="width: 50px;height: 50px;border-radius: 50%;border: 1px solid rgb(220, 223, 231);" /></span>
          </template>
        </el-table-column>
      <el-table-column label="用户昵称" align="center" prop="nickName" />
      <el-table-column label="用户名" align="center" prop="username" />
      <el-table-column label="用户手机号" align="center" prop="mobile" />
      <el-table-column label="推荐人姓名" align="center" prop="ancNickName" />
      <el-table-column label="推荐人用户名" align="center" prop="ancUsername" />
      <el-table-column label="直推人列表" align="center" prop="descendantCount">
        <template #default="scope">
          <span @click="getUserAllSon(1, scope.row)" style="cursor: pointer;display: inline-block;width: 100%;">{{
            scope.row.descendantCount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="后代列表" align="center" prop="childrenCount">
        <template #default="scope">
          <span @click="getUserAllSon(2, scope.row)" style="cursor: pointer;display: inline-block;width: 100%;">{{
            scope.row.childrenCount }}</span>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
:total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList(queryParams)" />
  </ContentWrap>

  <ContentWrap style="margin-top:10px;padding: 10px;" v-if="showType == 2">
    <div style="display: none;">{{ treeList }}</div>
    <Echart :height="650" @chart-init="handleChartInit" :options="treeOptions" />
  </ContentWrap>
  <!-- 表单弹窗：添加/修改 -->
  <Descendants ref="formRef" @success="getList" />
</template>

<script setup lang="ts">

import { SharePathApi, SharePathVO } from '@/api/system/distri/sharepath'
import { DuserApi } from '@/api/system/distri/duser'
import { EChartsOption } from 'echarts'
import Descendants from './Descendants.vue'
import { TabsPaneContext } from 'element-plus'
import {  Operation } from '@element-plus/icons-vue'
import { useAppStore } from '@/store/modules/app'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
const appStore = useAppStore()
const mobile = computed(() => appStore.getMobile)
const searchMoreShow = ref(false)
const props = defineProps({
  userId: {
    type: Number,
    default: 0
  }
})
const { wsCache } = useCache()
const user = wsCache.get(CACHE_KEY.USER)
const isAdmin = computed(() => {
  return user.user.id  === 1;
})

console.log(user.user.nickname && user.user.id)
// 打开更多搜索条件
const showSearchMore = () => {
  searchMoreShow.value = !searchMoreShow.value
}
const hideSearchMore = () => {
  searchMoreShow.value = false
}
const showType = ref(1)
/** 切换 Tab */
const handleTabClick = (tab: TabsPaneContext) => {
  showType.value = tab.paneName as number
  if(showType.value == 1){
    getList(queryParams)
  }else{
    treeParams.userId= props.userId || 1;
    getList(treeParams)
  }
}
/** 分销用户关系 列表 */
defineOptions({ name: 'SharePath' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<SharePathVO[]>([]) // 列表的数据
let treeList = ref([]) // 树形结构的数据
// 列表的总页数
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  mobile:undefined,
  nickName:undefined,
  username:undefined
})
const queryFormRef = ref() // 搜索的表单
const treeParams = reactive({
  userId: 1,
  nickName:undefined,
  mobile:undefined,
  maxDepth: 50,
  username:undefined
}) // 树形组件的参数
/** 查询列表 */
const getList = async (Params) => {
  loading.value = true
  if (showType.value == 1) {
    // 如果是1的话就是查默认结构
    try {
      const data = await DuserApi.getDuserPage(Params)
      list.value = data.list
      total.value = data.total
    } finally {
      loading.value = false
    }
  } else if (showType.value == 2) {
    // 如果是2的话就是查树结构
    try {
        
      const data = await SharePathApi.getSharePathPageTree(Params)
      // 处理数据以确保所有节点都有有效名称
      treeList.value = [extractRelevantData(data)]
      // 更新树形组件的选项
      treeOptions.series[0].data = treeList.value;
      treeOptions = { ...treeOptions };
      
      
    } finally {
      loading.value = false
    }
  }
}
/** 查看后代 */
const formRef = ref()
const getUserAllSon = async (type,row) => {
  formRef.value.open(type,row.userId,row.childrenCount)
}
function handleFormSubmit(event) {
    event.preventDefault();
   
  }
/** 搜索按钮操作 */
const handleQuery = (event = undefined) => {
  event.preventDefault();
  queryParams.pageNo = 1;
  getList(queryParams);
}
// 通过搜索来查找树节点
const getParamsList =async (treeParams) => {
  treeParams.userId = undefined;
  treeParams.maxDepth = 5;
  const data = await SharePathApi.getTreeByNameOrMobile(treeParams)
      // 处理数据以确保所有节点都有有效名称
  treeList.value = [extractRelevantData(data)]
  // treeList.value = data
  // 更新树形组件的选项
  treeOptions.series[0].data = treeList.value;
  treeOptions = { ...treeOptions };
}

/** 搜索按钮操作 */
const treeHandleQuery = (event) => { 
  event.preventDefault();
    if(!treeParams.nickName && !treeParams.mobile){
        getList(treeParams)
         return false
    }
    getParamsList(treeParams)
}
/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.mobile = undefined
  queryParams.nickName = undefined
  queryParams.username = undefined
  handleQuery()
  hideSearchMore()
}
/** 树重置按钮操作 */
const treeResetQuery = () => {
  treeParams.userId= props.userId || 1;
  treeParams.nickName=undefined;
  treeParams.mobile=undefined;
  getList(treeParams);
  hideSearchMore()
}

// 树的默认展开深度n层写死
const TreeDepth = 100000000
let treeOptions: EChartsOption = {
  tooltip: {
    trigger: 'item',
    triggerOn: 'mousemove',
    formatter: function (params) {
        // 使用 nickname 而不是 name
        return `${params.data.nickname}`;
    }
  },
  dataZoom: {
    type: 'inside'
  },
  series: [
    {
      type: 'tree',
      data: [],
      left: '2%',
      right: '2%',
      top: '8%',
      bottom: '20%',
      orient: 'vertical',
      initialTreeDepth: TreeDepth,
      expandAndCollapse: true,
      label: {
        position: 'bottom',
        // rotate: -90,
        verticalAlign: 'middle',
        align: 'center',
        fontSize: 14,
        padding:10,
        formatter: function (params) {
            // 使用 nickname 而不是 name
            return `${params.data.nickname}`;
        }
      },
      zoom: 1, //当前视角的缩放比例
      roam: true, //是否开启平游或缩放
      scaleLimit: { //滚轮缩放的极限控制
        min: 0.1,
        max: 100
      },
      leaves: {
        label: {
          position: 'bottom',
          // rotate: -90,
          verticalAlign: 'middle',
          align: 'center',
          fontSize: 14,
        }
      },
      animationDurationUpdate: 750,
      symbolSize:3,
    }
  ]
}

// 处理返回来的树中name为null或者undefined的情况
const extractRelevantData = (node) => {
    // console.log(node)
    if (node.name === null) {  // 如果节点名称为null，则设置为默认名称
        node.name = '未命名节点';
    }
    // node.symbol = 'circle';

    // node.symbol = 'image://https://mall-ffkj.oss-cn-guangzhou.aliyuncs.com/bb87e16579c886ed94a70081d14e6aa1b1924b7435f57ed1e195c39b33593312.png'

    
    if (node.children && node.children.length > 0) {
        // 如果存在子节点，并且子节点数组不为空，则递归处理每个子节点
        node.children = node.children.map(child => extractRelevantData(child));
        // 根据sort属性对子节点进行排序
        node.children.sort((a, b) => a.sort - b.sort);
    } else {
        node.children = [];  // 确保每个节点都有 children 属性，即使它是空的
    }
    return node;
}
const chartInstance = ref(null);
// 当echants组件初始化之后 返回一个echarts实例
const handleChartInit = (instance) =>{
  // 复制chartInstance
  chartInstance.value = instance;
  // 绑定点击事件
  if (chartInstance.value) {
    chartInstance.value.on('click', function(params) {
      if (params.componentType === 'series') {
        // console.log(params);
        // 检查当前节点的层级
        if (!params.data.children.length) {
            loadMoreData(params.data);
        }
    }
    });
  }
}

//加载更多数据
async function loadMoreData(node) {

    if(!node.userId){
      return
    }
    treeParams.userId = node.userId;
    let additionalData = await SharePathApi.getSharePathPageTree(treeParams);
    if (additionalData && additionalData.children.length > 0) {
        const resultNode = findNodeByUserId(treeList.value[0], node.userId)
        if (resultNode) {
            // 找到节点
            resultNode.children = additionalData.children;
        } else {
            console.log("没有找到匹配的节点");
        }
    }
    console.log(treeList.value[0]);
}
function findNodeByUserId(node, userId) {
    // 检查当前节点的 userId 是否匹配
    if (node.userId === userId) {
        return node; // 返回找到的节点
    }
    // 如果当前节点有子节点，递归搜索每一个子节点
    if (node.children && node.children.length > 0) {
        for (let child of node.children) {
            const found = findNodeByUserId(child, userId);
            if (found) {
                return found; // 如果找到匹配的子节点，返回该节点
            }
        }
    }
    return null; // 如果当前节点和所有子节点都不匹配，返回 null
}

/** 初始化 **/
onMounted(async() => {
  // 如果能拿到props.userId的话 说明是查看某个用户的关系
  // 否则就是查看默认结构
  // 如果是查看某个用户的关系的话 需要把userId传给queryParams
  // 如果是查看树结构的话 需要把userId传给treeParams
  if(props.userId){
    console.log("props.userId",props.userId)
    queryParams.userId = props.userId
    treeParams.userId = props.userId
  }
  console.log("treeParams",treeParams)
  await getList(queryParams)


})
</script>
<style src="@/styles/SearchIndex.css"  lang="scss" scoped></style>
<style scoped>
.parent-tabs {
  width: 150px;
  margin-bottom: 10px;
}

::v-deep .el-tabs__nav-wrap::after {
  position: static !important;
}

::v-deep .el-tabs__header {
  margin: 0;
}

::v-deep .el-tabs__active-bar {
  background-color: unset;
}

::v-deep .el-tabs__item {
  padding: 0 6px !important;
  margin: 0 6px;
  box-sizing: border-box;
}

::v-deep .el-tabs__item.is-active {
  color: var(--el-color-primary);
  border-bottom: 2px solid var(--el-color-primary);
}
</style>