<template>
  <div class="table_page">
    <div>
      <el-input style="width: 200px; height: 30px; margin-right: 10px;" suffix-icon="Search" placeholder="请输入优惠券名称"
                v-model="name"></el-input>
      <el-button class="ml-5" type="primary" @click="load(name)" size="default">搜索</el-button>
      <el-button type="warning" @click="reset" size="default">重置</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="name" label="优惠券名称"></el-table-column>
      <el-table-column prop="standardAmount" label="满减价格"></el-table-column>
      <el-table-column prop="conditionAmount" label="优惠价格"></el-table-column>
      <el-table-column prop="requirePoints" label="兑换积分"></el-table-column>
      <el-table-column prop="endTime" label="截止时间"></el-table-column>
      <el-table-column label="上架状态">
        <template #default="scope">
          <span style="margin-left: 10px" v-if="scope.row.isShelves == 1">上架</span>
          <span style="margin-left: 10px" v-if="scope.row.isShelves == 0">下架</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态"></el-table-column>
      <el-table-column label="操作" width="200px" >
        <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-button size="small" @click="handleOffCoupon(scope.row.id)">
            <div v-if="scope.row.isShelves == 1">下架</div>
            <div v-if="scope.row.isShelves == 0">上架</div>
          </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>
  </div>
  <!--  详情，编辑-->
  <el-dialog v-model="DialogVisible" :title="title">
    <el-form label-width="100px" :disabled="disabled" size="large">
      <el-form-item label="优惠券名称" style="width: 400px">
        <el-input v-model="editForm.name"></el-input>
      </el-form-item>
      <el-form-item label="满减价格">
        <el-input-number v-model="editForm.standardAmount" min="0.01" :precision="2" :step="1" />
        <el-text class="mx-1" size="large">元</el-text>
      </el-form-item>

      <el-form-item label="优惠价格">
        <el-input-number v-model="editForm.conditionAmount" min="0.01" :precision="2" :step="1" />
        <el-text class="mx-1" size="large">元</el-text>
      </el-form-item>

      <el-form-item label="兑换积分">
        <el-input-number v-model="editForm.requirePoints" min="0" :step="1" />
        <el-text class="mx-1" size="large">积分</el-text>
      </el-form-item>


      <el-form-item label="截至日期">
        <el-date-picker
            v-model="editForm.endTime"
            type="datetime"
            placeholder="Pick a Date"
            format="YYYY-MM-DD hh:mm:ss"
            value-format="YYYY-MM-DD hh:mm:ss"
        />
      </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 {inject, onMounted, ref} from "vue";
import myAxios from "@/api/myAxios";
import {ElMessage} from "element-plus";
import {SuccessInfo, WarnInfo} from "@/utils/messageInfo";

onMounted(() => {
  getCouponsList()
})
const name=ref('')
const DialogVisible = ref(false)
const idList = ref([])
const total = ref(0)
const tableData : any= ref([])
const title = ref('')
const editForm : any = ref({})
const disabled = ref(true)
const searchParams: any = ref({ //分页
  current: 1,
  pageSize: 5,
  sortField: "id",  //根据ID分类
  sortOrder: "descend" //降序
})

//处理行数大小变化
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 reload : any = inject("reload")
const reset = ()=>{
  reload()
}
//搜索
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 = JSON.parse(JSON.stringify(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 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: '删除成功',
    })
    await getCouponsList()
  }
}

const handleOffCoupon = async ( id:any )=> {
  const res = await myAxios.post('/coupon/shelves',{ id: id })
  if(res.data.code === 1) {
    SuccessInfo('更新成功')
    await getCouponsList()
  } else {
    WarnInfo('服务错误')
  }
}

</script>

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