<template>
  <!--  搜索-->
  <div>
    <el-input style="width: 200px; height: 30px; margin-right: 10px;" suffix-icon="Search" placeholder="请输入优惠券名称"
              v-model="Couponsname"></el-input>
    <el-button class="ml-5" type="primary" @click="load" style="height: 25px;">搜索</el-button>
    <el-button type="warning" @click="reset" style="height:25px">重置</el-button>
  </div>
  <!--  批量删除-->
  <div style="margin: 15px 0">
    <el-popconfirm class="ml-5" confirm-button-text='确定' cancel-button-text='取消' icon="InfoFilled" icon-color="red"
                   title="您确定批量删除这些数据吗？" @confirm="delBatch" width=180>
      <template #reference>
        <el-button style="height: 25px" class="ml-5" type="danger">批量删除 <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="{ 'text-align': 'center', 'font-size': '16px' }" @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="80"></el-table-column>
    <el-table-column prop="goodImg" label="优惠券图片">
      <template #default="scope">
        <div>
          <img :src="scope.row.image" alt="" style="height: 50px;">
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="name" label="优惠券名称"></el-table-column>
    <el-table-column prop="conditionAmount" label="满减金额" width="180"></el-table-column>
    <el-table-column prop="totalNum" label="发放数量"></el-table-column>
    <el-table-column prop="requirePoints" label="兑换积分"></el-table-column>
    <el-table-column prop="residueNum" label="剩余数量"></el-table-column>
    <el-table-column prop="limitNum" label="限量领取"></el-table-column>
    <el-table-column prop="useScope" label="使用范围"></el-table-column>
    <el-table-column prop="startTime" label="生效时间"></el-table-column>
    <el-table-column prop="endTime" label="截止时间"></el-table-column>
    <el-table-column label="操作" width="250px">
      <template #default="scope">
        <el-button size="small" @click="ReviseOrView(scope.$index, scope.row , 0)">
          详情
        </el-button>
        <el-button size="small" @click="ReviseOrView(scope.$index, scope.row, 1)">
          编辑
        </el-button>
        <el-popconfirm class="ml-5" confirm-button-text='确定' cancel-button-text='取消' icon="InfoFilled" icon-color="red"
                       title="是否确认删除" @confirm="deleteCoupons(scope.row.id)" width=180>
          <template #reference>
            <el-button  class="ml-5" type="danger">删除</el-button>
          </template>
        </el-popconfirm>
        <el-popconfirm confirm-button-text='确定' cancel-button-text='取消' icon="el-icon-info" icon-color="red"
                       title="您确定删除吗？">
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
  <!--  分页-->
  <div style="padding: 10px 0">
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                   :current-page="searchParams.current" :page-size="searchParams.pageSize" :page-sizes="[5, 10, 15, 20]"
                   :small="null" :disabled="null" :background="null" layout="total, sizes, prev, pager, next, jumper"
                   :total="total" />
  </div>
  <!--  详情，编辑-->
  <el-dialog v-model="DialogVisible" :title="title">
    <el-form label-width="100px" :disabled="disabled">
      <el-form-item label="优惠券编号">
        <el-input v-model="editForm.id" disabled></el-input>
      </el-form-item>
      <el-form-item label="优惠券图片">
        <div v-if="editForm.image">
          <img :src="editForm.image" alt="优惠券图片" class="thumbnail" style="width: 100px; height: 100px;" />
        </div>
        <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            multiple="true"
            :on-remove=" handleRemove"
            @change="(event: any) => handleChange(event, 0)"
            limit="1" >
          <el-icon>
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="优惠券名称">
        <el-input v-model="editForm.name"></el-input>
      </el-form-item>
      <el-form-item label="满减金额">
        <el-input v-model="editForm.conditionAmount"></el-input>
      </el-form-item>
      <el-form-item label="兑换积分">
        <el-input v-model="editForm.requirePoints"></el-input>
      </el-form-item>
      <el-form-item label="发放数量">
        <el-input v-model="editForm.totalNum"></el-input>
      </el-form-item>
      <el-form-item label="限量领取">
        <el-input v-model="editForm.limitNum"></el-input>
      </el-form-item>
      <el-form-item label="使用范围">
        <el-input type="textarea" v-model="editForm.useScope"></el-input>
      </el-form-item>
      <el-form-item label="发放时间">
        <el-input type="textarea" v-model="editForm.startTime"></el-input>
      </el-form-item>
      <el-form-item label="截止时间">
        <el-input type="textarea" v-model="editForm.endTime"></el-input>
      </el-form-item>
      <el-form-item label="使用说明">
        <el-input type="textarea" v-model="editForm.description"></el-input>
      </el-form-item>
    </el-form>
    <template #footer >
      <span class="dialog-footer">
        <el-button @click="DialogVisible = false" :disabled="disabled">取消</el-button>
        <el-button type="primary" @click="saveEdit" :disabled="disabled">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {onMounted, ref} from "vue";
import myAxios from "@/api/myAxios";
import {ElMessage, type UploadProps} from "element-plus";

onMounted(() => {
  getCouponsList()
})

const DialogVisible = ref(false)
const idList = ref([])
const total = ref(0)
const tableData : any= ref([])
const Couponsname = ref('')
const title = ref('')
const editForm : any = ref({})
const fileSimple = ref()
const disabled = ref(true)
const searchParams: any = ref({ //分页
  current: 1,
  pageSize: 5,
  sortField: "id",  //根据ID分类
  sortOrder: "descend" //降序
})
//删除图片
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}
//处理行数大小变化
const handleSizeChange = (newSize: any) => {
  searchParams.value.pageSize = newSize //新的页面数
  getCouponsList()
}
//处理当前表格变化
const handleCurrentChange = (Current: any) => {
  searchParams.value.current = Current
  getCouponsList()
}
const handleSelectionChange = (row: any) => {
  idList.value = row.map((item : any)=>item.id)
}
//批量删除
const delBatch = async ()=>{
  const res = await myAxios.post('/coupon/delete', {
    id:idList.value
  })
  if (res.data.code === 1) {
    ElMessage({
      type:'success',
      message:"批量删除成功"
    })
    getCouponsList()
  }else {
    ElMessage.error('删除失败')
  }
}
//重置搜索
const reset = () => {
  Couponsname.value = '';
}
//搜索
const load =(data:String)=>{
  searchParams.value.name = data
  searchParams.value.content = 1
  getCouponsList()
}
const saveEdit = async () => { //编辑商品
  const res = await myAxios.post('/coupon/update',{...editForm.value})
  if( res.data.code === 1 ) {
    ElMessage({
      type: 'success',
      message: '更新成功'
    })
    DialogVisible.value = false
  } else {
    ElMessage.error('更新失败，请检查字段')
  }
}
const ReviseOrView = (index: number, row: any , flag : number) => {
  flag ?  (title.value = "编辑商品" , disabled.value = false) : (title.value = "商品详情" , disabled.value = true)
  DialogVisible.value = true;
  editForm.value = row;
};
const getCouponsList = async ()=> {
  try {
    const res = await myAxios.post('/coupon/list/page', {...searchParams.value})
    console.log(res)
    if (res.data.code === 1) {
      tableData.value = res.data.data.records;
      total.value = parseInt(res.data.data.total)
    }else {
      ElMessage({
        type: 'error',
        message: '获取数据失败'
      })
    }
  }catch (error){
    ElMessage({
      type: 'error',
      message: '发生错误'
    })
  }
}
const handleChange = async (file: any, flag: number) => {
  fileSimple.value = filen
  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) {
    editForm.value.image = res.data.data
  }
}
const deleteCoupons = async (index: number) => {
  console.log(typeof index)
  const res = await myAxios.post('/coupon/delete', { id: index })
  console.log(res)
  if (res.data.code === 1) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getCouponsList()
  }
}

</script>

<style>

</style>