<template>
    <div>
        <el-card style="margin-bottom: 10px" class="cardTop">
            <el-form
                :model="formContent"
                :inline="true"
                label-width="auto"
                ref="dialogFormRef"
                :rules="rules"
                class="form-five"
            >
                <el-form-item label="脚本名称" prop="name">
                    <el-input v-model.trim="formContent.name" placeholder="请输入脚本名称" clearable />
                </el-form-item>
                <el-form-item label="参照标准名称" prop="standardName">
                    <el-input v-model.trim="formContent.standardName" placeholder="请输入参照标准名称" clearable />
                </el-form-item>
                <el-form-item label="标准推行年份" prop="standardTime">
                    <el-date-picker
                        v-model="formContent.standardTime"
                        style="width: 100%"
                        type="year"
                        format="YYYY"
                        value-format="YYYY"
                        placeholder="请选择标准推行年份"
                    />
                </el-form-item>
                <el-form-item label="模版类型" prop="type">
                    <el-select v-model="formContent.type" filterable clearable placeholder="请选择模版类型">
                        <el-option v-for="item in stencil" :key="item.value" :label="item.name" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="检测脚本值类型" prop="valueType">
                    <el-select
                        v-model="formContent.valueType"
                        :disabled="titleType == '编辑检测脚本'"
                        filterable
                        clearable
                        placeholder="请选择值类型"
                    >
                        <el-option
                            v-for="item in dictStore.getDictData('Script_Value_Type')"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <div class="formBut">
                        <el-button type="primary" :icon="Select" @click="save">保存</el-button>
                        <el-button :icon="Close" @click="close">返回</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card v-if="show">
            <TestScriptDetail :options="secondLevelOptions" :formContent="formContent" />
        </el-card>
    </div>
</template>
<script setup lang="ts">
import { ref, nextTick } from 'vue'
import { useDictStore } from '@/stores/modules/dict'
import TestScriptDetail from '@/views/machine/testScript/components/testScriptDetail.vue'
import { type TestScript } from '@/api/device/interface/testScript'
import type { Dict } from '@/api/system/dictionary/interface'
import { getDictTreeByCode } from '@/api/system/dictionary/dictTree'
import type { CascaderOption } from 'element-plus'
import { Select, Close } from '@element-plus/icons-vue'
import { pqScriptAdd, pqScriptUpdate } from '@/api/device/testScript'
import { useRouter } from 'vue-router'
const modeId = ref()
const show = ref(false)
const router = useRouter()

const secondLevelOptions: any[] = []
// 定义弹出组件元信息
const dialogFormRef = ref()
const dictStore = useDictStore()
function useMetaInfo() {
    const titleType = ref('add')
    const formContent = ref<TestScript.ResTestScript>({
        name: '',
        type: '',
        valueType: '',
        pattern: modeId.value,
        standardName: '',
        standardTime: '',
        state: 1
    })
    return { titleType, formContent }
}
const stencil = [
    { name: '脚本', value: 0 },
    { name: '模版', value: 1 }
]
const rules = {
    name: [{ required: true, message: '请输入脚本名称', trigger: 'blur' }],
    standardName: [{ required: true, message: '请输入参照标准名称', trigger: 'blur' }],
    standardTime: [{ required: true, message: '请选择标准推行年份', trigger: 'change' }],
    type: [{ required: true, message: '请选择模版类型', trigger: 'change' }],
    valueType: [{ required: true, message: '请选择检测脚本值类型', trigger: 'change' }]
}

const { titleType, formContent } = useMetaInfo()

// 清空formContent
const resetFormContent = () => {
    formContent.value = {
        name: '',
        type: '',
        valueType: '',
        pattern: '',
        standardName: '',
        standardTime: '',
        state: 1
    }
    router.go(-1)
}
// 关闭弹窗
const close = () => {
    // 清空dialogForm中的值
    resetFormContent()
    // 重置表单
    dialogFormRef.value?.resetFields()
}
// 关闭信息弹框
const closeInformation = () => {}

// 保存数据
const save = () => {
    // dialogFormRef
    dialogFormRef.value.validate((valid: boolean) => {
        if (valid) {
            if (titleType.value == '新增检测脚本') {
                formContent.value.pattern = modeId.value
                pqScriptAdd(formContent.value).then(res => {
                    if (res.code === 'A0000') {
                        ElMessage.success({ message: res.message })
                        formContent.value.id = res.data
                        titleType.value == '编辑检测脚本'
                        show.value = true
                    }
                })
            } else {
                pqScriptUpdate(formContent.value).then(res => {
                    if (res.code === 'A0000') {
                        ElMessage.success({ message: res.message })
                    }
                })
            }
        }
    })
}

// 打开弹窗，可能是新增，也可能是编辑
const open = async (title: string, row: any) => {
    titleType.value = title
    if (title == '新增检测脚本') {
        show.value = false
    } else {
        let list = JSON.parse(row)
        formContent.value = list
        show.value = true
    }

    // 重置表单
    dialogFormRef.value?.resetFields()
}
// 获取树字典
const treeInfo = async (currentMode: string) => {
    const data: Dict.ResDictTree = {
        name: '',
        id: '',
        pid: '',
        pids: '',
        code: 'Script_Indicator_Items',
        sort: 0
    }
    const result = await getDictTreeByCode(data)
    const allOptions = convertToOptions(result.data as Dict.ResDictTree[])
    secondLevelOptions.push(...(allOptions[0]?.children || []))
    modeId.value = dictStore.getDictData('Pattern').find(item => item.name === currentMode)?.id
}

onMounted(() => {
    let data: any = router.options.history.state
    console.log('🚀 ~ onMounted ~ data:', data)
    if (data.title == null) return
    nextTick(async () => {
        await treeInfo(data.mode)
        await open(data.title, data.row)
    })
})

// 转换函数
const convertToOptions = (dictTree: Dict.ResDictTree[]): CascaderOption[] => {
    return dictTree.map(item => ({
        value: item.id,
        code: item.code.split('-')[1] || item.code.split('-')[0],
        label: item.name,
        children: item.children ? convertToOptions(item.children) : undefined
    }))
}

// 对外映射
defineExpose({ open })
</script>
<style lang="scss" scoped>
/* .dialog-content {
  padding: 10px;
} */
:deep(.cardTop) {
    .el-card__body {
        padding: 20px 0 0 20px;
    }
}
.formBut {
    width: 100%;
    display: flex;
    justify-content: end;
}
.form-five {
    display: flex;
    flex-wrap: wrap;
    // justify-content: space-between;
    .el-form-item {
        display: flex;
        width: 15.8%;

        .el-form-item__content {
            flex: 1;
            .el-select,
            .el-cascader,
            .el-input__inner,
            .el-date-editor {
                width: 100%;
            }
        }
    }
}
</style>
