<template>
    <hc-dialog v-model="isShow" widths="26rem" title="编辑节点" is-footer-center @close="dialogClose">
        <el-form ref="formRef" :model="formModel" :rules="formRules" label-position="top" label-width="auto">
            <el-form-item label="节点名称：" prop="nodeName">
                <el-input v-model="formModel.nodeName" clearable class="is-right-btn">
                    <template #append>
                        <el-button hc-btn type="primary" @click="aliasShowClick">添加别名</el-button>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item label="上级节点：">
                <el-input v-model="formModel.parentName" disabled />
            </el-form-item>
            <el-form-item label="节点类型：" prop="nodeType">
                <el-select v-model="formModel.nodeType" placeholder="选择节点类型" filterable block>
                    <el-option v-for="item in nodeTypelist" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item v-if="wbsType !== 2 && wbsType !== 5" label="划分编号：">
                <el-input v-model="formModel.partitionCode" clearable />
            </el-form-item>
            <el-form-item v-if="wbsType !== 5" label="唯一编码：">
                <el-input v-model="formModel.uniqueCode" clearable />
            </el-form-item>
            <el-form-item v-if="wbsType === 6" label="是否有混凝土：">
                <div class="form-item-div">
                    <el-radio-group v-model="formModel.isConcrete">
                        <el-radio :value="0">否</el-radio>
                        <el-radio :value="1">有</el-radio>
                    </el-radio-group>
                </div>
            </el-form-item>
            <el-form-item v-if="wbsType === 6" label="是否试验节点：">
                <div class="form-item-div">
                    <el-radio-group v-model="formModel.isExpernode">
                        <el-radio :value="0">否</el-radio>
                        <el-radio :value="1">是</el-radio>
                    </el-radio-group>
                </div>
            </el-form-item>
            <el-form-item v-if="wbsType !== 2 && wbsType !== 5" label="内业资料类型：" prop="majorDataType">
                <el-select v-model="formModel.majorDataType" placeholder="选择内业资料类型" filterable block>
                    <el-option v-for="item in majorDataType" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item v-if="wbsType === 2 && formModel.nodeType === 53" label="勾选相关联试验：" prop="mixRatioTestIds" :f="getTestTreeData()">
                <el-tree-select
                    v-model="mixRatioTestIds" placeholder="选择勾选相关联试验" show-checkbox clearable filterable multiple block
                    node-key="id" :data="testData" :props="testProps" :render-after-expand="false" @check="testTreeCheckChange"
                />
            </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>

    <!-- 节点别名 -->
    <hc-dialog v-model="isAliasShow" widths="26rem" title="节点别名" is-footer-center @close="aliasDialogClose">
        <el-form ref="formAliasRef" :model="formAliasModel" :rules="formAliasRules" label-position="top" label-width="auto">
            <el-form-item prop="aliasName">
                <el-input v-model="formAliasModel.aliasName" placeholder="请输入节点别名" clearable class="is-right-btn">
                    <template v-if="formModel.pKeyId" #append>
                        <el-button hc-btn type="primary" @click="addAliasName">添加</el-button>
                    </template>
                </el-input>
            </el-form-item>
        </el-form>
        <div v-if="aliasArr.length > 0" class="hc-tree-node-edit-form-alias-name">
            <template v-for="(item, index) in aliasArr" :key="index">
                <el-tag closable type="primary" @close="aliasNameClose(index)">{{ item }}</el-tag>
            </template>
        </div>
        <template #footer>
            <el-button hc-btn @click="aliasDialogClose">取消</el-button>
            <el-button hc-btn type="primary" :loading="submitAliasLoading" @click="aliasSubmit">提交</el-button>
        </template>
    </hc-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { deepClone, formValidate, getArrValue, isNullES } from 'js-fast-way'
import projectApi from '~api/project/project'
import privateApi from '~api/wbs/private'

const props = defineProps({
    node: {
        type: Object,
        default: () => ({}),
    },
    type: {
        type: Number,
        default: 1,
    },
    wid: {
        type: [String, Number],
        default: '',
    },
    pid: {
        type: [String, Number],
        default: '',
    },
    treeProps: {
        type: Object,
        default: () => ({}),
    },
    nodeType: {
        type: Array,
        default: () => ([]),
    },
    majorType: {
        type: Array,
        default: () => ([]),
    },
})

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

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

//数据变量
const formModel = ref(props.node)
const wbsType = ref(props.type)
const wbsId = ref(props.wid)
const projectId = ref(props.pid)
const nodeTypelist = ref(props.nodeType)
const majorDataType = ref(props.majorType)
const testProps = ref(props.treeProps)

//监听数据
watch(() => [
    props.node,
    props.type,
    props.wid,
    props.pid,
    props.nodeType,
    props.majorType,
    props.treeProps,
], ([node, type, wid, pid, nodeType, majorType, treeProps]) => {
    formModel.value = node
    wbsType.value = type
    wbsId.value = wid
    projectId.value = pid
    nodeTypelist.value = nodeType
    majorDataType.value = majorType
    testProps.value = treeProps
}, { deep: true })

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

//获取数据
const getDataInfo = () => {
    const { nodeType } = formModel.value
    if (nodeType === 53) {
        getTestTreeData()
    }
}

//节点别名
const isAliasShow = ref(false)

//节点别名
const formAliasRef = ref(null)
const formAliasModel = ref({})
const formAliasRules = {
    aliasName: {
        required: true,
        trigger: 'blur',
        message: '请输入节点别名',
    },
}

//显示节点别名弹窗
const aliasArr = ref([])
const aliasShowClick = () => {
    isAliasShow.value = true
    aliasArr.value = []
    const { fullName } = deepClone(formModel.value)
    if (isNullES(fullName)) return
    aliasArr.value = fullName.split(',')
}

//添加别名
const addAliasName = async () => {
    const formRes = await formValidate(formAliasRef.value)
    if (!formRes) return false
    const { aliasName } = deepClone(formAliasModel.value)
    if (aliasArr.value.indexOf(aliasName) !== -1) {
        window.$message.warning('请不要重复别名')
        return
    }
    aliasArr.value.push(aliasName)
    formAliasModel.value.aliasName = ''
}

//移除别名
const aliasNameClose = (index) => {
    aliasArr.value.splice(index, 1)
}

//提交别名
const submitAliasLoading = ref(false)
const aliasSubmit = async () => {
    submitAliasLoading.value = true
    const { pKeyId } = formModel.value
    const fullName = aliasArr.value.join(',')
    const { isRes } = await privateApi.privateSubmitFullName({
        pKeyId, fullNames: fullName,
    })
    submitAliasLoading.value = false
    if (!isRes) return
    aliasDialogClose()
    window?.$message?.success('操作成功')
}

//关闭节点别名弹窗
const aliasDialogClose = () => {
    isAliasShow.value = false
    formAliasModel.value = {}
}

//获取实验树的数据
const testData = ref([])
const mixRatioTestIds = ref([])
const getTestTreeData = async () => {
    testData.value = []
    const { primaryKeyId, pKeyId, mixRatioTestIds: testIds } = formModel.value
    let pid = primaryKeyId ?? pKeyId
    const { data } = await projectApi.findProjectTree({
        projectId: projectId.value,
        wbsId: wbsId.value,
        parentId: pid,
    })
    testData.value = getArrValue(data)
    if (!isNullES(testIds)) {
        mixRatioTestIds.value = testIds?.split(',') ?? []
    } else {
        mixRatioTestIds.value = []
    }
}
//监听实验树的勾选， halfCheckedKeys
const testTreeCheckChange = (_, { checkedKeys }) => {
    formModel.value.mixRatioTestIds = checkedKeys.join(',')
}

//表单
const formRef = ref(null)
const formRules = {
    nodeName: {
        required: true,
        trigger: 'blur',
        message: '请输入节点名称',
    },
    nodeType: {
        required: true,
        trigger: 'blur',
        message: '请选择节点类型',
    },
    majorDataType: {
        required: true,
        trigger: 'blur',
        message: '请选择内业资料类型',
    },
    mixRatioTestIds: {
        required: true,
        trigger: 'blur',
        message: '请勾选相关联试验',
    },
}

//提交表单
const submitLoading = ref(false)
const dialogSubmit = async () => {
    const formRes = await formValidate(formRef.value)
    if (!formRes) return false
    submitLoading.value = true
    //发起请求
    const { isRes } = await privateApi.submit(formModel.value)
    submitLoading.value = false
    if (!isRes) return
    dialogClose()
    window?.$message?.success('操作成功')
    emit('change')
}

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

<style lang="scss">
.hc-tree-node-edit-form-alias-name {
    position: relative;
    border: 1px dashed #dcdfe6;
    border-radius: 4px;
    padding: 5px 5px 0;
    .el-tag {
        margin-right: 5px;
        margin-bottom: 5px;
    }
}
</style>
