<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="getOkrList"
        />
      </el-row>
      <el-row>
        <el-button type="info" @click="handleShowOkr(searchForm.nodeId)"> 节点详情 </el-button>
        <el-button type="success" @click="handleUpdateProcess">更新进度</el-button>
      </el-row>
    </div>

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

<script setup name="MyDuty">
import OkrTable from './OkrTable.vue'
import DialogOkrInfo from './DialogOkrInfo.vue'
import DialogOkr from './DialogOkr.vue'
import { listToTree } from '@/utils/tree'

import { getMyNodeTree, getMyOkrPage } from '@/api/okr/okr'

const message = useMessage()

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

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

const peroidList = ref([])

// onMounted(() => {
handleSearchPeroid()
// })

function handleSearchPeroid() {
  getMyNodeTree().then((resp) => {
    peroidList.value = listToTree(resp?.tree || [], {
      id: 'nodeId',
      pid: 'parentId',
      children: 'children'
    })
    searchForm.value.nodeId = resp.nodeId
    getOkrList()
  })
}

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

const dialogOkrInfo = ref(null)
// function handleAddNode() {
//   dialogOkrInfo.value.open('create', null)
// }

function handleEditOkr(nodeId = undefined) {
  dialogOkr.value.close()
  dialogOkrInfo.value.open('update', nodeId || searchForm.value.nodeId, 1)
}

function handleUpdateProcess() {
  okrTableRef.value.updateProcess(searchForm.value.nodeId).then(() => {
    message.success('更新成功')
    getOkrList()
  })
}

const dialogOkr = ref(null)
function handleShowOkr(id) {
  dialogOkr.value.open({
    nodeId: id,
    canEdit: true,
    queryType: 1
  })
}
</script>

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