<template>
    <el-dialog draggable class="cn-operate-dialog" width="800px" v-model.trim="dialogVisible" :title="title"
        @close="emit('closePopup')">
        <el-form class="form-two" :model="form" label-width="100px" ref="formRef" :rules="rules">
            <el-form-item label="设备类型" prop="type">

                <el-select v-model.trim="form.type" placeholder="请选择设备类型" @change="formDevTypeChange" clearable>
                    <el-option v-for="item in devTypeOptions" :key="item.value" :label="item.label"
                        :value="item.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="设备型号" prop="devType">
                <!-- <el-select v-model.trim="form.devType" placeholder="请选择" filterable @change="devTypeChange">
                    <el-option v-for="item in DevTypeOptions" :key="item.id" :label="item.name"
                        :value="item.id"></el-option>
                </el-select> -->
                <el-select v-model.trim="form.devType" filterable placeholder="请选择设备型号" clearable
                    @change="devTypeChange">
                    <el-option v-for="item in formDevModelOptionsFilter" :key="item.value" :label="item.label"
                        :value="item.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="版本号" prop="versionNo">
                <el-input maxlength="32" show-word-limit    v-model.trim="form.versionNo" autocomplete="off"
                    placeholder="请输入版本号"></el-input>
            </el-form-item>
            <el-form-item label="版本类型" prop="versionType">
                <el-input maxlength="32" show-word-limit    v-model.trim="form.versionType" autocomplete="off"
                    placeholder="填写特殊类型(不填默认通用类型)"></el-input>
            </el-form-item>
            <el-form-item label="协议版本" prop="versionAgreement">
                <el-input maxlength="32" show-word-limit    v-model.trim="form.versionAgreement" autocomplete="off"
                    placeholder="请输入协议版本"></el-input>
            </el-form-item>
            <el-form-item label="版本日期" prop="versionDate">
                <el-date-picker v-model.trim="form.versionDate" type="date" value-format="YYYY-MM-DD"
                    placeholder="选择日期时间" style="width: 100%"></el-date-picker>
            </el-form-item>

            <el-form-item label="CRC校验" prop="crc">
                <el-input maxlength="32" show-word-limit    v-model.trim="form.crc" autocomplete="off"
                    placeholder="请输入CRC校验"></el-input>
            </el-form-item>
        </el-form>
        <el-form :model="form" label-width="100px" class="mt10 form-one">
            <el-form-item label="描述" prop="description">
                <el-input  show-word-limit  maxlength="300" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" 
                    v-model.trim="form.description" autocomplete="off" placeholder="请输入描述"></el-input>
            </el-form-item>
            <el-form-item label="升级文件" prop="file">
                <el-upload :limit="1" accept=".bin" :auto-upload="false" :on-change="fileChange" :on-exceed="fileExceed"
                    :on-remove="fileRemove" :file-list="fileList">
                    <el-button type="primary">点击上传</el-button>
                </el-upload>
            </el-form-item>
        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submit" :loading="loading">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, inject, computed } from 'vue'
import { reactive } from 'vue'
import TableStore from '@/utils/tableStore'
import { ElMessage } from 'element-plus'
import { queryByCode, queryByid, queryCsDictTree } from '@/api/system-boot/dictTree'
import { addEdData, auditEdData } from '@/api/cs-device-boot/edData'
const emit = defineEmits(['closePopup'])
const TypeOptions = ref()
const DevTypeAllOptions = ref()
const DevTypeOptions = ref()
const devTypeOptions: any = ref([])

const devModelOptions: any = ref([])
const fileList: any = ref([])
const tableStore = inject('tableStore') as TableStore
const formRef = ref()
const loading = ref(false)
const form = reactive<any>({
    devType: null,
    devTypeName: null,
    versionAgreement: null,
    versionNo: null,
    versionType: null,
    crc: null,
    description: null,
    versionDate: null,
    type: null,
    id: null,
    file: []
})
const rules = {
    type: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
    devType: [{ required: true, message: '请选择设备型号', trigger: 'change' }],
    versionNo: [{ required: true, message: '请输入版本号', trigger: 'blur' }],
    versionType: [{ required: true, message: '请输入版本类型', trigger: 'blur' }],
    versionAgreement: [{ required: true, message: '请输入协议版本', trigger: 'blur' }],
    versionDate: [{ required: true, message: '请输入版本日期', trigger: 'blur' }],
    description: [{ required: true, message: '请输入描述', trigger: 'blur' }],
    crc: [{ required: true, message: '请输入CRC校验', trigger: 'blur' }],
    file: [{ required: true, message: '请输入升级文件', trigger: 'blur' }]
}
const typeChange = () => {
    // console.log(form.type)
    form.devType = null
    form.devTypeName = null
    queryCsDictTree(form.type).then(res => {
        DevTypeOptions.value = res.data
    })
}
const devTypeChange = (e: any) => {
    // console.log(e)
    form.devTypeName = formDevModelOptionsFilter.value.filter((item: any) => item.value == e)[0].label
}
queryByCode('Device_Type').then(async res => {
    const id = res.data.id
    queryCsDictTree(id).then(res => {
        devTypeOptions.value = res.data.map((item: any) => {
            return {
                value: item.id,
                label: item.name,
                ...item
            }
        })
    })
    queryByid(id).then(res => {
        res.data.map((item: any, index: any) => {
            if (item.pid == id) {
                res.data.splice(index, 1)
            }
        })
        devModelOptions.value = res.data.map((item: any) => {
            return {
                value: item.id,
                label: item.name,
                ...item
            }
        })
    })
    // tableStore.index()
})
queryByCode('Direct_Connected_Device').then(res => {
    queryCsDictTree(res.data.id).then(res => {
        TypeOptions.value = res.data
    })
    queryByid(res.data.id).then(res => {
        DevTypeAllOptions.value = res.data
    })
})
const formDevModelOptionsFilter = computed(() => {
    return devModelOptions.value.filter((item: any) => {
        if (form.type) {
            return item.pid == form.type
        } else {
            return true
        }
    })
})
const fileChange = (e: any) => {
    if (!beforeUpload(e.raw)) return
    form.file = e.raw
    fileList.value = [e.raw]
}
const fileExceed = (e: any) => {
    ElMessage.error('只能上传一个文件')
}
// 处理上传前检查
const beforeUpload = (file: any) => {
    const isWord = file.name.endsWith('.bin')

    if (!isWord) {
        ElMessage.error('请上传(.bin)格式文件!')
        fileList.value = []
        return false
    }

    // 校验通过后允许上传，交由 http-request 处理
    return true
}

const fileRemove = (e: any) => {
    form.file = null
    fileList.value = []
}
const formDevTypeChange = (e: any) => {
    if (!e) {
        return
    }
    // form.devModel = ''
}
const dialogVisible = ref(false)
const title = ref('新增版本')
const open = async (text: string, data?: anyObj) => {
    title.value = text
    dialogVisible.value = true
    if (data) {
        for (let key in form) {
            form[key] = data[key]
        }
        fileList.value = [
            {
                name: data.filePath,
                url: data.filePath
            }
        ]
    } else {
        for (let key in form) {
            form[key] = null
        }
    }

}
const submit = () => {
    // console.log(formRef)
    formRef.value.validate(async (valid: boolean) => {
        // console.log(valid)
        if (valid) {

            if (fileList.value.length == 0) {
                ElMessage.warning('请上传升级文件')
                return
            }
            loading.value = true
            let submitForm = new FormData()
            for (let key in form) {
                submitForm.append(key, form[key])
            }
            if (form.id) {
                await auditEdData(form)
            } else {
                await addEdData(form)
            }
            ElMessage.success('操作成功')
            tableStore.index()
            dialogVisible.value = false
            emit('closePopup')
            loading.value = false
        }
    })
}

defineExpose({ open })
</script>
<style scoped lang="scss">
:deep(.el-upload-list__item-info) {
    width: 600px !important;
}
</style>
