<script setup>
import { ref, reactive } from 'vue'
import {InfoFilled,Search} from '@element-plus/icons-vue'
import {apiImgSource,apiMediaCommon} from '@/api/media'
import {cloneDeep} from 'lodash'
const tableQuery = reactive({
    keyWord:'',
    labels:'',
    currentPage:1,
    pageSize:10,
    totals:0,
    sortType:''
})

const tableColumns = [
    {label:'图片预览',key:'SrcUrl',},
    {label:'图片名称',key:'ImgName',},
    {label:'添加时间',key:'CreatedTime',width:250,sortable:true},
    {label:'关联标签',key:'PermissionName',},
]
let picUploadShow = ref(false)
let curPicData = ref({})
function handlePicUploadShow(data={}){
    curPicData.value = cloneDeep(data)
    formRef.value?.clearValidate()
    picUploadShow.value = true
}
function handleEdit(data){
    handlePicUploadShow(data)
}
function handleDelete(data){
    ElMessageBox.confirm(
        '删除后不可恢复，是否确认删除该图片？',
        '提示',
        {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        }
    )
    .then(() => {
        apiImgSource.deleteImgSource({
            ImageId:data.Id
        }).then(res=>{
            if(res.Ret!==200) return 
            ElMessage.success('删除成功')
            getTableData()
        })
    }).catch(() => {})
}
const labelOptions = ref([])
function getLabelOptions(){
    apiMediaCommon.getPermissionList().then(res=>{
        if(res.Ret!==200) return
        labelOptions.value = res.Data.List||[]
    })
}
getLabelOptions()
const tableLoading = ref(false)
const tableData = ref([])
function getTableData(){
    tableLoading.value = true
    apiImgSource.getImgSourceList({
        KeyWord:tableQuery.keyWord,
        PermissionIds:Array.isArray(tableQuery.labels)?tableQuery.labels.join(','):'',
        SortType:tableQuery.sortType,
        CurrentIndex:tableQuery.currentPage,
        PageSize:tableQuery.pageSize
    }).then(res=>{
        tableLoading.value = false
        if(res.Ret!==200) return 
        tableData.value = res.Data.List||[]
        tableQuery.totals = res.Data.Paging.Totals||0
    })
}
getTableData()
function handlePageChange(page){
    tableQuery.currentPage = page
    getTableData()
}
function handleUploadImg(file){
    //图片大小和格式限制
    const {size,type} = file.file
    const sizeLimit = 500*1024
    if(!['image/png','image/jpeg'].includes(type)){
        ElMessage.warning('仅支持png、jpg格式的图片')
        return
    }
    if(size>sizeLimit){
        ElMessage.warning('资源库图片不能超过500kb')
        return
    }
    let form = new FormData();
    form.append('File',file.file);
    apiImgSource.uploadImgFile(form).then(res=>{
        if(res.Ret!==200) return 
        curPicData.value.SrcUrl = res.Data?.Url||''
    })
}
const rules = {
    SrcUrl:[{required:true,message:'请上传图片'}],
    ImgName:[{required:true,message:'请输入图片名称'}],
    PermissionId:[{required:true,message:'请选择关联标签'}],
}
const formRef = ref(null)
async function handleSavePic(){
    try{
        await formRef.value?.validate()
    }catch(e){ return }
    const params = {
        ImageName:curPicData.value.ImgName,
        SrcUrl:curPicData.value.SrcUrl,
        PermissionId:curPicData.value.PermissionId
    }
    const res = curPicData.value.Id
    ? await apiImgSource.editImgSource({...params,ImageId:curPicData.value.Id})
    :await apiImgSource.addImgSource(params)
    if(res.Ret!==200) return 
    ElMessage.success(`${curPicData.value.Id?'编辑':'添加'}成功`)
    getTableData()
    picUploadShow.value = false
}
function handleSortChange({order,prop}){
    tableQuery.sortType = order==='ascending'?'asc':'desc'
    getTableData()
}
</script>

<template>
    <div class="picture-libraray-wrap">
        <div class="top-box">
            <el-button type="primary" @click="handlePicUploadShow({})" v-permission="'source:uploadImage'">上传图片</el-button>
            <el-tooltip
                class="box-item"
                effect="dark"
                content="应用于小程序报告列表页，取产品关联的第一个标签展示"
                placement="top-start"
            >
            <el-icon style="margin-left: 5px;"><InfoFilled /></el-icon>
            </el-tooltip>
            <el-cascader v-model="tableQuery.labels" @change="handlePageChange(1)" placeholder="标签"
                :options="labelOptions"
                collapse-tags
                collapse-tags-tooltip
                clearable
                :props="{
                    value:'id',
                    label:'name',
                    emitPath:false,
                    multiple:true
                }"
            ></el-cascader>
            <el-input style="width:426px;" :prefix-icon="Search" clearable 
                placeholder="请输入图片名称"
                v-model="tableQuery.keyWord"
                @input="handlePageChange(1)"
            />
        </div>
        <div class="table-box">
            <el-table stripe border :data="tableData" element-loading-text="数据加载中..." v-loading="tableLoading" @sort-change="handleSortChange">
                <el-table-column 
                    align="center"
                    v-for="column in tableColumns" :key="column.key"
                    :prop="column.key" :label="column.label" :sortable="column.sortable" :width="column.width">
                    <template #default="{row}">
                        <div v-if="column.key==='SrcUrl'" style="color:#086CE0;cursor: pointer;">
                            <el-image 
                                v-if="row[column.key]"
                                fit="cover"
                                :src="row[column.key]||''" 
                                :preview-src-list="[row[column.key]||'']" 
                                style="display: inline-block;width:60px;height: 60px;" preview-teleported/>
                            <span v-else style="display: inline-block;width:60px;height: 60px;line-height: 60px;">-</span> 
                        </div>
                        <span v-else>{{ row[column.key]||'-' }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="{row}">
                        <el-link type="primary" :underline="false" @click="handleEdit(row)" style="margin-right: 20px;" v-permission="'source:edit'">编辑</el-link>
                        <el-link type="danger" :underline="false" @click="handleDelete(row)" v-permission="'source:delete'">删除</el-link>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                background
                layout="total,prev,pager,next,jumper"
                :current-page="tableQuery.currentPage"
                :page-size="tableQuery.pageSize"
                :total="tableQuery.totals"
                @current-change="handlePageChange"
                style=" justify-content: flex-end;border:1px solid #ebeef5;border-top: none;"
            />
        </div>
    </div>
    <el-dialog v-model="picUploadShow" :title="curPicData.Id?'编辑图片':'上传图片'" width="646px" draggable>
        <div class="content-wrap">
            <el-form label-width="95px" label-position="left" :model="curPicData" :rules="rules" ref="formRef">
                <el-form-item label="照片" prop="SrcUrl">
                    <ImageUpload
                        :imgUrl="curPicData.SrcUrl"
                        uploadHint="支持jpg、jpeg、png等格式，建议上传宽高比例为3:4的图片"
                        width="90px"
                        height="120px"
                        @upload="handleUploadImg"
                        @remove="curPicData.SrcUrl=''"
                    ></ImageUpload>
                </el-form-item>
                <el-form-item label="图片名称" prop="ImgName">
                    <el-input v-model="curPicData.ImgName" placeholder="请输入图片名称"></el-input>
                </el-form-item>
                <el-form-item label="关联标签" prop="PermissionId">
                    <el-cascader v-model="curPicData.PermissionId" placeholder="请选择关联品种" style="width: 100%;"
                        :options="labelOptions"
                        :props="{
                            value:'id',
                            label:'name',
                            emitPath:false,
                            multiple:false
                        }"
                    ></el-cascader>
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <div class="footer-wrap">
                <el-button type="primary" plain size="large" @click="picUploadShow = false">取消</el-button>
                <el-button type="primary" size="large" @click="handleSavePic">保存</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style scoped lang="scss">
.picture-libraray-wrap{
    .top-box{
        display: flex;
        justify-content: space-between;
        align-items: center;
        :deep(.el-cascader){
            margin-left: auto;
            margin-right: 20px;
        }
    }
    .table-box{
        margin-top: 25px;
    }
}
</style>
