<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%" row-key="id"
            v-loading="licInfoTable.loading">
            <el-table-column type="expand">
                <template #default="scope">
                    <div v-if="scope.row.dockerServices.length === 0">
                        <el-empty description="暂无镜像" :image-size="100" />
                    </div>
                    <div v-else style="padding: 20px 40px;">
                        <div style="display: flex; justify-content: space-between; margin-bottom: 20px;">
                            <span style="font-size: 16px; font-weight: 700;">docker镜像</span>
                            <el-button type="primary" size="small" @click="addMirror(scope.row)">添加镜像</el-button>
                        </div>
                        <el-table :data="scope.row.dockerServices" style="width: 100%">
                            <el-table-column prop="name" label="镜像名" align="center" />
                            <el-table-column prop="contextPath" label="服务路径" align="center" />
                            <el-table-column prop="version" label="版本" align="center" />
                            <el-table-column label="操作" width="200" align="center">
                                <template #default="item">
                                    <el-button size="small" type="danger"
                                        @click="handleServiceDelete(scope.row, item.row.id)">删除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="lqLicName" label="项目名称" 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="操作" width="200">
                <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>

    <mirror-form ref="mirrorFormRef" v-model:mirror-dialog="mirrorDialog" @mirror-data="getMirrorData" />
</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";
import mirrorForm from './components/mirrorForm.vue'

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

const licInfoRef = ref()
const mirrorFormRef = ref()

const searchValue = ref()
const mirrorDialog = ref()

const licInfoForm = reactive<any>({
    dialogVisible: false,
    title: '新增',
    formLicInfo: {
        dockerServices: [],
        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.dialogVisible = true
}

const mirrorRow = ref() as any

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 {
                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 {
            console.log("校验失败", fields);
        }
    })

}

const addMirror = (row: any) => {
    mirrorDialog.value = true
    mirrorFormRef.value.title = '新增镜像'
    mirrorRow.value = JSON.parse(JSON.stringify(row))
}

const getMirrorData = async (data: any) => {
    mirrorRow.value.dockerServices.push(data)
    const res: any = await licInfoUpdate(mirrorRow.value)
    if (res.code === 200) {
        ElMessage.success('添加成功')
        initLicInfo(searchValue.value, licInfoTable.pageNo, licInfoTable.pageSize)
        mirrorDialog.value = false
    }
}

// 删除
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 handleServiceDelete = (row: any, id: number) => {
    ElMessageBox.confirm("请确认删除?", "删除", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(async () => {
            let index;
            row.dockerServices.map((item: any, i: number) => {
                if (item.id === id) {
                    index = i
                }
            })
            row.dockerServices.splice(index, 1)
            const res: any = await licInfoUpdate(row)
            if (res.code === 200) {
                ElMessage.success('添加成功')
                initLicInfo(searchValue.value, licInfoTable.pageNo, licInfoTable.pageSize)
                mirrorDialog.value = false
            }
        })
        .catch(() => {
            ElMessage({
                type: "info",
                message: "取消删除！",
            });
        });
}

// 导出
const handleExport = (data: any) => {
    ElMessageBox.confirm("确认导出文件?", "导出", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(() => {
            licInfoFileCreate(data).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.formLicInfo = {
        dockerServices: [],
        macAddress: '',
        effectiveTime: '',
        fileEffectiveTime: '',
        verificationInterval: '',
        moduleVerification: '',
        lqLicName: ''
    }
    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>

<style lang="scss" scoped>
:deep(.el-empty) {
    padding: 0;
}

:deep(.el-descriptions__title) {
    margin-left: 20px;
}

:deep(.el-descriptions__extra) {
    margin-right: 20px;
}

:deep(.is-bordered-label) {
    width: 100px;
}
</style>