<template>
  <div style="margin-bottom: 10px;">
    <el-button type="success" @click="showForm">添加类别</el-button>
    <el-button type="danger" @click="">删除类别</el-button>
  </div>

  <el-dialog v-model="dialogVisible" title="商品类别" width="500">
    <el-form :model="typeForm" label-width="auto" style="max-width: 600px">
      <el-form-item label="添加类别图片">
        <!-- 下面的event的作用,传入当前事件对象 -->
        <el-upload 
          action="#" 
          list-type="picture-card" 
          :auto-upload="false" 
          multiple="true"
          :on-remove="handleRemove"
          @change="(event: any) => handleChange(event)" 
          limit="1" >
          <el-icon>
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="类别名">
        <el-input v-model="typeForm.typeName" />
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="typeForm.typeIntro" />
      </el-form-item>
    </el-form>
    <template #footer #default="{ row, $index }">
      <div class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="addOrUpdateType">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 数据展示层 -->
  <el-table :data="tableData" border style="width: 100%;" :header-cell-style="{ 'text-align': 'center' }"
    @selection-change="handleSelectionChange" :cell-style="{ 'text-align': 'center', 'font-size': '16px' }">
    <el-table-column type="selection" width="55"></el-table-column>
    <el-table-column prop="id" label="类别编号" width="150"></el-table-column>
    <el-table-column prop="typeUrl" label="类别图片" width="300">
      <!-- 插槽，拿到父组件的值typeUrl -->
      <!-- scope 提供了关于当前行的信息 -->
      <template #default="scope"><img :src="scope.row.typeUrl" alt="" style="height: 50px;"></template>
    </el-table-column>
    <el-table-column prop="typeName" label="类别名称" width="150"></el-table-column>
    <el-table-column prop="typeIntro" label="备注"></el-table-column>
    <el-table-column prop="operation" label="操作">
      <template #default="scope">
        <el-button type="success" @click="editShowForm(scope.$index, scope.row)">修改类别</el-button>
        <!-- scope.$index是当前行 第一行为0 -->
        <el-popconfirm class="ml-5" confirm-button-text='确定' cancel-button-text='取消' icon="InfoFilled" icon-color="red"
          title="是否确认删除" @confirm="Delete_type(scope.row.id)" width=180>
          <template #reference>
            <el-button style="height: 25px" class="ml-5" type="danger">删除类别</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup lang="ts">
import { ElMessage ,type UploadProps} from 'element-plus';
import { onMounted, ref } from 'vue'
import myAxios from '@/api/myAxios';
const fileSimple = ref()  //单个文件
const selectedItems = ref([]) 
const dialogVisible = ref(false)
//表单数据
const typeForm = ref({
  id: 0,
  typeName: '',
  typeUrl: '',
  typeIntro: ''
})
//表格数据
const tableData = ref([])
//旗帜 表示点击添加类别(0)  和  点击修改类别两个状态(1)，因为我们共用一个表格 
const flag = ref(0)
const typeList = ref([])
//老套路 页面加载必须获取类别列表
onMounted(() => {
  getTypeList()
})
//获取类别列表
const getTypeList = async () => {
  const res = await myAxios.post('/category/list')
  // console.log(res.data.data)
  if (res.data.code === 1) {
    tableData.value = res.data.data
  } else {
    ElMessage.error('获取类别列表失败，请检查服务')
  }
}
//上传图片，一张图片，不需要flag值
const handleChange = async (file: any) => {
  fileSimple.value = file
  let formData = new FormData()  //这一步很重要 创建一个FormData对象
  formData.append("file", fileSimple.value.raw)  //fileSimple.value.raw 才是文件主体  将其以文件的格式插入formData
  const res = await myAxios({   //编写请求，与以前的请求不同，这一次要指定好头部类型和文件类型
    url: '/file/upload/server/not_login',
    method: 'post',
    headers: {
      'content-Type': 'multipart/form-data'
    },
    data: {
      biz: "test",
      file: formData.get("file")  // 取出formData对象中的file
    }
  })
  if ( res.data.code === 1) {
    typeForm.value.typeUrl = res.data.data
  }
}
//上传图片移除 --逻辑上移除
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}
//新增类别
const showForm = async () => {
  dialogVisible.value = true;
  flag.value = 0
}
//取消
const cancel = () => {
  dialogVisible.value = false
  resetForm()
}
//新增类别  很繁杂 不知道怎么改 只能不断判空
const addOrUpdateType = async () => {
  //判空(*后期引入对象判空)
  if (typeForm.value.typeName?.indexOf(' ') !== -1 ||
    typeForm.value.typeName == '' || typeForm.value.typeUrl == '') {
    ElMessage({
      type: 'warning',
      message: '不能为空格/空字符串'
    })
    return
  }
  //取消展示表单
  dialogVisible.value = false;
  if (flag.value === 0) {
    const res = await myAxios.post('/category/add', {
      //对齐后端请求体
      typeName: typeForm.value.typeName,
      typeUrl: typeForm.value.typeUrl,
      typeIntro: typeForm.value.typeIntro
    })
    if (res.data.code === 1) {
      //提交成功后，之间重置表格
      resetForm()
    } else {
      ElMessage.error('提交失败')
    }
  }
  if( flag.value === 1 ) {
    const res = await myAxios.post('/category/update',{
      id : typeForm.value.id,
      typeName: typeForm.value.typeName,
      typeUrl: typeForm.value.typeUrl,
      typeIntro: typeForm.value.typeIntro
    })
    if (res.data.code === 1) {
      //提交成功后，之间重置表格
      ElMessage({
        type: 'success',
        message: '更新成功'
      })
    } else {
      ElMessage.error('更新失败')
    }
  }
  getTypeList()
}
//重置表单
const resetForm = () => {
  typeForm.value = {
    id: 0,
    typeName: '',
    typeUrl: '',
    typeIntro: ''
  }
};
const handleSelectionChange = (row: any) => {
  selectedItems.value = JSON.parse(JSON.stringify(row))
}
//编辑
const editShowForm = (index: number, row: any) => {
  dialogVisible.value = true
  typeForm.value = row
  flag.value = 1
  // console.log(row)
}
//删除类别  请求体里只传id即可
const Delete_type = async (index: number) => {
  console.log(typeof index)
  const res = await myAxios.post('/category/delete', { id: index })
  console.log(res)
  if (res.data.code === 1) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
  }
  getTypeList()
}
//批量删除类别
const delBatch = async ()=>{
  console.log(typeList.value);
  const res = await myAxios.post('/goods/delBatch',{
    idList: typeList.value
  })
}
</script>

<style scoped></style>