<script setup>
import { bannerlist,bannerupload,banneradd,banneredit,bannerdelete } from '@/api/api.js';
import {formatter} from '@/hooks/mixins'
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import $ from 'jquery'

let PageIndex = ref(0)
let total = ref(0)
let pageSize = ref(15)
let ispage = ref(true)
let listLoading = ref(false)
let tableData = ref([])
let aeDialog = ref(false)
let uploadloading = ref(false)
let isadd = ref(true)
let aeForm = reactive({
    img_url:'',
    banner_type:1,
    jump_url:'',
})
const aerules = reactive({
    img_url:[{required:true,message:'请上传图片',trigger:'blur'}],
    jump_url:[{required:true,message:'请输入跳转链接',trigger:'blur'}],
})
function getlist(){  //获取用户列表
    let params={
        CurrentIndex:PageIndex.value,
        PageSize:pageSize.value,
        BannerType:1,
        KeyWord:''
    }
    listLoading.value = true;
    bannerlist(params).then((res) => {
        if( res.Ret === 200 ){
            tableData.value = res.Data.List || [];
            total.value=parseInt(res.Data.Paging.Totals||0);
        }
        listLoading.value = false;
    });
}
getlist()
function clickinput(){  //上传模拟点击
    $("#file").click();
}
function fileSelected(){  //选择文件上传
    if( document.getElementById('file').files[0] ){
        let hostfile = document.getElementById('file').files[0];
        let size = Math.floor(hostfile.size / 1024 / 1024);
        if( size>200 ){
            ElMessage.error('上传文件大小不能大于200M！');
            hostfile = {};
            return false
        }
        if( hostfile.name.toLowerCase().includes('.png') || hostfile.name.toLowerCase().includes('.jpg') || hostfile.name.toLowerCase().includes('.jpeg') ){
            let form = new FormData();
            form.append('file',hostfile);  //hostfile.name
            uploadloading.value=true;
            bannerupload(form).then((res) => {
                if( res.Ret === 200 ){
                    aeForm.img_url=res.Data.ResourceUrl;
                }
                uploadloading.value=false;
                $("#file").val('');
                hostfile = {};
            });
        }else{
            ElMessage.error('上传文件格式不正确！');
        }
    } 
}
function edititem(item){  //去编辑
    aeForm.banner_id = parseInt(item.Id)
    aeForm.img_url = item.ImageUrl
    aeForm.jump_url = item.JumpUrl
    Object.assign(aeForm,{
        banner_id:parseInt(item.Id),
        img_url:item.ImageUrl,
        jump_url:item.JumpUrl,
        banner_type:1
    })
    isadd.value=false;
    aeDialog.value=true;
}
function deleteitem(item){  //删除
    ElMessageBox.confirm('确认删除吗?','提示',{
        type:'warning'
    }).then(() => {
        bannerdelete({BannerId:parseInt(item.Id)}).then(res =>{
            if( res.Ret === 200 ){
                ElMessage.success( res.Msg );
                getlist();
            }
        });
    }).catch(() => {});
}
let aeFormRef = ref(null)
function saveDialog(){  //保存
    aeFormRef.value?.validate((valid)=>{
        if( valid ){
            let params={
                ImgUrl:aeForm.img_url,
                BannerType:aeForm.banner_type,
                JumpUrl:aeForm.jump_url
            };
            if( isadd.value ){
                banneradd(params).then(res =>{
                    if( res.Ret === 200 ){
                        ElMessage.success( '上传成功' );
                        getlist();
                        aeDialog.value=false;
                    }
                });
            }else{
                params.BannerId=aeForm.banner_id;
                banneredit(params).then(res =>{
                    if( res.Ret === 200 ){
                        ElMessage.success( '上传成功' );
                        getlist();
                        aeDialog.value=false;
                    }
                });
            }
        }
    });
}
function aeDialogTrue(){  //去新增
    Object.assign(aeForm,{
        img_url:'',
        jump_url:'',
        banner_type:1
    })
    isadd.value=true;
    aeDialog.value=true;
}
function handleCurrentChange(current){  //分页页码跳转
    PageIndex.value = current;
    getlist();
}
function handleSizeChange(val){    //分页页码改变
    pageSize.value=val;
    getlist();
}	
</script>
<template>
	<div id="bannerlist">
		<el-card class="box-card">
			<div slot="header" class="header">
				<el-button type="primary" @click="aeDialogTrue">添加banner</el-button>
			</div>
			<el-table :data="tableData" v-loading="listLoading" element-loading-text="数据加载中..." row-key="id" border default-expand-all :tree-props="{children:'children',hasChildren:'hasChildren'}">
				<el-table-column prop="Id" label="图片管理" align="center">
					<template #default="scope">
						<img :src="scope.row.ImageUrl" style="height:100px;" />
					</template>
				</el-table-column>
				<el-table-column prop="ClassifyName" label="跳转地址" align="center" min-width="140">
					<template #default="scope"> <span>{{scope.row.JumpUrl}}</span> </template>
				</el-table-column>
				<el-table-column prop="ModifyTime" label="更新时间" min-width="110" :formatter="formatter" sortable align="center"></el-table-column>
				<el-table-column label="操作" align="center">
					<template #default="scope">
						<div style="color:#4099ef; font-size:24px;">
							<span class="editsty" @click="edititem(scope.row)">编辑</span>
							&nbsp;&nbsp;
							<span class="deletesty" @click="deleteitem(scope.row)">删除</span>
						</div>
					</template>
				</el-table-column>
			</el-table>
			<el-col :span="24" class="toolbar">
		  		<el-pagination v-if="ispage" layout="total,prev,pager,next,jumper" background @current-change="handleCurrentChange" :page-size="pageSize" @size-change="handleSizeChange" :total="total" style="float:right;"></el-pagination>
		  	</el-col>
		</el-card>
		<!-- 添加账号弹框 -->
		<el-dialog :modal-append-to-body='false' :title="isadd?'新增banner':'编辑banner'" v-model="aeDialog" @open="" :close-on-click-modal="false" :center="true" class="dialogclass" width="510px">
			<template #header>
				<div style="display:flex;align-items:center;">
					<img :src="isadd?$icons.add:$icons.edit" style="color:#fff;width:16px;height:16px;margin-right:5px;">
					<span style="font-size:16px;">{{isadd?'新增banner':'编辑banner'}}</span>
				</div>
			</template>
			<el-form :model="aeForm" :rules="aerules" ref="aeFormRef" label-position="right" label-width="0px" class="demo-aeForm" id="login-container" @submit.native.prevent>
				<el-form-item prop="img_url" label="">
					<input type="file" name="file" @change="fileSelected()" id="file" class="true-file" style="display:none;">
					<el-input type="text" v-model="aeForm.img_url" placeholder="上传图片" readonly size="medium" style="width:350px;"></el-input>
					<el-button type="primary" size="medium" @click.native="clickinput" :loading="uploadloading">{{uploadloading?'上传中':'选择图片'}}</el-button>
				</el-form-item>
				<el-form-item prop="jump_url" label="">
					<el-input type="text" v-model="aeForm.jump_url" placeholder="绑定跳转链接" size="medium" style="width:430px;"></el-input>
				</el-form-item>
			</el-form>
			<div class="dialog-footer" style="text-align:right;margin:20px 0;">
				<el-button type="primary" plain size="medium" @click.native="aeDialog=false">取 消</el-button>
				<el-button type="primary" size="medium" @click.native="saveDialog">保 存</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<style scoped lang="scss">
	#bannerlist{
		overflow:hidden;
		.header{
			margin-bottom: 20px;
		}
	}
</style>