<template>
  <div class="table_page">
  <div style="display: flex; align-items: center">
    <el-input style="width: 200px; height: 30px; margin-right: 10px;" suffix-icon="Search" placeholder="请输入课程名称" size="large"
      v-model="productName"></el-input>
    <div>
      <el-form-item label="" style="width: 200px; margin: 3px 10px 0 0;display: inline-block;">
        <el-select size="default" v-model="state" placeholder="商品状态" @change="(event: any) => searchByState(event)">
          <el-option label="已上架" value="1" />
          <el-option label="已下架" value="0" />
        </el-select>
      </el-form-item>
    </div>
    <el-button class="ml-5" type="primary" @click="onSearch(productName)" style="height: 30px;">搜索</el-button>
    <el-button type="warning" @click="reset" style="height:30px">重置</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" @select="selectChange"
    :header-cell-style="{ 'text-align': 'center' }" default-expand-all>
    <el-table-column type="selection" width="55"></el-table-column>
    <el-table-column prop="id" label="课程编号" width="80">
      <template #default="{ $index }">
        {{ $index + 1 }}
      </template>
    </el-table-column>
    <el-table-column prop="goodImg" label="课程图片">
      <template #default="scope">
        <div>
          <img :src="downloadUrl + scope.row.goodImg" alt="" style="height: 50px;">
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="name" label="课程名称"></el-table-column>
    <el-table-column prop="price" label="单次价格" width="100"></el-table-column>
    <el-table-column label="展开时间段" type="expand" width="80">
      <template #default="{ $index }">
        <!-- 放后端传来的预约时间 -->
        <el-table :data="appointmentDateArr[$index]" :header-cell-style="{ 'text-align': 'center' }"
          :cell-style="{ 'text-align': 'center' }">
          <el-table-column label="是否可预约" prop="isAvailable">
            <template #default="{ row  }">
              {{ row.isAvailable == 1 ? "是" : "否" }}
            </template>
          </el-table-column>
          <el-table-column label="日期" prop="specificDate" />
          <el-table-column label="操作">
            <template v-slot="scope">
            <el-button size="small" @click="updateDay(scope.row)">
              <div v-if="scope.row.isAvailable == 1">取消预约</div>
              <div v-if="scope.row.isAvailable == 0">启用预约</div>
            </el-button>
            <el-button size="small" type="primary" @click="addDate(scope.row)">
              添加日期
            </el-button>
            <el-button size="small" @click="openDrawer($index,scope.row)">
              编辑
            </el-button>
            <el-popconfirm class="ml-5" confirm-button-text='确定' cancel-button-text='取消' icon="InfoFilled" icon-color="red"
                           title="是否确认删除" @confirm="deleteDate(scope.row.id)" width=180>
              <template #reference>
                <el-button class="ml-5" type="danger" v-if="tableData[$index].appointmentDateVOList.length>1">删除</el-button>
              </template>
            </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-table-column>
    <el-table-column label="商品状态" width="80">
      <template #default="scope">
        <div>
          <span style="margin-left: 10px" v-if="scope.row.isShelves == 1">上架</span>
          <span style="margin-left: 10px" v-if="scope.row.isShelves == 0">下架</span>
        </div>
      </template>
    </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-button size="small" @click="handleOff(scope.row)">
          <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="deleteProduct(scope.row.id)" width=180>
          <template #reference>
            <el-button class="ml-5" type="danger">删除</el-button>
          </template>
        </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-drawer
    v-model="drawer"
    :title="'当前日期：'+drawerDate.specificDate + '&emsp;课程名称：' + className"
    direction="ltr"
    @closed="closedDrawer">
  <div style="margin-bottom: 20px">选择当天时间段和人数</div>
    <div v-for="(item,index) in drawerDate.timePeriodVOList" style="margin-bottom: 40px">
        <div style="margin-bottom: 15px"><span>时间段</span></div>
        <el-time-picker
            v-model="timePickArr[index]"
            format='HH:mm'
            is-range="true"
            range-separator="到"
            start-placeholder="开始"
            end-placeholder="结束"
            value-format="HH:mm"
            :style="{ width: '236px', marginBottom: '15px' }"
            @change="saveTime(index)"
            :disabled="timeAbleArr[index]"
        />

      <div style="margin-bottom:15px">
        <div style="display: flex; align-items: center; margin-bottom: 15px">
          <div style="margin-right: 15px"><span>最小人数:</span></div>
          <el-select v-model="InfoArr[index].minNumber" style="width: 50px" @change="minNum(index)" :disabled="numAbleArr[index]">
            <el-option v-for="item in minArr" :label="item" :value="item" />
          </el-select>
        </div>

        <div style="display: flex; align-items: center; margin-bottom: 15px">
          <div style="margin-right: 15px"><span>最大人数:</span></div>
          <el-select v-model="InfoArr[index].maxNumber" style="width: 50px" @change="maxNum(index)" :disabled="numAbleArr[index]">
            <el-option v-for="item in maxArr" :label="item" :value="item" />
          </el-select>
        </div>

        <el-button type="primary" @click="UpdateNum(item,index)" v-if="timeAbleArr[index]">{{ btnText[index] }}</el-button>
        <el-button type="danger" @click="subList(item, index)" v-if="index > 0">删除</el-button>
      </div>
    </div>
    <el-button type="success" @click="addList">{{ addbtnText }}</el-button>
  </el-drawer>
  <!-- 添加日期弹窗 -->
  <el-dialog
    v-model="addDateVisible"
    title="添加日期"
    width="500"
    >
    <calendarUtil @calendar-info="handleCalendarInfo"></calendarUtil>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addDateVisible = false">取消</el-button>
        <el-button type="primary" @click="submitDate()">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus';
import {ref, onMounted, inject} from 'vue';
import myAxios from "@/api/myAxios";
import calendarUtil from '@/layout/components/calendarUtil.vue';
import emitter from "@/utils/emitter";
import { useRouter } from "vue-router";
import { downloadUrl } from '@/utils/formatImgUpload'

const router = useRouter();  //路由
const total = ref(0); //总页数
const idList = ref<Number[]>([]);  //用于批量删除
const searchParams: any = ref({ //封装分页
  current: 1, //当前页码
  pageSize: 5, //每页显示条数
  sortField: "id",  //根据ID分类
  sortOrder: "descend" //降序
})
const tableData : any= ref([]);
const appointmentDateArr : any = ref([])
const productName = ref('');
const state = ref('');  //根据商品上架状态select栏
const reload : any = inject("reload")  //页面重新刷新
//抽屉变量
const drawer = ref(false)  //抽屉打开
const drawerDate : any = ref({})  //当前日期、时间段人数信息
const timePickArr : any = ref([])  //时间段选择器
const minArr : any = ref([])  //最小人数数组
const maxArr : any = ref([])  //最大人数数组
const InfoArr : any = ref([]) //时间段人数信息数组
const btnText = ref(Array.from({length:15},()=>('修改')))
const addbtnText = ref('添加时间段')
const timeAbleArr = ref( //禁用时间段组件
  Array.from({ length: 15 },()=>(false))
)
const numAbleArr = ref(  //禁用人数组件
  Array.from({ length: 15 },()=>(true))
)
const className = ref('') //课程名称
const nowBookPeo = ref(0) //当前预约人数
const addDateVisible = ref(false)  //添加日期弹窗
onMounted(() => { //页面加载时获取商品列表和分类页表
  getProductList()
  for(let i = 0;i <=50 ; i++) {  //初始化人数选择的数组
    minArr.value[i] = 5+i
    maxArr.value[i] = 6+i
  }
})

const appointmentDateAddRequestList : any = ref([])

const handleCalendarInfo = (data:any) => {
  appointmentDateAddRequestList.value = data
  console.log(data)
}

const getProductList = async () => {
  try {
    const res = await myAxios.post('/goods/service/list/page', { ...searchParams.value });
    // console.log('res--->',res.data)
    if (res.data.code === 1) {
      tableData.value = res.data.data.records;
      total.value = parseInt(res.data.data.total)  //总数据量，用于分页
      appointmentDateArr.value.splice(0,total.value)
      console.log('tableData--->',tableData.value);
      tableData.value.forEach((val : any) => {
        appointmentDateArr.value.push(val.appointmentDateVOList)  
      })
      console.log('时间--->',appointmentDateArr.value);
    } else {
      ElMessage({
        message: '获取数据失败',
      });
      return;
    }
  } catch (error) {
    ElMessage({
      message: '发生错误',
    });
  }
}

const searchByState = (event : any) => {  //通过商品是否上架/下架搜索
  searchParams.value.isShelves = event
  searchParams.value.current = 1
  getProductList()
}
//删除商品
const deleteProduct = async (index: number) => {
  console.log(typeof index)
  const res = await myAxios.post('/goods/delete/service', { id: index })
  console.log(res)
  if (res.data.code === 1) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getProductList()
  }
}
//详情或编辑 
const ReviseOrView = (index: number, row: any , flag : number) => {
  router.push({
    name: '课程详情',
    params: {
      id: row.id,
      flag: flag
    }
  })
};

//下架商品
const handleOff = async (row: any) => { 
  console.log(row.isShelves);
  const res = await myAxios.post('/goods/service/shelves',{id: row.id}) 
  if(res.data.code === 1) {
    ElMessage({
      type:'success',
      message:'更新成功'
    })
  }
  getProductList()
}
//处理行数大小变化
const handleSizeChange = (newSize: any) => {
  searchParams.value.pageSize = newSize //新的页面数
  getProductList()
}
//处理当前表格变化
const handleCurrentChange = (Current: any) => {
  searchParams.value.current = Current
  getProductList()
}
//重置按钮
const reset = () => {
  reload()
}

const onSearch = (data : String)=>{ //搜索按钮方法
  searchParams.value.name = data
  searchParams.value.current = 1
  getProductList()
}
 //批量删除
const delBatch = async ()=>{
  console.log(idList.value);
  const res = await myAxios.post('/goods/delBatch/service',{
    idList: idList.value
  })
  console.log(res.data);
  if(res.data.code === 1) {
    ElMessage({
      type: 'success',
      message: '批量删除成功'
    })
    await getProductList()
  } else {
    ElMessage.error('删除失败')
  }
}
const handleSelectionChange =()=>{}
const selectChange =(selection: any, row : any)=> {   //selction是对象数组，row是当前行对象
  idList.value.splice(0,idList.value.length)   //删掉
  selection.forEach((item: any)=> {
    idList.value.push(item.id)
  })
  // console.log('idList--->',idList.value);
}
const openDrawer =(index : number,dateInfo : any)=>{  //抽屉打开方法
  // console.log('row-->',dateInfo);
  className.value = tableData.value[index].name
  timePickArr.value.splice(0,timePickArr.value.length) //删除之前的时间段
  drawerDate.value = dateInfo
  InfoArr.value = dateInfo.timePeriodVOList
  console.log(drawerDate.value);
  dateInfo.timePeriodVOList.forEach((item:any,index:number)=>{  //格式化时间段框，然后将时间段数组禁用，只修改人数
    let arr = item.timeSlot.split("-")
    timeAbleArr.value[index] = true
    timePickArr.value.push(arr)
  })
  drawer.value = true
}
const saveTime =(index: number)=>{  //格式化日期
  try{
    drawerDate.value.timePeriodVOList[index].timeSlot = timePickArr.value[index][0]+'-'+timePickArr.value[index][1]
  } catch {
    drawerDate.value.timePeriodVOList[index].timeSlot = ''
  }
}
const minNum =(index: number)=>{}
const maxNum =(index: number)=>{}
const addList = async ()=>{
  let newIndex = drawerDate.value.timePeriodVOList.length
  numAbleArr.value[newIndex] = false  //启用组件
  console.log('drawerDate--->',drawerDate.value);
  if(addbtnText.value === '添加时间段') {
    drawerDate.value.timePeriodVOList.push({   //增加当前日期时间段
      id: 0,
      timeSlot: '',
      maxNumber: 0,
      minNumber: 0
    })
    timePickArr.value.push([])
    addbtnText.value = '保存时间段'
  }
  // console.log('timeSlot-->',drawerDate.value.timePeriodVOList[newIndex].timeSlot);
  if(!judgeNull(drawerDate.value.timePeriodVOList)) {
    ElMessage({
      type: 'warning',
      message: '填写时间段和人数'
    })
    return;
  }
  const res = await myAxios.post('/appointmentDate/add/time',{
    timeSlot: drawerDate.value.timePeriodVOList[newIndex-1].timeSlot,
    minNumber: drawerDate.value.timePeriodVOList[newIndex-1].minNumber,
    maxNumber: drawerDate.value.timePeriodVOList[newIndex-1].maxNumber,
    appointmentDateId: drawerDate.value.id,
  })
  console.log(res.data.data);
  if(res.data.code === 1) {
    drawerDate.value.timePeriodVOList[newIndex-1].id = res.data.data
    drawerDate.value.timePeriodVOList.forEach((item: any,index: number)=>{
      timeAbleArr.value[index] = true
      numAbleArr.value[index] = true
    })
    ElMessage({
      type: 'success',
      message: '添加时间段成功'
    })
  } else {
    ElMessage({
      type: 'error',
      message: '添加失败'
    })
  }
  console.log(res.data);
  addbtnText.value = '添加时间段'
}
const subList = async (item:any, index: number)=> {
  console.log(index, '->', item)
  if (item.id !== 0) {
    const res = await myAxios.post('/appointmentDate/del/time/id', {
      id: item.id,
    })
    if (res.data.code === 1) {
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
    } else {
      ElMessage({
        type: 'error',
        message: '删除失败'
      })
    }
  }
  drawerDate.value.timePeriodVOList.pop()
  addbtnText.value = '添加时间段'
}
const UpdateNum = async (item: any,index:number)=>{  //修改具体日期某时间段的人数
  btnText.value[index] === '修改' ? btnText.value[index] = '保存' : btnText.value[index] = '修改'
  btnText.value[index] === '保存' ? numAbleArr.value[index] = false : numAbleArr.value[index] = true
  if(btnText.value[index] === '修改') {
    const res = await myAxios.post('/appointmentDate/update/time',{
      id: item.id,
      minNumber: item.minNumber,
      maxNumber: item.maxNumber
    })
    if(res.data.code === 1) {
      ElMessage({
        type: 'success',
        message: '更新成功'
      })
    } else {
      ElMessage({
        type: 'error',
        message: '更新失败'
      })
    }
  }
}
const updateDay = async (row:any)=>{  //修改今天是否可以预约
  const res = await myAxios.post('/appointmentDate/update/status',{id: row.id})
  if(res.data.code === 1) {
    ElMessage({
      type:'success',
      message: '修改成功'
    });
  }
  await getProductList()
}
const judgeNull =(List : any)=>{  //时间段和人数统一判空方法
  console.log('List--->',List);
  if (List.some((item:any) => item.timeSlot=== '' || item.minNumber === 0 || item.maxNumber === 0)) {
    return false;
  }
  return true;
}
const closedDrawer =()=>{  //完全关闭抽屉触发
  let newIndex = drawerDate.value.timePeriodVOList.length
  timeAbleArr.value.forEach((item: any ,index: number)=>{
    timeAbleArr.value[index] = false
    numAbleArr.value[index] = true
    btnText.value[index] = '修改'
  })
  if(!judgeNull(drawerDate.value.timePeriodVOList)) {
    console.log('关闭抽屉的删除数组被激活');
    drawerDate.value.timePeriodVOList.splice(newIndex-1,1)
  }
  addbtnText.value = '添加时间段'
}
const deleteDate = async (id: number)=>{  //删除当前日期方法
  console.log(id)
  const res = await myAxios.post('/appointmentDate/del/id',{id:id})
  // console.log('res--->',res);
  if(res.data.code === 1) {
    getProductList()
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
  } else {
    ElMessage({
      type: 'info',
      message: '请求失败'
    })
  }
}
let goodId = 0
const addDate = ( obj : any ) => { //添加日期方法
  console.log('obj--->',obj);
  addDateVisible.value = true
  goodId = obj.goodId
}
const submitDate = async ()=> {  //提交日期方法
  appointmentDateAddRequestList.value.forEach((item:any,index:number)=>{
    Object.assign(item, {goodId:goodId})
  })
  const res = await myAxios.post("/appointmentDate/addBatch", appointmentDateAddRequestList.value)
  console.log(res)
  await getProductList();
  addDateVisible.value = false
  appointmentDateAddRequestList.value = []
  emitter.emit('clear')
}
</script>

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