<template>
  <div>
    <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"
          check-strictly
          style="width: 400px"
          @change="getOkrList"
        />
        <el-button class="ml-10px" type="primary" @click="handleAddNode">新建节点</el-button>
      </el-row>
      <el-row>
        <el-button type="info" @click="handleShowOkr(searchForm.nodeId)"> 节点详情 </el-button>
        <el-button type="warning" @click="handleEditOkr(searchForm.nodeId)">
          修改当前节点
        </el-button>
        <el-button type="success" @click="handleUpdateProcess">更新进度</el-button>
      </el-row>
    </div>

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

<script setup name="AllTarget">
import OkrTable from './OkrTable.vue'
import DialogOkrInfo from './DialogOkrInfo.vue'
import DialogOkr from './DialogOkr.vue'

import { getAllNodeTree, getAllOkrPage } from '@/api/okr/okr'
import { listToTree } from '@/utils/tree'

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() {
  getAllNodeTree().then((resp) => {
    peroidList.value = listToTree(resp.tree, {
      id: 'nodeId',
      pid: 'parentId',
      children: 'children'
    })
    searchForm.value.nodeId = resp.nodeId
    getOkrList()
  })
}

function getOkrList() {
  getAllOkrPage(searchForm.value).then((resp) => {
    const list = resp
    nextTick(() => {
      okrTableRef.value.prepareData(list)
    })
  })
}

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

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

function handleUpdateProcess() {
  message.success('更新进度成功')
  getOkrList()
}

const dialogOkr = ref(null)
function handleShowOkr(id) {
  dialogOkr.value.open(id)
}
</script>

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