<template>
  <div class="h-full flex flex-col">
    <div class="flex items-center justify-between">
      <el-row>
        <el-tree-select
          v-model="searchForm.nodeId"
          :data="peroidList"
          :props="defaultProps"
          :render-after-expand="false"
          :default-expand-all="false"
          style="width: 400px"
          @change="nodeChange"
        />
      </el-row>
      <el-row>
        <el-button type="info" @click="handleShowOkr(searchForm.nodeId)"> 节点详情 </el-button>
        <el-button
          type="warning"
          v-if="currentUserId == searchForm.creatorId"
          @click="handleEditOkr(searchForm.nodeId)"
        >
          修改当前节点
        </el-button>
      </el-row>
    </div>

    <OkrTable ref="okrTableRef" canEdit />
    <DialogOkr ref="dialogOkr" @edit="handleEditOkr" />
    <DialogOkrInfo ref="dialogOkrInfo" @success="handleSearchPeroid" />
  </div>
</template>

<script setup name="MySon">
import OkrTable from './OkrTable.vue'
import DialogOkr from './DialogOkr.vue'
import DialogOkrInfo from './DialogOkrInfo.vue'
import { listToTree, findNode } from '@/utils/tree'
import { useUserStore } from '@/store/modules/user'

import { getMySonNodeTree, getMySonOkrPage } from '@/api/okr/okr'

const props = defineProps({
  userId: {
    type: Number,
    default: undefined
  }
})

const defaultProps = {
  value: 'nodeId',
  label: 'nodeName',
  children: 'children'
}

const userStore = useUserStore()
const currentUserId = userStore.getUser.id

const okrTableRef = ref(null)
const searchForm = ref({
  nodeId: undefined
})

const peroidList = ref([])

handleSearchPeroid()

function handleSearchPeroid() {
  getMySonNodeTree({ userId: props.userId }).then((resp) => {
    peroidList.value = listToTree(resp?.tree || [], {
      id: 'nodeId',
      pid: 'parentId',
      children: 'children'
    })
    nodeChange(resp.nodeId)
  })
}

function getOkrList() {
  getMySonOkrPage({
    ...searchForm.value,
    userId: props.userId
  }).then((resp) => {
    if (resp && resp.length > 0) {
      nextTick(() => {
        okrTableRef.value.prepareData(resp)
      })
    } else {
      // 如果没有数据，清空表格
      okrTableRef.value.prepareData([])
    }
  })
}

function nodeChange(nodeId) {
  searchForm.value.nodeId = nodeId
  getOkrList()
  const currentNode = findNode(peroidList.value, (node) => {
    return node.nodeId == nodeId
  })
  searchForm.value.creatorId = currentNode.creatorId
}

const dialogOkr = ref(null)
function handleShowOkr(id) {
  dialogOkr.value.open({
    nodeId: id,
    canEdit: true,
    queryType: 2
  })
}

const dialogOkrInfo = ref(null)
function handleEditOkr(nodeId = undefined) {
  dialogOkr.value.close()
  dialogOkrInfo.value.open('update', nodeId || searchForm.value.nodeId, 2)
}
</script>

<style lang="scss" scoped>
:deep(.el-overlay-dialog) {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
