<template>
    <hc-drawer v-model="isShow" ui="hc-element-recognition-drawer" to-id="hc-layout-box" is-close @close="drawerClose">
        <hc-page-split :options="{ sizes: [14, 60, 26], minSize: [50, 300, 100] }" class="hc-element-recognition">
            <template #left>
                <hc-card scrollbar>
                    <template #header>
                        <hc-search-input v-model="searchTreeName" placeholder="请输入关键字" @search="searchTreeNameClick" />
                    </template>
                    <template v-if="isTreeMode === 1">
                        <hc-lazy-tree v-if="isShow" :h-props="treeProps" tree-key="id" @load="treeLoadNode" @node-tap="treeNodeTap">
                            <template #name="{ data }">
                                <span class="text-16px font-400">{{ data.name }}</span>
                            </template>
                        </hc-lazy-tree>
                    </template>
                    <template v-if="isTreeMode === 2">
                        <hc-data-tree ref="treeRef" :h-props="treeProps" tree-key="id" :datas="treeData" @node-tap="treeNodeTap">
                            <template #name="{ data }">
                                <span class="text-16px font-400">{{ data.name }}</span>
                            </template>
                        </hc-data-tree>
                    </template>
                </hc-card>
            </template>
            <hc-card :title="`【元素识别】${isNullES(nodeInfo.name) ? '表名称' : nodeInfo.name}`">
                <hc-table-form ref="excelRef" :html="excelHtml" @tap="excelClick" />
            </hc-card>
            <template #right>
                <hc-card>
                    <template #header>
                        <el-button color="#2550A2" size="small" class="text-white" :disabled="!isTreeNode" @click="webTemplateClick">关联WBS并创建元素</el-button>
                        <el-button color="#FF986A" size="small" class="text-white" :disabled="!isTreeNode" @click="elementLibClick">添加到元素库</el-button>
                        <!-- el-button color="#567722" size="small" class="text-white">元素匹配</el-button>
                        <el-button color="#67C23B" size="small" class="text-white">调整表单</el-button -->
                    </template>
                    <template #extra>
                        <el-button type="primary" size="small" :disabled="!isTreeNode" @click="addColByTab">新增</el-button>
                    </template>
                    <hc-table ref="tabRef" :column="tableColumn" :datas="tableData" :index-style="{ width: 60 }" @row-click="tableRowClick">
                        <template #textInfo="{ row }">
                            <hc-table-input v-model="row.textInfo" />
                        </template>
                        <template #textElementType="{ row }">
                            <el-select v-model="row.textElementType" filterable block>
                                <el-option v-for="item in dataType" :key="item.value" :label="item.label" :value="item.value" />
                            </el-select>
                        </template>
                        <template #textDeviation="{ row }">
                            <hc-table-input v-model="row.textDeviation" />
                        </template>
                        <template #action="{ row }">
                            <el-link type="warning" @click="saveRowClick(row)">保存</el-link>
                            <el-link type="danger" @click="delRowClick(row)">删除</el-link>
                        </template>
                    </hc-table>
                </hc-card>
            </template>
        </hc-page-split>
        <!-- 添加新元素字段 -->
        <HcAddColTab v-model="addColTabShow" :info="addColTabInfo" @finish="getTableData" />
        <!-- 添加到元素库 -->
        <HcElementLib v-model="elementLibShow" :info="elementLibInfo" :data="tableData" @finish="getTableData" />
        <!-- 关联公共WBS模板 -->
        <HcWebTemplate v-model="webTemplateShow" :info="webTemplateInfo" :data="tableData" @finish="getTableData" />
    </hc-drawer>
</template>

<script setup>
import { HcDelMsg } from 'hc-vue3-ui'
import { ref, watch } from 'vue'
import { getArrValue, isNullES, isString } from 'js-fast-way'
import { getDictionaryData } from '~uti/tools'
import HcAddColTab from './add-col-tab.vue'
import HcElementLib from './element-lib.vue'
import HcWebTemplate from './web-temp.vue'
import mainApi from '~api/exctab/exceltab'

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

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

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

//监听数据
const dataInfo = ref(props.data)
watch(() => props.data, (data) => {
    dataInfo.value = data
}, { immediate: true, deep: true })

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

//处理相关数据
const getDataApi = () => {
    getDataType()
}

//树搜索
const isTreeMode = ref(1) //1懒加载，2全加载
const searchTreeName = ref('')
const searchTreeNameClick = async () => {
    if (isNullES(searchTreeName.value)) {
        isTreeMode.value = 1
    } else {
        isTreeMode.value = 2
        await getTreeAllData()
        treeRef.value?.treeRef?.filter(searchTreeName.value)
    }
}

//树配置
const treeRef = ref(null)
const treeProps = {
    label: 'name',
    children: 'children',
    isLeaf: (item) => {
        return !item.hasChildren
    },
}

//全加载树
const treeData = ref([])
const getTreeAllData = async () => {
    const { data } = await mainApi.tabLazyTreeAll({
        modeId: dataInfo.value.id,
        name: '',
    })
    treeData.value = getArrValue(data)
}

//懒加载树
const treeLoadNode = async ({ item, level }, resolve) => {
    const parentId = level === 0 ? 0 : item.id
    const { data } = await mainApi.tabLazyTree({
        parentId: parentId,
        modeId: dataInfo.value.id,
    })
    resolve(getArrValue(data))
}

//树节点被点击
const isTreeNode = ref(false)
const nodeInfo = ref({})
const treeNodeTap = async ({ data }) => {
    nodeInfo.value = data
    if (data.fileType !== 3) {
        isTreeNode.value = false
        return
    }
    await getExcelHtmlCol(data.id)
    await getTableData()
    isTreeNode.value = true
}

//获取excel模板
const getExcelHtmlCol = async (id) => {
    const { error, code, data } = await mainApi.getExcelHtmlCol({ id })
    const resData = isString(data) ? data || '' : ''
    if (!error && code === 200 && resData) {
        excelHtml.value = resData
    } else {
        excelHtml.value = ''
    }
}

//excel模板
const excelRef = ref(null)
const excelHtml = ref('')

//获取元素类型
const dataType = ref([])
const getDataType = async () => {
    dataType.value = await getDictionaryData('data_type')
}

//元素表格
const tabRef = ref(null)
const tableColumn = [
    { key: 'textInfo', name: '元素名称' },
    { key: 'textElementType', name: '数据类型' },
    { key: 'textDeviation', name: '允许偏差值' },
    { key: 'action', name: '操作', width: 90, align: 'center' },
]
const tableData = ref([])
const getTableData = async () => {
    const { data } = await mainApi.getColByTabId({
        tabId: nodeInfo.value.id,
    })
    tableData.value = getArrValue(data)
}

//框框被点击
const excelClick = async (item) => {
    const arr = tableData.value
    let key = item.target.getAttribute('data-index')
    for (let i = 0; i < arr.length; i++) {
        let xys = isNullES(arr[i].xys) ? [] : arr[i].xys.split(',')
        if (xys.indexOf(key) > -1) {
            tabRef.value?.tableRef?.setCurrentRow(arr[i])
            await tableScrollToRow(i)
            break
        }
    }
}

//滚动到表格某一行
const tableScrollToRow = async (index) => {
    const table = tabRef.value?.tableRef.$el
    const row = table.querySelectorAll('.el-table__row')[index]
    tabRef.value?.tableRef?.setScrollTop(row.offsetTop)
}

//表格的某一行被点击
const tableRowClick = ({ row }) => {
    let xys = isNullES(row.xys) ? [] : row.xys.split(',')
    excelRef.value?.setSelect(xys)
}

//保存元素表格
const saveRowClick = async (row) => {
    if (isNullES(row.textInfo)) {
        window?.$message.warning('请填写元素名称')
        return
    }
    const { isRes } = await mainApi.saveColByTabId(row)
    if (!isRes) return
    window.$message.success('保存成功')
}

//删除元素表格
const delRowClick = (row) => {
    HcDelMsg(async (resolve) => {
        const { isRes } = await mainApi.delColByTabId(row.id)
        resolve() //关闭弹窗的回调
        if (!isRes) return
        window.$message.success('删除成功')
        getTableData().then()
    })
}

//添加新元素字段
const addColTabShow = ref(false)
const addColTabInfo = ref({})
const addColByTab = () => {
    addColTabInfo.value = nodeInfo.value
    addColTabShow.value = true
}

//添加到元素库
const elementLibShow = ref(false)
const elementLibInfo = ref({})
const elementLibClick = () => {
    elementLibInfo.value = nodeInfo.value
    elementLibShow.value = true
}

//关联公共WBS模板
const webTemplateShow = ref(false)
const webTemplateInfo = ref({})
const webTemplateClick = () => {
    webTemplateInfo.value = nodeInfo.value
    webTemplateShow.value = true
}

//关闭抽屉
const drawerClose = () => {
    isShow.value = false
    emit('close')
}
</script>

<style scoped lang="scss">

</style>

<style lang="scss">
.el-overlay .el-drawer.hc-element-recognition-drawer {
    background-color: #F1F5F8;
    .tree-line .el-tree__empty-block {
        min-width: unset;
    }
}
</style>
