
<script setup>
// 引入依赖
import api from '@/api/integral'
import custom from '@/utils/custom'
import {formatDate} from '@/utils/format'
import cityList from '@/utils/city.json'
import {ref,onMounted,provide } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
// store
import { useUserStore } from '@/pinia/modules/user'
const userStore = useUserStore()
// 变量
const path = ref(import.meta.env.VITE_BASE_API)
const queryParams = ref({
  page:1,
  pageSize:10,
  key:'',
  status:20,
  sort:'',
  current_page:1,
  loading_egg:''
})
// const subjectParams = ref({
//     pageIndex:1,
//     pageSize:100,
// })
const state_arr = ref([
    {
      name:'全部',
      value:20
    },
    {
      name:'已上架',
      value:1
    },
    {
      name:'未上架',
      value:0
    },
    {
      name:'已下架',
      value:2
    },
    {
      name:'已结束',
      value:3
    },
    {
      name:'未开始',
      value:4
    },
    {
      name:'报名中',
      value:5
    }
])
const tableData = ref([])
const deleteVisible = ref(false)
const total = ref(0)
const draw_ids = ref([])
// 生命周期
onMounted(() => {
  getDrawList()
})
// 方法
async function getDrawList() {
  const res = await api.getDrawList(queryParams.value)
  if(res.code === 0) {
    tableData.value = res.data.list
    total.value = res.data.total
  }
}
function onSubmit() {
  getDrawList()
}
const onReset = () => {
  queryParams.value = {
    page:1,
    pageSize:10,
    key:'',
    status:20,
    sort:'',
    current_page:1
  }
}
async function onDelete() {
  const ids = draw_ids.value
  const res = await api.delDrawData({ ids:draw_ids.value })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: res.msg
    })
    deleteVisible.value = false
    getDrawList()
  }
}
const handleSelectionChange = (val) => {
  draw_ids.value = val.map((item) => {
      return item.id
  })
}
function handleCurrentChange(val) {
  queryParams.value.current_page = val
  getDrawList()
}
function handleSizeChange(val) {
  queryParams.value.pageSize = val
  getDrawList()
}
// function viewTeacherFunc(row) { // 查看详情
//   router.push({name:'teacherDetail',params:{id:row.teacher_info_id}})
// }
function getStateName(row) {
  let name = ''
  switch(row.status) {
    case 1:
      // 检查是否过期
      if(row.end_time < (Date.parse(new Date()))) { // 已过期
        name = '已结束';
        row.status = 3
      }
      else if(row.begin_time < (Date.parse(new Date()))) { // 已开始
        name = '报名中';
      }
      else{
        name = '未开始';
      }
      break;
    case 2:
      name = '已下架';
      break;
    case 0:
      name = '未上架';
      break;
    case 3:
      name = '已结束';
      break;
  }
  return name
}

// 新增 & 编辑相关 ================
const popupVisible = ref(false)
const popupTitle = ref('')
const drawForm = ref({})
const drawFormRules = ref({
  product_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  market_value:[{ required: true, message: '请输入市场价格', trigger: 'blur'},
  { type: 'number', message: '请输入正确的格式',trigger: 'blur' }],
  in_point:[{ required: true, message: '请输入参与积分', trigger: 'blur'},
  { type: 'number', message: '请输入正确的格式' }],
  full_member:[{ required: true, message: '请输入满员人数', trigger: 'blur'},
  { type: 'number', message: '请输入正确的格式' }],
  end_time:[{ required: true, message: '请输入截止时间', trigger: 'blur' }],
  // delay_time:[{ required: true, message: '请输入砸蛋时间', trigger: 'blur' }],
  begin_time:[{ required: true, message: '请输入开始时间', trigger: 'blur' }],
  product_cover:[{ required: true, message: '请选择商品封面', trigger: 'blur' }],
  egg_quantity:[{ required: true, message: '请输入金蛋数量', trigger: 'blur'},
  { type: 'number', message: '请输入正确的格式' }],
  prize_number:[{ required: true, message: '请输入中奖号码', trigger: 'blur'},
  { type: 'number', message: '请输入正确的格式' }],
})
const drawFormRef = ref(null)
function openDialog() {
  drawForm.value = {}
  popupTitle.value = '新增竞拍'
  popupVisible.value = true
}
function editDrawFunc(row) {
  popupTitle.value = '编辑竞拍'
  popupVisible.value = true
  drawForm.value = row
}
function delFunc(row) {
  ElMessageBox.confirm('此操作将永久删除该数据, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  .then(async() => {
    console.log(1)
    const res = await api.delDrawData({
          ids:[row.id]
    })
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
      getDrawList()
    }
  },() => {
  })
}
function cancelClick() {
  popupVisible.value = false
}
async function confirmClick() { //提交竞拍
  submitForm(drawFormRef.value)
}
async function submitForm(formEl) {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) { // 验证通过
      // console.log('submit!')
      saveData()
    } else {
      // console.log('请填写完整信息!', fields)
    }
  })
}
async function saveData() {
  const params = {
    ...drawForm.value
  }
  let func = ''
  if(params.id) { // 编辑
    func = 'editDrawData'
  }
  else{ // 新增
    func = 'addDrawData'
  }
  // console.log(params);return
  const res = await api[func](params)
  if(res.code === 0) {
    ElMessage({
      type: 'success',
      message: res.msg
    })
    getDrawList()
    cancelClick()
  }
}
function handleAvatarSuccess(res) { // 图片上传回调
  console.log(res)
  drawForm.value[file_type.value[file_type_index]] = res.data.file.url

}
function beforeAvatarUpload(file) {
  const isLt05M = file.size / 1024 / 1024 < 20
  const isJPG = file.type.indexOf('image/') === -1
  if (isJPG) {
    ElMessage.error('文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件')
  }
  if (!isLt05M) {
    ElMessage.error('上传头像图片大小不能超过 2M!')
  }
  return !isJPG && isLt05M
}
const file_type = ref(['product_cover','product_introduce'])
let file_type_index = 0
function fileChange(index) {
  console.log(index)
  file_type_index = index
}
function loadingEggChange() {
  console.log(drawForm.value)
}
async function drawStateFunc(row,type) { //竞拍上架 下架
  let title = '确定要上架该抽奖吗？'
  if(type === 2) {
    title = '确定要下架该抽奖吗？'
  }
  ElMessageBox.alert(title, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    callback:async (action) => {
      console.log(action)
      if(action === 'confirm') {
        const res = await api.drawStateFunc({id:row.id,status:type})
        if(res.code === 0) {
            ElMessage({
              type: 'success',
              message: `修改成功`,
            })
            getDrawList()
        }
      }
    },
  })
}
// 查看明细相关
const viewParams = ref({
  id:0,
  type:1,
  current_page:1,
  page_size:10,
  sort:'desc'
})
const dialogViewVisible = ref(false)
const viewInfo = ref([])
const view_total = ref(0)
async function viewAuctionFunc(row) { // 竞拍明细
  viewParams.value.id = row.id
  dialogViewVisible.value = true
  const res = await api.viewAutionDetail(viewParams.value)
  if(res.code === 0) {
    view_total.value = res.data.total
    viewInfo.value = res.data.list
  }
}
function memberFunc() {
  drawForm.value.egg_quantity = drawForm.value.full_member
}
const egg_mask = ref(true)
function getRandomNumber() {
  if(!drawForm.value.full_member) {
    ElMessage({
      type: 'warning',
      message: `请先输入满员人数`,
    })
    drawForm.value.prize_number = ''
    return
  }
  if(!drawForm.value.end_time) {
    ElMessage({
      type: 'warning',
      message: `请先设置截止时间`,
    })
    drawForm.value.prize_number = ''
    return
  }
  let rand_num = Math.random()
  let rand_res = 1
  if(!rand_num){
    rand_num = 1
  }
  rand_res = Math.ceil(rand_num*drawForm.value.full_member)
  // console.log(rand_res)
  if(drawForm.value.end_time < (Date.parse(new Date()))) { // 已过期 可以显示
    egg_mask.value = false
  }
  else{ // 隐藏中奖号码
    egg_mask.value = true
  }
  drawForm.value.prize_number  = rand_res
}
</script>
<template>
  <div>
    <!--    搜索框-->
    <div class="gva-search-box">
      <el-form ref="searchForm" :inline="true" :model="queryParams">
        <el-form-item label="关键字">
          <el-input v-model="queryParams.key" placeholder="根据关键字进行查询" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" clearable placeholder="请选择">
            <el-option
              v-for="item in state_arr"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button size="small" icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--    表格数据-->
    <div class="gva-table-box">
      <!--      批量操作-->
      <div class="gva-btn-list">
        <el-button size="small" type="primary" icon="plus" @click="openDialog('add')">新增</el-button>
        <el-popover v-model="deleteVisible" placement="top" width="160">
          <p>确定要删除吗？</p>
          <div style="text-align: right; margin-top: 8px;">
            <el-button size="small" type="primary" link @click="deleteVisible = false">取消</el-button>
            <el-button size="small" type="primary" @click="onDelete">确定</el-button>
          </div>
          <template #reference>
            <el-button icon="delete" size="small" type="danger" :disabled="!draw_ids.length" style="margin-left: 10px;" @click="deleteVisible = true">删除</el-button>
          </template>
        </el-popover>
      </div>
      <!--      数据列表-->
      <el-table  :data="tableData" border @selection-change="handleSelectionChange">
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column align="center" label="ID"  prop="id" sortable="custom" />
        <el-table-column align="center" label="商品名称" min-width="150" prop="product_name" />
        <el-table-column align="center" label="商品图片" min-width="150">
          <template #default="scope">
            <img class="avatar-box" :src="scope.row.product_cover" alt="">
          </template>
        </el-table-column>
        <el-table-column align="center" label="市场价值（元）" min-width="150" prop="market_value" />
        <el-table-column align="center" label="参与积分" min-width="150" prop="in_point" />
        <el-table-column align="center" label="满员人数" min-width="150" prop="full_member" />
        <el-table-column align="center" label="发布日期" min-width="150" >
          <template #default="scope">
            {{custom.timestampToDate2(scope.row.begin_time)}}
          </template>
        </el-table-column>
        <el-table-column align="center" label="截止日期" min-width="150" >
          <template #default="scope">
            {{custom.timestampToDate2(scope.row.end_time)}}
          </template>
        </el-table-column>
<!--        <el-table-column align="center" label="砸蛋日期" min-width="150" >-->
<!--          <template #default="scope">-->
<!--            {{custom.timestampToDate2(scope.row.delay_time)}}-->
<!--          </template>-->
<!--        </el-table-column>-->

        <el-table-column align="center" label="已参与人数" min-width="150" prop="in_member" />
        <el-table-column align="center" label="金蛋数量" min-width="150" prop="egg_quantity" />
        <el-table-column align="center" label="中奖号" min-width="150" prop="prize_number" />
<!--        <el-table-column align="center" label="奖品装蛋" min-width="150" prop="loading_egg" >-->
<!--          <template #default="scope">-->
<!--            {{scope.row.loading_egg?'是':'否'}}-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column align="center" label="最高积分" prop="most_point" />-->
        <el-table-column align="center" label="状态">
          <template #default="scope">
            <div>{{getStateName(scope.row)}}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" fixed="right" label="操作" width="200">
          <template #default="scope">
            <el-button
              icon="view"
              size="small"
              type="primary"
              link
              @click="editDrawFunc(scope.row)"
            >编辑</el-button>
<!--            <el-button-->
<!--              icon="view"-->
<!--              size="small"-->
<!--              type="primary"-->
<!--              link-->
<!--              @click="viewAuctionFunc(scope.row)"-->
<!--            >明细</el-button>-->
            <el-button
              icon="delete"
              size="small"
              type="danger"
              link
              v-if="scope.row.status===2 || scope.row.status===0"
              @click="delFunc(scope.row)"
            >删除</el-button>
            <el-button
              icon="top"
              size="small"
              type="primary"
              link
              @click="drawStateFunc(scope.row,1)"
              v-if="scope.row.status===2 || scope.row.status===0"
            >上架</el-button>
            <el-button
              icon="bottom"
              size="small"
              type="danger"
              link
              @click="drawStateFunc(scope.row,2)"
              v-if="scope.row.status!==2 && scope.row.status!==0"
            >下架</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          :current-page="queryParams.current_page"
          :page-size="queryParams.pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <!-- 新增&编辑 窗口-->
    <el-drawer
      v-model="popupVisible"
      :title="popupTitle"
      direction="rtl"
      size="50%"
    >
      <el-form ref="drawFormRef" class="form-box" :model="drawForm" :rules="drawFormRules" label-width="80px">
        <el-form-item label="商品名称" prop="product_name">
          <el-input v-model="drawForm.product_name" placeholder="请输入商品名称" autocomplete="off" />
        </el-form-item>
        <el-form-item label="奖品封面" prop="product_cover">
          <el-upload
            class="avatar-uploader"
            :action="`${path}/fileUploadAndDownload/upload`"
            :headers="{ 'x-token': userStore.token }"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            @click="fileChange(0)"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="drawForm.product_cover" :src="drawForm.product_cover" class="img-container" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="市场价格"  prop="market_value">
          <el-input v-model.number="drawForm.market_value" placeholder="请输入市场价格" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="in_point" label="参与积分" >
          <el-input v-model.number="drawForm.in_point" placeholder="请输入参与积分" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="full_member" label="满员人数" >
          <el-input @change="memberFunc" v-model.number="drawForm.full_member" placeholder="请输入满员人数" autocomplete="off" />
        </el-form-item>
        <el-form-item label="开始日期" prop="begin_time" >
          <el-date-picker
            v-model="drawForm.begin_time"
            type="datetime"
            placeholder="开始日期"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="x"
          />
        </el-form-item>
        <el-form-item label="截止日期" prop="end_time" >
          <el-date-picker
            v-model="drawForm.end_time"
            type="datetime"
            placeholder="截止日期"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="x"
          />
        </el-form-item>
<!--        <el-form-item label="砸蛋日期" prop="delay_time" >-->
<!--          <el-date-picker-->
<!--            v-model="drawForm.delay_time"-->
<!--            type="datetime"-->
<!--            placeholder="砸蛋日期"-->
<!--            format="YYYY-MM-DD HH:mm:ss"-->
<!--            value-format="x"-->
<!--          />-->
<!--        </el-form-item>-->
        <el-form-item label="金蛋数量" prop="egg_quantity">
          <el-input v-model.number="drawForm.egg_quantity"  disabled="true"  placeholder="请输入金蛋数量" autocomplete="off" />
        </el-form-item>
        <el-form-item style="position:relative" label="中奖人数" prop="prize_number">
          <el-input v-model.number="drawForm.prize_number" placeholder="请设置中奖人数" autocomplete="off" />
          <!-- <el-input v-model.number="drawForm.prize_number" disabled placeholder="请设置中奖号码" autocomplete="off" />
          <div class="egg-mask" v-if="egg_mask && drawForm.prize_number">已生成中奖号码，活动结束后方可观看</div>
          <div class="egg-mask" v-else-if="egg_mask && !drawForm.prize_number">请点击下方生成中奖号码，活动结束后方可观看</div>
          <el-button size="small" type="plain" @click="getRandomNumber">随机生成</el-button> -->
        </el-form-item>
<!--        <el-form-item label="奖品装蛋" >-->
<!--          <el-switch @change="loadingEggChange" v-model="drawForm.loading_egg" active-text="是" inactive-text="否" :active-value="true" inactive-value="false"  />-->
<!--        </el-form-item>-->
        <el-form-item label="奖品详情" prop="product_introduce">
          <el-upload
            class="avatar-uploader"
            :action="`${path}/fileUploadAndDownload/upload`"
            :headers="{ 'x-token': userStore.token }"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            @click="fileChange(1)"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="drawForm.product_introduce" :src="drawForm.product_introduce" class="img-container" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
<!--        <el-form-item label="启用状态" prop="status">-->
<!--          <el-switch v-model="drawForm.status" :active-value="1" :inactive-value="2" active-text="启用" inactive-text="禁用" />-->
<!--        </el-form-item>-->

      </el-form>
       <template #footer>
          <div style="flex: auto">
            <el-button @click="cancelClick">取消</el-button>
            <el-button type="primary" @click="confirmClick">确定</el-button>
          </div>
       </template>
    </el-drawer>
    <!-- 查看明细窗口-->
    <el-dialog v-model="dialogViewVisible" :before-close="closeViewDialog" title="竞拍明细">
      <el-table :data="viewInfo" border >
        <el-table-column align="center" label="ID"  prop="id"  />
        <el-table-column align="center" label="用户名称"  prop="name"  />
<!--        <el-table-column align="center" label="抽奖积分"  prop="point"  />-->
        <el-table-column align="center" label="是否中奖"  prop="status"  />
        <el-table-column align="center" label="参与时间"  prop="CreatedAt"  />
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          :current-page="viewParams.current_page"
          :page-size="viewParams.pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="view_total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="closeViewDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped lang="scss">
  .egg-mask{
    position: absolute;
    left: 0px;
    background: #e7e7e7;
    width: 100%;
    height: 50%;
    top: 0px;
    color: #999999;
    padding: 0 10px;
  }
  .form-box{
    padding: 10px;
  }
  .img-container{
    width: 200px;
    height: 150px;
  }
  .avatar-box{
    width: 50px;
    height: 50px;
    border-radius: 50%;
    border: 1px solid #dbdbdb;
  }
  .e-img{
    width: 150px;
    height: 100px;
  }
  .option-item{
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }
  .button-box {
    padding: 10px 20px;
    .el-button {
      float: right;
    }
  }
  .warning {
    color: #dc143c;
  }
</style>
