<template>
    <hc-dialog
        v-model="isShow"
        widths="40rem"
        ui="hc-association-list-box"
        is-table
        title="关联清表"
        is-footer-center
        @close="dialogClose"
    >
        <el-form
            ref="formRef"
            :model="formModel"
            label-position="top"
            label-width="auto"
        >
            <el-form-item label="清表模版：">
                <el-select
                    v-model="formModel.name"
                    placeholder="请选择清表模版"
                    filterable
                    block
                    @change="nameChange"
                >
                    <el-option
                        v-for="item in excelData"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="请输入需要选择的内容：">
                <el-input
                    v-model="formModel.search"
                    placeholder="请输入需要选择的内容"
                />
            </el-form-item>
        </el-form>
        <div v-loading="isLoading" class="hc-association-list-tree-box">
            <el-scrollbar>
                <el-tree
                    ref="treeRef"
                    :filter-node-method="filterNode"
                    class="filter-tree"
                    :props="tabTreeProps"
                    :data="tabTreeData"
                    node-key="id"
                    accordion
                    show-checkbox
                    @check="checkChange"
                />
            </el-scrollbar>
        </div>
        <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 { deepClone, getArrValue, isNullES } from 'js-fast-way'
import excelApi from '~api/exctab/exceltab'
import testApi from '~api/desk/test-collect'

const props = defineProps({
    info: {
        type: Object,
        default: () => ({}),
    },
    type: {
        type: [String, Number],
        default: '', //默认没有，独立表单库类型为2,试验关联清表3
    },
})

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

//双向绑定
// eslint-disable-next-line no-undef
const isShow = defineModel('modelValue', {
    default: false,
})

//监听数据
const rows = ref(props.info)
const type = ref(props.type)

watch(
    () => [props.info, props.type],
    ([info, tpe]) => {
        rows.value = info
        type.value = tpe
    },
    { deep: true },
)

//监听显示
watch(isShow, (val) => {
    if (val) {
        getDataInfo()
    } else {
        emit('close')
    }
})

//表单
const formRef = ref(null)
const formModel = ref({})
const getDataInfo = () => {
    const form = deepClone(rows.value)
    getExcelListData()
    formModel.value = {
        id: type.value === 2 ? form.primaryKeyId : form.pkeyId,
        ids: form.id,
        excelId: type.value === 2 ? form.excelIds : type.value === 3 ? rows.value.excelId : form.excelId,
        initTableId: form.initTableId,
        initTableName: form.initTableName,
    }
    setTimeout(() => {
        const { excelId } = formModel.value
        if (excelId) {
            const arr = formModel.value.excelId.split(',')
            treeRef.value?.setCheckedKeys(arr)
        }
       
    }, 2000)
}

//获取清表列表
const excelData = ref([])
const getExcelListData = async () => {
    const { data } = await excelApi.getList({
        current: 1,
        size: 100000,
        parentId: 0,
    })
    excelData.value = getArrValue(data?.records)
}

//清表列表被选择
const nameChange = () => {
    if (!isNullES(formModel.value.name)) {
        formModel.value.search = ''
        getTabLazytreeAll()
    }
}

//清表树参数
const treeRef = ref(null)
const tabTreeProps = {
    label: 'name',
    children: 'children',
    disabled: 'hasChildren',
    isLeaf: function (data) {
        let tag = false
        if (!data.hasChildren) {
            tag = true
        }
        if (Number(data.isExistForm) === 1) {
            tag = true
        }
        return tag
    },
}

//获取清表树
const isLoading = ref(false)
const tabTreeData = ref([])
const getTabLazytreeAll = async () => {
    const { name, search } = formModel.value
    isLoading.value = true
    const { data } = await excelApi.tabLazyTreeAll({
        modeId: name,
        name: search,
    })
    tabTreeData.value = getArrValue(data)
    isLoading.value = false
}

//搜索筛选
const filterNode = (value, data, node) => {
    if (isNullES(value)) return true
    let _array = [] //这里使用数组存储 只是为了存储值。
    getReturnNode2(node, _array, value)
    let result = false
    _array.forEach((item) => {
        result = result || item
    })
    return result
}

const getReturnNode2 = (node, _array, value) => {
    let isPass
        = node.data && node.data.name && node.data.name.indexOf(value) !== -1
    isPass ? _array.push(isPass) : ''
    if (!isPass && node.level !== 1 && node.parent) {
        getReturnNode2(node.parent, _array, value)
    }
}

const checkChange = (data) => {
    //节点选中回调
    if (treeRef.value?.getCheckedNodes().length === 0) {
        treeRef.value?.setCheckedKeys([])
    } else if (treeRef.value?.getCheckedNodes().length >= 1) {
        treeRef.value?.setCheckedKeys([data.id])
    }
}

//提交表单
const submitLoading = ref(false)
const dialogSubmit = async () => {
    let checkNodes = treeRef.value?.getCheckedNodes()
    if (checkNodes.length <= 0) {
        window?.$message?.warning('请先设置清表')
        return
    }
    let node = checkNodes[checkNodes.length - 1]
    if (Number(node.fileType) !== 3) {
        window?.$message?.warning('请先上传Excel表')
        return
    }
    submitLoading.value = true
    if (type.value === 3) {
        const { isRes } = await testApi.relevancy({
            excelId: node.id,
            classId: rows.value.id,
        })
        
        submitLoading.value = false
        if (!isRes) return
        dialogClose()
        window?.$message?.success('关联清表成功')
        emit('change')
    } else {
        const { isRes } = await excelApi.saveLinkTab({
        exceTabId: node.id,
        tabId: formModel.value.id,
         })
        submitLoading.value = false
        if (!isRes) return
        dialogClose()
        window?.$message?.success('关联清表成功')
        emit('change')
    
    }

}

//关闭弹窗
const dialogClose = () => {
    formModel.value.name = ''
    formModel.value.search = ''
    formModel.value.id = ''
    tabTreeData.value = []
    treeRef.value?.setCheckedKeys([])
    isShow.value = false
    emit('close')
}
</script>

<style lang="scss">
.el-overlay-dialog
    .el-dialog.hc-new-dialog.hc-association-list-box
    .hc-new-dialog-body {
    .hc-association-list-tree-box {
        position: relative;
        padding: 5px 0;
        height: calc(100% - 160px);
        border: 1px solid #dcdfe6;
        border-radius: 5px;
    }
}
</style>
