<template>
    <hc-dialog v-model="isShow" widths="500px" is-footer-center is-table title="关联试验划分树" @close="dialogClose">
        <el-alert :closable="false" title="勾选试验划分节点，被勾选的节点数据将会汇总到当前台账分类中" type="warning" />
        <el-form ref="formRef" :model="formModel" :rules="formRules" label-position="top" label-width="auto" class="mt-14px">
            <el-form-item label="项目名称：" prop="pid">
                <el-select v-model="formModel.pid" filterable block placeholder="请选择项目" @change="formNameChange">
                    <el-option v-for="item in projectData" :key="item.id" :label="item.projectName" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="树搜索关键词：">
                <hc-search-input v-model="filterText" placeholder="输入关键字搜索" />
            </el-form-item>
            <el-form-item label="树数据：">
                <hc-data-tree ref="treeRef" :h-props="treeProps" show-checkbox :datas="treeData" :search-val="filterText" :default-checked-keys="defaultCheckedKeys">
                    <template #name="{ data }">
                        <span class="text-16px font-400">{{ data.title }}</span>
                    </template>
                </hc-data-tree>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button hc-btn @click="dialogClose">取消</el-button>
            <el-button hc-btn type="primary" :loading="submitLoading" @click="dialogSubmit">提交</el-button>
        </template>
    </hc-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { formValidate, getArrValue, isNullES } from 'js-fast-way'
import projectApi from '~api/project/project'
import mainApi from '~api/desk/test-collect'

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

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

//双向绑定
// eslint-disable-next-line no-undef
const isShow = defineModel('modelValue', {
    default: false,
})
const defaultCheckedKeys = ref([])
//监听可否编辑
const dataInfo = ref(props.data)
watch(() => props.data, (data) => {
    dataInfo.value = data
    console.log( dataInfo.value, '  dataInfo.value')
    
  
}, { immediate: true, deep: true })

//监听显示
watch(isShow, () =>{
     getDataApi()
     const { trialTreeIds } = dataInfo.value
 if (isShow.value && trialTreeIds) {
    defaultCheckedKeys.value = trialTreeIds.split(',')
 }

    })
const getDataApi = () => {
    console.log(dataInfo.value)
    getProjectData()
   
}

//项目列表
const projectData = ref([])
const getProjectData = async () => {
    const { data } = await projectApi.page({
        current: 1, size: 9999,
    })
    projectData.value = getArrValue(data?.records)
}

//项目列表被选择
const formNameChange = () => {
    const item = projectData.value.find(item=>item.id === formModel.value?.pid)
    const pid = !isNullES(item) ? item.referenceWbsTemplateIdTrial : null
    getTreeData(formModel.value?.pid, pid)
}

//表单
const formRef = ref(null)
const formModel = ref({})
const formRules = {
    pid: { required: true, trigger: 'blur', message: '请选择项目' },
}

//获取树数据
const treeData = ref([])
const getTreeData = async (id, pid) => {
    const { data } = await projectApi.findProjectTree({ projectId: id, wbsId: pid })
    treeData.value = getArrValue(data)
}

//树配置
const treeRef = ref(null)
const filterText = ref('')
const treeProps = {
    label: 'title',
    children: 'children',
    isLeaf: (item) => {
        let tag = false
        if (!item.hasChildren) {
            tag = true
        }
        if (Number(item.isExistForm) === 1) {
            tag = true
        }
        return tag
    },
}


//提交表单
const submitLoading = ref(false)
const dialogSubmit = async () => {
    const isForm = await formValidate(formRef.value)
    if (!isForm) return
    const checkIds = treeRef.value?.treeRef?.getCheckedKeys()
    if (checkIds.length <= 0) {
        window.$message.warning('请先勾选关联的树节点')
        return
    }
    submitLoading.value = true
    let ids = checkIds.join(',')
    const { isRes } = await mainApi.matching({
        classId: dataInfo.value.id,
        ids: ids,
    })
    submitLoading.value = false
    if (!isRes) return
    window.$message.success('操作成功')
    dialogClose()
    emit('finish')
}

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