<template>
  <div class="table_page">
  <div style="margin-bottom: 15px">
    <el-button  type="primary" slot="reference" @click="addCarouse">添加图片</el-button>
    <el-popconfirm
        confirm-button-text='确定'
        cancel-button-text='取消'
        icon="InfoFilled"
        icon-color="red"
        title="您确定批量删除这些数据吗？"
        @confirm=""
        width=180
    >
      <template #reference>
        <el-button type="danger" slot="reference">批量删除 <el-icon style="margin-left: 5px;"><Remove /></el-icon></el-button>
      </template>
    </el-popconfirm>
  </div>
  <el-table :data="tableData" border stripe header-cell-class-name="headerBg" :cell-style="{textAlign: 'center'}"
            @selection-change="handleSelectionChange" :header-cell-style="{'text-align': 'center'}">
    <el-table-column type="selection" width="55"></el-table-column>
    <el-table-column prop="id" label="图片序号" width="50"></el-table-column>
    <el-table-column prop="url" label="图片">
      <template #default="scope"><img :src="downloadUrl + scope.row.url" alt="" style="height: 50px;"></template>
    </el-table-column>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button type="success" @click="editCarouse(scope.row)">编辑<i class="el-icon-edit"></i></el-button>
        <el-popconfirm
            confirm-button-text='确定'
            cancel-button-text='取消'
            icon="el-icon-info"
            icon-color="red"
            title="您确定删除吗？"
            @confirm="deleteCarouse(scope.row.id)"
        >
          <template #reference>
            <el-button type="danger">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
  </div>
  <div style="padding: 10px 0">
    <!-- 分页器 -->
    <el-pagination
        :current-page="searchParams.current"
        :page-size="searchParams.pageSize"
        :page-sizes="[2, 5, 10, 20]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :small="null"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
    />
  </div>
  <!-- 编辑/详情表单 -->
  <el-dialog v-model="DialogVisible" :title="title" >
    <el-form label-width="100px" :disabled="disabled" v-loading="loading">
      <el-form-item label="轮播图">
        <el-upload
            v-model:file-list="carouseImg"
            ref="uploadImg"
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            multiple="true"
            :on-remove="removePic"
            @change="(event: any) => handleChange(event)"
            :on-exceed="Exceed_ProductImg"
            limit="1" >
          <el-icon>
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer >
      <span class="dialog-footer">
        <el-button @click="restForm" :disabled="loading">取消</el-button>
        <el-button type="primary" @click="saveEdit" :disabled="loading">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { type UploadProps } from 'element-plus';
import myAxios from '@/api/myAxios';
import {ref, onMounted, inject } from 'vue'
import { WarnInfo, SuccessInfo  } from '@/utils/messageInfo';
import { downloadUrl } from '@/utils/formatImgUpload'

const DialogVisible = ref(false);  //表单显示
const disabled = ref(false)
const editForm : any= ref({})
const uploadImg : any = ref()  //图片上传的ref绑定
const carouseImg: any = ref([]) //给商品中心页面编辑商品使用
const reload : any = inject("reload")  //页面重新刷新
const tableData = ref([])  //获取的所有数据
const total = ref(0) //筛选条数
const fileSimple = ref() //单个文件
//请求参数
const searchParams: any = ref({
  //当前页码
  current: 1,
  //每页显示条数
  pageSize: 5,
  //轮播图类别
  type: '服务类',
  sortOrder: 'descend'
})

const title : any = ref('编辑表单')
const loading = ref(false)

onMounted(() => {
  getCourseList()
})

const getCourseList = async () => {
  const res = await myAxios.post('/banner/query/web',{
    current: searchParams.value.current,
    pageSize: searchParams.value.pageSize,
    type: searchParams.value.type,
    sortOrder: searchParams.value.sortOrder
  })
  // console.log('分页后端返回---->',res.data)
  if(res.data.code === 1) {
    tableData.value = res.data.data.records
    total.value = parseInt(res.data.data.total)
  }
}

const handleSelectionChange  = (val:any)=>{
  console.log(val)
}
// 处理行数大小变化
const handleSizeChange = (newSize:any) => {
  searchParams.value.pageSize = newSize //新的页面条数
  getCourseList()
};
// 处理当前页变化
const handleCurrentChange = (Current:any) => {
  searchParams.value.current = Current //新的当前页面
  getCourseList()
};

const restForm =()=> {
  DialogVisible.value = false
  carouseImg.value.splice(0,1)
  editForm.value.url = ''
}

const deleteCarouse = async (id: number) =>{  //删除单个轮播图
  const res = await myAxios.post('/banner/delete',{ id: id })
  if(res.data.code === 1) {
    SuccessInfo('删除图片成功')
    await getCourseList()
  } else {
    WarnInfo('服务错误')
  }
}

const editCarouse = async (obj: any) =>{
  title.value = '编辑轮播图'
  carouseImg.value.splice(0,carouseImg.value.length)
  carouseImg.value.push({   //编辑展示
    url: downloadUrl + obj.url
  })
  editForm.value = JSON.parse(JSON.stringify(obj))
  DialogVisible.value = true
}

const saveEdit = async ()=>{  //保存表单
  if(editForm.value.url === '') {
    WarnInfo('图片不能为空')
    return
  }
  DialogVisible.value = false
  if(editForm.value.id == undefined) {
    const res = await myAxios.post('/banner/add',{
      type: '服务类',
      url: editForm.value.url
    })
    if(res.data.code === 1) {
      DialogVisible.value = false
      await getCourseList()
      reload()
      return
    }
  } else {
    const res = await myAxios.post('/banner/update',{ ...editForm.value })
    if(res.data.code === 1) {
      DialogVisible.value = false
      await getCourseList()
      reload()
      SuccessInfo('更新成功')
      return
    }
  }
  WarnInfo('服务错误')
}

const removePic : UploadProps['onRemove'] = (uploadFile, uploadFiles) => {    //uploadFile表示当前删除的图片，uploadFiles是还剩余的图片信息
  carouseImg.value.splice(0,1)
  editForm.value.url = ''
}

const Exceed_ProductImg: UploadProps['onExceed'] = (files) => { //覆盖商品照片   'onExceed'当文件个数超过限制时，做出的判断
  WarnInfo('请移除之前的再上传')
}

const handleChange = async (file: any ) => {
  loading.value = true
  fileSimple.value = file
  let formData = new FormData()  //这一步很重要 创建一个FormData对象
  formData.append("file", fileSimple.value.raw)  //fileSimple.value.raw 才是文件主体  将其以文件的格式插入formData
  const res = await myAxios({   //编写请求，与以前的请求不同，这一次要指定好头部类型和文件类型
    url: '/file/uploadFile',
    method: 'post',
    headers: {
      'content-Type': 'multipart/form-data'
    },
    data: {
      biz: "test",
      // 取出formData对象中的file
      file: formData.get("file")
    }
  })
  if(res.data.code === 1) {
    editForm.value.url = res.data.data
    loading.value = false
    SuccessInfo('图片上传成功')
  }
}

//添加轮播图
const addCarouse = async () => {
  restForm()
  title.value = '添加轮播图'
  DialogVisible.value = true
}

</script>


<style scoped>
.table_page {
  min-width: 1000px;
  overflow: auto;
}
</style>