<template>
    <hc-dialog v-model="isShow" ui="hc-exctab-exceltab-add-excel" :title="type" widths="800px" :padding="false" @close="dialogClose">
        <div class="relative h-80px">
            <el-form ref="formRef" :model="formModel" :rules="formRules" label-position="top" label-width="auto">
                <el-row :gutter="14">
                    <el-col :span="12">
                        <el-form-item label="清表名称：" prop="nodeName">
                            <el-input v-model="formModel.nodeName" placeholder="请输入清表名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="清表类型：" prop="tabType">
                            <el-select v-model="formModel.tabType" filterable block placeholder="请选择清表类型">
                                <el-option v-for="item in excelTypeData" :key="item.value" :label="item.label" :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <div class="hc-exctab-exceltab-add-excel-middle">
            <el-row :gutter="14" class="h-full">
                <el-col :span="12" class="h-full">
                    <div class="left-card h-full">
                        <div class="select">
                            <el-select v-model="formModel.wbsId" filterable block placeholder="请选择WBS模板" @change="wbsModelChange">
                                <el-option v-for="item in wbsModel" :key="item.id" :label="item.wbsName" :value="item.id" />
                            </el-select>
                        </div>
                        <div v-loading="treeLoading" class="tree">
                            <el-scrollbar>
                                <el-tree v-if="isWbsTree" :props="wbsTreeProps" :load="wbsTreeLoad" lazy accordion highlight-current @node-click="wbsTreeClick" />
                            </el-scrollbar>
                        </div>
                    </div>
                </el-col>
                <el-col :span="12" class="h-full">
                    <div class="right-card h-full">
                        <hc-table :column="tableColumn" :datas="tableData" :is-index="false" :is-current-row="false">
                            <template #action="{ row }">
                                <el-link v-if="row.isLinkTable !== 2" type="primary" @click="rowRelation(row)">关联</el-link>
                                <el-link v-if="row.isLinkTable === 2" type="warning" @click="rowCancel(row)">取消关联</el-link>
                            </template>
                        </hc-table>
                    </div>
                </el-col>
            </el-row>
        </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 { nextTick, ref, watch } from 'vue'
import { getDictionaryData } from '~uti/tools'
import { formValidate, getArrValue, getObjValue, isNullES } from 'js-fast-way'
import mainApi from '~api/exctab/exceltab'

const props = defineProps({
    info: {
        type: Object,
        default: () => ({}),
    },
    type: {
        type: String,
        default: '新增',
    },
})

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

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

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

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

//处理数据
const wbsMiddle = ref(false)
const excelTypeData = ref([])
const getInfoData = async () => {
    const data = getObjValue(dataInfo.value)
    console.log(data)
    if (data.fileType === 3) {
        wbsMiddle.value = false
    } else {
        wbsMiddle.value = true
        getWbsTypeList().then() //wbs模板名称
    }
    //获取清表类型
    const types = await getDictionaryData('sys_excltab_type', true)
    types.forEach(item => {
        item.value = Number(item.value)
    })
    excelTypeData.value = types
    //处理表单默认数据
    if (props.type === '新增') {
        formModel.value = { parentId: data.id }
    } else {
        formModel.value = { id: data.id }
    }
}

//清表编辑 wbs 下拉框选择
const wbsModel = ref([])
const getWbsTypeList = async () => {
    const { data } = await mainApi.getWbsTypeList({ wbstype: 2 })
    wbsModel.value = getArrValue(data)
}
//选择WBS模板
const isWbsTree = ref(false)
const wbsModelChange = () => {
    isWbsTree.value = false
    tableData.value = []
    tableList.value = []
    const wbsId = formModel.value.wbsId
    wbsModel.value.forEach(item => {
        if (item.id === wbsId) {
            formModel.value.wbsType = item.wbsType
        }
    })
    nextTick(() => {
        isWbsTree.value = true
    })
}

//树
const wbsTreeProps = {
    label: 'nodeName',
    isLeaf: (item) => {
        return !item.hasChildren
    },
}

//懒加载树
const treeLoading = ref(false)
const wbsTreeLoad = async (node, resolve) => {
    treeLoading.value = true
    const parentId = node.level === 0 ? 0 : node.data.id
    const { wbsId, wbsType } = formModel.value
    const { data } = await mainApi.wbsTree({
        parentId, wbsId, wbsType,
    })
    treeLoading.value = false
    resolve(getArrValue(data))
}

//树节点被点击
const wbsForm = ref({})
const wbsTreeClick = ({ id, type, nodeName }) => {
    wbsForm.value = { id, wbsType: type, wbsName: nodeName }
    const form = formModel.value
    if (tableList.value.length <= 0) {
        selectByNodeTable(id, type, form.id, form.wbsId)
    } else {
        let tag = true
        tableList.value.forEach((item) => {
            if (item.id === id) {
                tableData.value = item.arrs
                tag = false
            }
        })
        if (tag) {
            selectByNodeTable(id, type, form.id, form.wbsId)
        }
    }
}

//获取数据
const selectByNodeTable = async (id, type, formId, wbsId) => {
    const { data } = await mainApi.selectByNodeTable({
        id,
        wbsType: type ?? '',
        liunxId: formId ?? '',
        projectid: wbsId ?? '',
    })
    const res = getArrValue(data)
    res.forEach(item => {
        item.changeTable = item.isLinkTable
    })
    tableData.value = res
}

//基础表单
const formRef = ref(null)
const formModel = ref({})
const formRules = {
    nodeName: {
        required: true,
        trigger: 'blur',
        message: '请输入清表名称',
    },
    tabType: {
        required: true,
        trigger: 'blur',
        message: '请选择清表类型',
    },
}

//表格
const tableColumn = [
    { key: 'tableName', name: '表名' },
    { key: 'action', name: '操作', width: 80, align: 'center' },
]
const tableData = ref([])
const tableList = ref([])

//关联
const rowRelation = (row) => {
    row.isLinkTable = 2
    setTableList()
}

//取消关联
const rowCancel = (row) => {
    row.isLinkTable = 1
    setTableList()
}

//处理数据
const setTableList = () => {
    const form = wbsForm.value
    let tap = tableList.value.find((item) => {
        return item.id === form.id
    })
    if (!tap) {
        tableList.value.push({
            id: form.id,
            wbsType: form.wbsType,
            wbsName: form.wbsName,
            arrs: tableData.value,
        })
    }
}

//提交
const submitLoading = ref(false)
const dialogSubmit = async () => {
    const isValidate = await formValidate(formRef.value)
    if (!isValidate) return false
    submitLoading.value = true
    let linkDataInfo = []
    const list = tableList.value
    if (list.length > 0) {
        list.forEach(item => {
            let linkIds = ''
            item.arrs.forEach(data => {
                if (data.isLinkTable !== data.changeTable) {
                    linkIds = `${linkIds}${linkIds !== '' ? ',' : ''}${data.pkeyId}_${data.isLinkTable}`
                }
            })
            if (!isNullES(linkIds)) {
                linkDataInfo.push({
                    id: item.id,
                    linkIds: linkIds,
                    wbsName: item.wbsName,
                    wbsType: item.wbsType,
                })
            }
        })
    }
    let res = {}
    const form = formModel.value
    if (!isNullES(form.parentId) && isNullES(form.id)) {
        res = await mainApi.savaDataInfo({
            nodeName: form.nodeName,
            tabType: form.tabType,
            parentId: form.parentId,
            linkDataInfo: linkDataInfo,
        })
    } else {
        res = await mainApi.savaDataInfo({
            nodeName: form.nodeName,
            tabType: form.tabType,
            id: form.id,
            linkDataInfo: linkDataInfo,
        })
    }
    const { code } = res
    submitLoading.value = false
    if (code === 200) {
        window.$message.success('保存成功')
        dialogClose()
        emit('finish')
    }
}

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

<style lang="scss">
.el-overlay-dialog .el-dialog.hc-new-dialog.hc-exctab-exceltab-add-excel .el-dialog__body{
    height: 660px;
    padding: 12px 0;
}
.hc-exctab-exceltab-add-excel-middle {
    position: relative;
    height: calc(100% - 80px);
    overflow: hidden;
    .left-card {
        position: relative;
        border: 1px solid gainsboro;
        border-radius: 3px;
        .select {
            position: relative;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 6px;
            height: 45px;
            border-bottom: 1px solid gainsboro;
        }
        .tree {
            position: relative;
            height: calc(100% - 45px);
            padding: 6px;
        }
    }
    .right-card {
        position: relative;
    }
}
</style>
