<template>
    <div class="app-container">
        <el-row justify="start" style="margin-bottom: 20px;">
            <el-col :span="4">
                <el-input v-model="searchValue" placeholder="请输入MAC地址"></el-input>
            </el-col>
            <el-col :span="2" style="text-align: center;">
                <el-button type="primary" @click="search">搜索</el-button>
            </el-col>
        </el-row>
        <el-button type="primary" @click="addlicInfo" style="margin-bottom: 20px;">添加信息</el-button>
        <el-table :data="licInfoTable.licInfoData" border style="width: 100%" v-loading="licInfoTable.loading">
            <el-table-column prop="lqLicName" label="Lic名称" width="200" />
            <el-table-column prop="macAddress" label="MAC地址" width="200" />
            <el-table-column prop="effectiveTime" label="导入有效时间" />
            <el-table-column prop="fileEffectiveTime" label="文件有效时间" />
            <el-table-column prop="verificationInterval" label="验证间隔时间(s)" />
            <el-table-column prop="moduleVerification" label="模块验证" />
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除
                    </el-button>
                    <el-button size="small" type="primary" @click="handleExport(scope.row)">导出</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div style="margin-top: 20px">
            <el-pagination v-model:currentPage="licInfoTable.pageNo" v-model:page-size="licInfoTable.pageSize"
                :page-sizes="[10, 15, 20]" layout="->, total,sizes, prev, pager, next, jumper"
                :total="licInfoTable.total" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                hide-on-single-page />
        </div>
    </div>

    <!-- 添加对话框 -->
    <el-dialog v-model="licInfoForm.dialogVisible" :title="licInfoForm.title" width="30%" :before-close="handleClose">
        <el-form ref="licInfoRef" :model="licInfoForm.formLicInfo" :rules="licInfoForm.rules" label-width="130px"
            status-icon>
            <el-form-item label="Lic名称" prop="lqLicName">
                <el-input v-model="licInfoForm.formLicInfo.lqLicName" placeholder="请输入MAC地址"></el-input>
            </el-form-item>
            <el-form-item label="MAC地址" prop="macAddress">
                <el-input v-model="licInfoForm.formLicInfo.macAddress" placeholder="请输入MAC地址"></el-input>
            </el-form-item>
            <el-form-item label="导入有效时间" prop="effectiveTime">
                <el-date-picker v-model="licInfoForm.formLicInfo.effectiveTime" type="datetime" placeholder="请输入有效时间"
                    value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
            <el-form-item label="文件有效时间" prop="fileEffectiveTime">
                <el-date-picker v-model="licInfoForm.formLicInfo.fileEffectiveTime" type="datetime"
                    placeholder="请输入有效时间" value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
            <el-form-item label="验证间隔时间(s)" prop="verificationInterval">
                <el-input v-model.number="licInfoForm.formLicInfo.verificationInterval" placeholder="请输入验证间隔时间">
                </el-input>
            </el-form-item>
            <el-form-item label="模块验证">
                <el-input v-model="licInfoForm.formLicInfo.moduleVerification" placeholder="请输入模块验证"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleClose">关闭</el-button>
                <el-button type="primary" @click="onConfirm">确认</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { licInfoList, licInfoDelete, licInfoFileCreate, licInfoUpdate, licInfoCreate } from '@/services/api/licInformation/licInformation'
import { ElMessageBox, ElMessage } from "element-plus";

const licInfoTable = reactive({
    licInfoData: [],
    total: 0,
    pageNo: 1,
    pageSize: 10,
    loading: true
})

const licInfoRef = ref()

const searchValue = ref()

const licInfoForm = reactive<any>({
    dialogVisible: false,
    title: '新增',
    formLicInfo: {
        macAddress: '',
        effectiveTime: '',
        fileEffectiveTime: '',
        verificationInterval: '',
        moduleVerification: '',
        lqLicName: ''
    },
    rules: {
        macAddress: [{ required: true, message: '', trigger: 'blur' }],
        lqLicName: [{ required: true, message: '', trigger: 'blur' }],
        effectiveTime: [{
            type: 'date',
            required: true,
            message: '',
            trigger: 'change',
        }],
        fileEffectiveTime: [{
            type: 'date',
            required: true,
            message: '',
            trigger: 'change',
        }],
        verificationInterval: [{ required: true, message: '', trigger: 'blur' }, { type: 'number', message: '请输入数字' }],
    }
})

const search = () => {
    initLicInfo(searchValue.value, licInfoTable.pageNo, licInfoTable.pageSize)
}

const addlicInfo = () => {
    licInfoForm.title = '新增'
    licInfoForm.formLicInfo = {
        macAddress: '',
        effectiveTime: '',
        fileEffectiveTime: '',
        verificationInterval: '',
        moduleVerification: '',
        lqLicName: ''
    }
    licInfoForm.dialogVisible = true
}

const handleEdit = (data: any) => {
    licInfoForm.title = '编辑'
    licInfoForm.formLicInfo = data
    licInfoForm.dialogVisible = true
}

// 新条数
const handleSizeChange = (val: number) => {
    licInfoTable.pageSize = val;
    initLicInfo(searchValue.value, licInfoTable.pageNo, licInfoTable.pageSize)
};

// 新页数
const handleCurrentChange = (val: number) => {
    licInfoTable.pageNo = val;
    initLicInfo(searchValue.value, licInfoTable.pageNo, licInfoTable.pageSize)
};

const onConfirm = () => {
    licInfoRef.value?.validate((valid: any, fields: any) => {
        if (valid) {
            if (licInfoForm.title === '新增') {
                licInfoCreate(licInfoForm.formLicInfo).then((res: any) => {
                    if (res.code === 200) {
                        initLicInfo(searchValue.value, licInfoTable.pageNo, licInfoTable.pageSize)
                        licInfoRef.value?.resetFields()
                        ElMessage({ type: "success", message: "添加成功！" });
                        licInfoForm.dialogVisible = false
                    }// else ElMessage({ type: "error", message: "添加失败！" });
                })
            } else {
                licInfoUpdate(licInfoForm.formLicInfo).then((res: any) => {
                    if (res.code === 200) {
                        initLicInfo(searchValue.value, licInfoTable.pageNo, licInfoTable.pageSize)
                        licInfoRef.value?.resetFields()
                        ElMessage({ type: "success", message: "修改成功！" });
                        licInfoForm.dialogVisible = false
                    } // else ElMessage({ type: "error", message: "修改失败！" });
                })
            }
        } else {
            console.log("校验失败", fields);
        }
    })

}
// 删除
const handleDelete = (id: number) => {
    ElMessageBox.confirm("请确认删除?", "删除", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(() => {
            licInfoDelete(id).then((res: any) => {
                if (res.code === 200) {
                    initLicInfo();
                    ElMessage({
                        type: "success",
                        message: "删除成功！",
                    });
                }
            });
        })
        .catch(() => {
            ElMessage({
                type: "info",
                message: "取消删除！",
            });
        });
}

// 导出
const handleExport = (data: any) => {
    console.log(data);
    ElMessageBox.confirm("确认导出文件?", "导出", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(() => {
            licInfoFileCreate(data.macAddress, data.effectiveTime, data.verificationInterval).then((res: any) => {
                const content = res;
                const blob = new Blob([content])
                const downloadElement = document.createElement('a')
                // 创建下载的链接
                const href = window.URL.createObjectURL(blob)
                downloadElement.href = href
                // 下载后文件名
                downloadElement.download = 'lic' + data.macAddress + '.lqlic';
                document.body.appendChild(downloadElement)
                // 点击下载
                downloadElement.click()
                // 下载完成移除元素
                document.body.removeChild(downloadElement)
                // 释放掉blob对象
                window.URL.revokeObjectURL(href)
            });
        })
        .catch(() => {
            ElMessage({
                type: "info",
                message: "取消导出！",
            });
        })
}

const handleClose = () => {
    licInfoRef.value?.resetFields()
    licInfoForm.dialogVisible = false
}

// 列表数据 macAddress?: string, pageNo?: number, pageSize?: number
const initLicInfo = (macAddress?: string, pageNo?: number, pageSize?: number) => {
    licInfoList(macAddress, pageNo, pageSize).then((res: any) => {
        if (res.code === 200) {
            licInfoTable.licInfoData = res.data.records
            licInfoTable.total = res.data.total
            licInfoTable.loading = false
        }
    })
}

initLicInfo()
</script>