<template>
    <hc-dialog v-model="isShow" title="调整排序" widths="800px" is-table @close="dialogClose">
        <hc-table
            ref="tableRef" :column="tableColumn" :datas="tableData" is-row-drop is-sort
            quick-sort @row-drop="rowDropTap" @row-sort="rowSortTap"
        />
        <template #footer>
            <el-button hc-btn @click="dialogClose">取消</el-button>
            <el-button hc-btn type="primary" :disabled="tableData.length <= 0" :loading="submitLoading" @click="dialogSubmit">提交</el-button>
        </template>
    </hc-dialog>
</template>

<script setup>
import { nextTick, ref, watch } from 'vue'
import { getArrValue, getObjValue } from 'js-fast-way'
import mainApi from '~api/project/tree'

const props = defineProps({
    data: {
        type: Object,
        default: () => ({}),
    },
})

//事件
const emit = defineEmits(['finish', 'close'])

//双向绑定
const isShow = defineModel('modelValue', {
    default: false,
})

//监听可否编辑
const datas = ref(props.data)
watch(() => props.data, (val) => {
    datas.value = getObjValue(val)
}, { immediate: true, deep: true })

//监听显示
watch(isShow, (val) => {
    if (val) getDataApi()
})

//表格
const tableRef = ref(null)
const tableColumn = [{ key: 'nodeName', name: '表名' }]
const tableData = ref([])

//处理数据
const getDataApi = async () => {
    const { id } = getObjValue(datas.value)
    const { data } = await mainApi.getSameGradeNode({ id })
    tableData.value = getArrValue(data)
}

// 行拖拽
const rowDropTap = (rows) => {
    tableData.value = [] // 先清空，否则排序会异常
    nextTick(() => {
        tableRef.value?.setData(rows)
    })
}

// 点击排序
const rowSortTap = (rows) => {
    tableData.value = [] // 先清空，否则排序会异常
    nextTick(() => {
        tableData.value = rows
    })
}

//提交
const submitLoading = ref(false)
const dialogSubmit = async () => {
    submitLoading.value = true
    const { isRes } = await mainApi.submitTreeSort(tableData.value)
    submitLoading.value = false
    if (!isRes) return
    window.$message.success('保存成功')
    dialogClose()
    emit('finish')
}

//关闭弹窗
const dialogClose = () => {
    isShow.value = false
    submitLoading.value = false
    tableData.value = []
    emit('close')
}
</script>
