<template>
    <div>
        <el-card style="margin-bottom: 10px" class="cardTop" :style="{ height: height }">
            <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 maxlength="32" show-word-limit/>
                </el-form-item>
                <el-form-item label="参照标准名称" prop="standardName">
<!--                    <el-input v-model.trim="formContent.standardName" placeholder="请输入参照标准名称" clearable />-->
                  <el-select v-model="formContent.standardName" filterable placeholder="请选择参照标准名称" @change="setStandardTimeList">
                    <el-option v-for="item in standardNameList" :key="item.label" :label="item.label" :value="item.label" />
                  </el-select>
                </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-select v-model="formContent.standardTime" filterable placeholder="请选择标准推行年份">
                    <el-option v-for="item in standardTimeList" :key="item" :value="item" :label="item" />
                  </el-select>
                </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>
                    <div class="formBut">
                        <el-button
                            type="primary"
                            :icon="shrink ? ArrowUpBold : ArrowDownBold"
                            @click="shrinkChange"
                        ></el-button>
                        <el-button type="primary" :icon="Select" @click="save">保存</el-button>
                        <el-button :icon="Close" @click="close">返回</el-button>
                    </div>
                </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 label="额定电流" prop="ratedCurr">
                    <el-input-number
                        v-model.trim="formContent.ratedCurr"
                        min="0"
                        max="20"
                        style="width: 100%"
                        placeholder="请输入额定电流"
                        clearable
                    />
                </el-form-item>
                <el-form-item label="额定电压" prop="ratedVolt">
                    <el-input-number
                        v-model.trim="formContent.ratedVolt"
                        min="0"
                        max="380"
                        style="width: 100%"
                        placeholder="请输入额定电压"
                        clearable
                    />
                </el-form-item>

                <el-form-item v-if="appSceneStore.currentScene=='1'" label="福禄克专用" prop="fluke">
                <el-switch
                    v-model="formContent.fluke"
                    active-color="#13ce66"
                />
              </el-form-item>
            </el-form>
        </el-card>
        <el-card v-if="show">
            <TestScriptDetail :options="secondLevelOptions" :formContent="formContent" :shrink="shrink" />
        </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, ArrowDownBold, ArrowUpBold } from '@element-plus/icons-vue'
import { pqScriptAdd, pqScriptUpdate } from '@/api/device/testScript'
import { useRouter } from 'vue-router'
import {useAppSceneStore} from "@/stores/modules/mode";
const modeId = ref()
const show = ref(false)
const height = ref('125px')
const router = useRouter()
const standardNameList = reactive<{id:string,label: string, value: string}[]>([])
const standardTimeList = reactive<Array<string>>([])

const secondLevelOptions: any[] = []
// 定义弹出组件元信息
const dialogFormRef = ref()
const dictStore = useDictStore()
const appSceneStore = useAppSceneStore()

function useMetaInfo() {
    const titleType = ref('add')
    const formContent = ref<TestScript.ResTestScript>({
        name: '',
        type: '',
        valueType: '',
        pattern: modeId.value,
        standardName: '',
        standardTime: '',
        state: 1,
        ratedCurr: 0,
        ratedVolt: 0,
        fluke: 0,
    })
    return { titleType, formContent }
}
const shrink = ref(true)
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' }],
    ratedCurr: [{ required: true, message: '请填写额定电流', trigger: 'change' }],
    ratedVolt: [{ required: true, message: '请填写额定电压', trigger: 'change' }],
  fluke: [{ required: true }],
}

const { titleType, formContent } = useMetaInfo()
// 收缩
const shrinkChange = () => {
    shrink.value = !shrink.value
    shrink.value ? (height.value = '125px') : (height.value = '70px')
}
// 清空formContent
const resetFormContent = () => {
    formContent.value = {
        name: '',
        type: '',
        valueType: '',
        pattern: '',
        standardName: '',
        standardTime: '',
        state: 1,
        ratedCurr: 0,
        ratedVolt: 0,
        fluke: 0,
    }
    router.go(-1)
}
// 关闭弹窗
const close = () => {
    // 清空dialogForm中的值
    resetFormContent()
    // 重置表单
    dialogFormRef.value?.resetFields()
}
// 关闭信息弹框
const closeInformation = () => {}

const setStandardTimeList = ()=>{
  let checkStandard = standardNameList.find(item => item.label === formContent.value.standardName)
  if (checkStandard) {
    standardTimeList.push(...checkStandard.value.split(','))
  } else {
    standardTimeList.push('2016', '2017', '2018', '2019', '2020', '2021', '2022', '2023', '2024', '2025')
  }
}

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

// 打开弹窗，可能是新增，也可能是编辑
const open = async (title: string, row: any) => {
  dictStore.getDictData("Script_Standard_Name").forEach(item => {
    standardNameList.push({id: item.id, label: item.name, value: item.value})
  })

    titleType.value = title
    if (title == '新增检测脚本') {
        show.value = false
    } else {
        let list = JSON.parse(row)
        formContent.value = list
      formContent.value.fluke = formContent.value.fluke == 1? true : false
        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 result1 = (await getDictTreeByCode({ ...data, code: 'Script_Error' })).data[0].children
    const allOptions = await convertToOptions(result.data as Dict.ResDictTree[])
    const setallTree = await setTree(allOptions[0]?.children, result1)
    secondLevelOptions.push(...(setallTree || []))
    modeId.value = dictStore.getDictData('Pattern').find(item => item.name === currentMode)?.id
}

onMounted(() => {
    let data: any = router.options.history.state
    if (data.title == null) return
    nextTick(async () => {
        await treeInfo(data.mode)
        await open(data.title, data.row)
    })
})
const setTree = async (data, data1) => {
    data.forEach(item => {
        data1.forEach(item1 => {
            if (item.label.replace(/准确度|检测/g, '') == item1.name) {
                item.value = item1.id
            }
        })
    })
    return data
}
// 转换函数
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: 18.8%;

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