<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="应用名称" prop="appName">
                <el-input v-model="queryParams.appName" placeholder="请输入应用名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="创建者" prop="createBy">
                <el-input v-model="queryParams.createBy" placeholder="请输入创建者" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 200px;">
                    <el-option label="正常" :value="1" />
                    <el-option label="关闭" :value="0" />
                </el-select>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd"
                    v-hasPermi="['system:app:add']">新增</el-button>
            </el-col>

            <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
                    v-hasPermi="['system:app:remove']">删除</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="docList" @selection-change="handleSelectionChange" :row-key="getRowKey">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column type="index" label="序号" align="center" width="80" />
            <el-table-column label="应用名称" align="center" prop="appName" />
            <el-table-column label="显示顺序" align="center" prop="appSort" width="100" />
            <el-table-column label="状态" align="center" prop="status">
                <template #default="scope">
                    <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
                </template>
            </el-table-column>
            <el-table-column label="创建者" align="center" prop="createBy" />
            <el-table-column label="创建时间" align="center" prop="createTime" width="180">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-tooltip content="修改" placement="top" v-hasPermi="['system:app:edit']">
                        <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
                    </el-tooltip>
                    <el-tooltip content="删除" placement="top" v-hasPermi="['system:app:remove']">
                        <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
                    </el-tooltip>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改应用管理对话框 -->
        <el-dialog :title="title" v-model="open" width="700px" append-to-body destroy-on-close>
            <el-form ref="docRef" :model="form" :rules="rules" label-width="9em">
                <el-form-item label="应用名称" prop="appName">
                    <el-input v-model="form.appName" placeholder="请输入应用名称" />
                </el-form-item>
                <el-form-item label="角色" prop="roleIds">
                    <el-select v-model="form.roleIds" multiple placeholder="请选择角色" style="width: 100%;">
                        <el-option v-for="role in roleOptions" :key="role.roleId" :label="role.roleName"
                            :value="role.roleId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="链接" prop="appUrl">
                    <el-input v-model="form.appUrl" placeholder="请输入应用链接" />
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="form.status">
                        <el-radio :label="'1'">正常</el-radio>
                        <el-radio :label="'0'">关闭</el-radio>
                    </el-radio-group>
                </el-form-item>
                <!-- <el-form-item label="是否为首页应用" prop="homePage">
                    <el-radio-group v-model="form.homePage">
                        <el-radio :label="'1'">是</el-radio>
                        <el-radio :label="'0'">否</el-radio>
                    </el-radio-group>
                </el-form-item> -->
                <el-form-item label="首页角色" prop="homeRoleIds">
                    <el-select v-model="form.homeRoleIds" multiple placeholder="请选择角色" style="width: 100%;">
                        <el-option v-for="role in roleOptions" :key="role.roleId" :label="role.roleName"
                            :value="role.roleId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="显示顺序" prop="appSort">
                    <el-input-number v-model="form.appSort" :min="1" :max="999" controls-position="right"
                        placeholder="请输入显示顺序" />
                </el-form-item>
                <el-form-item label="图标" prop="workbenchIcon">
                    <el-upload ref="iconUploadRef" :limit="1" accept="image/*" :headers="upload.headers"
                        :action="upload.url" :file-list="upload.iconFileList" :disabled="false"
                        :on-success="handleIconSuccess" :on-remove="handleIconRemove" :auto-upload="true"
                        list-type="picture-card">
                        <el-icon class="avatar-uploader-icon">
                            <plus />
                        </el-icon>
                        <template #tip>
                            <div class="el-upload__tip">请上传图标，建议尺寸 64x64px</div>
                        </template>
                    </el-upload>
                </el-form-item>


            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="cancel">取 消</el-button>
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="App">
import { onMounted, ref, reactive, toRefs, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled, Plus } from '@element-plus/icons-vue'
import Pagination from '@/components/Pagination/index.vue'
import RightToolbar from '@/components/RightToolbar/index.vue'
import { parseTime } from '@/utils/ruoyi'
import { getToken } from '@/utils/auth'
import { listApp, getApp, deleteApp, addApp, updateApp } from '@/api/system/app'
import { listRole } from '@/api/system/role'
const { proxy } = getCurrentInstance()

// 使用真实API接口，已从@/api/system/workDocu导入
const sys_normal_disable = [
    { label: '正常', value: '1' },
    { label: '关闭', value: '0' }
]

const getRowKey = (row) => {
    return row.appId
}

// 表格数据
const docList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')

// 角色选项
const roleOptions = ref([])

// 上传相关

const iconUploadRef = ref(null)


const upload = reactive({

    iconFileList: [],

    // 是否显示弹出层
    open: false,
    // 弹出层标题
    title: "",
    // 是否禁用上传
    isUploading: false,
    // 是否更新已经存在的用户数据
    updateSupport: 0,
    // 设置上传的请求头部
    headers: { Authorization: "Bearer " + getToken() },
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + "/common/upload"
})




const handleIconSuccess = (response, file, fileList) => {
    if (response.code === 200) {
        form.value.workbenchIcon = response.url
        ElMessage.success('图标上传成功')
    } else {
        ElMessage.error(response.msg || '图标上传失败')
    }
}


// 图标移除处理
const handleIconRemove = (file, fileList) => {
    form.value.workbenchIcon = '';
}






// 表单数据
const data = reactive({
    form: {
        appId: null,
        appName: '',
        roleIds: [],
        homeRoleIds: [],
        appUrl: '',
        status: '1',
        // homePage: '0',
        workbenchIcon: '',
        homeChart: '',
        appFile: '',
        appSort: 1

    },
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        appName: '',
        createBy: '',
        status: null
    },
    rules: {
        appName: [
            { required: true, message: '应用名称不能为空', trigger: 'blur' }
        ],
        appSort: [
            { required: true, message: '请输入显示顺序', trigger: 'blur' }
        ],
        workbenchIcon: [
            { required: true, message: '请上传图标', trigger: 'change' }
        ],
    }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询应用列表 */
const getList = () => {
    loading.value = true
    listApp(queryParams.value).then(response => {
        docList.value = response.rows
        total.value = response.total
        loading.value = false
    })
}

// 取消按钮
const cancel = () => {
    open.value = false
    reset()
}

// 表单重置
const reset = () => {
    form.value = {
        appId: null,
        appName: '',
        roleIds: [],
        homeRoleIds: [],
        appUrl: '',
        status: '1',
        // homePage: '0',
        workbenchIcon: '',
        homeChart: '',
        appFile: '',
        appSort: 1
    }
    // 清空文件列表

    upload.iconFileList = []

    if (proxy?.$refs?.docRef) {
        proxy.$refs.docRef.resetFields()
    }
}

/** 搜索按钮操作 */
const handleQuery = () => {
    queryParams.value.pageNum = 1
    getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
    if (proxy?.$refs?.queryRef) {
        proxy.$refs.queryRef.resetFields()
    }
    handleQuery()
}

///** 多选框选中数据 */
const handleSelectionChange = (selection) => {
    ids.value = selection.map(item => item.appId)
    single.value = selection.length != 1
    multiple.value = !selection.length
}

/** 新增按钮操作 */
const handleAdd = () => {
    reset()
    open.value = true
    title.value = '添加工作文档'
}

/** 修改按钮操作 */
const handleUpdate = (row) => {
    reset()

    const _id = row?.appId || ids.value
    getApp(_id).then(response => {
        form.value = response.data;


        if (response.data.sysRoleList) {
            form.value.roleIds = response.data.sysRoleList.map(item => item.roleId)

        }
        if (response.data.homePageSysRoleList) {
            form.value.homeRoleIds = response.data.homePageSysRoleList.map(item => item.roleId)
        }

        if (response.data.workbenchIcon) {
            upload.iconFileList = [{
                name: '',
                url: response.data.workbenchIcon
            }]
        }



        open.value = true
        title.value = '修改应用管理'
    })
}

/** 提交按钮 */
const submitForm = () => {
    if (proxy?.$refs?.docRef) {
        proxy.$refs.docRef.validate((valid) => {
            if (valid) {
                let sysRoleList = roleOptions.value.filter(item => form.value.roleIds.includes(item.roleId))
                let homePageSysRoleList = roleOptions.value.filter(item => form.value.homeRoleIds.includes(item.roleId))
                let params = {
                    ...form.value,
                        sysRoleList: sysRoleList,
                        homePageSysRoleList: homePageSysRoleList
                }
                if (form.value.appId != undefined) {
                    updateApp(params).then(response => {
                        ElMessage.success('修改成功')
                        open.value = false
                        getList()
                    })
                } else {
                    addApp(params).then(response => {
                        ElMessage.success('新增成功')
                        open.value = false
                        getList()
                    })
                }
            }
        })
    }
}

/** 删除按钮操作 */
const handleDelete = (row) => {
    const _ids = row?.appId || ids.value;

    // 检查是否有要删除的ID
    if (!_ids || (Array.isArray(_ids) && _ids.length === 0)) {
        ElMessage.warning('请选择要删除的数据项')
        return
    }

    if (proxy?.$modal) {
        proxy.$modal.confirm('是否确认删除数据项？').then(() => {
            const deleteIds = Array.isArray(_ids) ? _ids.join(',') : _ids
            return deleteApp(deleteIds)
        }).then(() => {
            getList()
            ElMessage.success('删除成功')
        }).catch((error) => {
            console.error('删除失败:', error)
            ElMessage.error('删除失败')
        })
    }
}

// 获取角色列表
const getRoleList = () => {
    listRole().then(response => {
        roleOptions.value = response.rows || []
    })
}

// 页面加载时获取数据
onMounted(() => {
    getList()
    getRoleList()
})
</script>

<style scoped>
.app-container {
    padding: 20px;
}

.mb8 {
    margin-bottom: 8px;
}

.fixed-width {
    width: 140px;
}

.small-padding .cell {
    padding: 10px 5px;
}

.dialog-footer {
    text-align: right;
}

/* 图片上传预览样式 */
.avatar {
    width: 100px;
    height: 100px;
    object-fit: contain;
    border-radius: 6px;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    transition: border-color 0.3s;
}

.avatar-uploader-icon:hover {
    border-color: #409eff;
}

/* 图片上传组件样式优化 */
:deep(.el-upload--picture-card) {
    width: 100px;
    height: 100px;
    line-height: 100px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
    width: 100px;
    height: 100px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item-thumbnail) {
    width: 100%;
    height: 100%;
    object-fit: contain;
}
</style>