<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="请输入服装名称"
              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 confirm-button-text='确定' cancel-button-text='取消' icon="InfoFilled" icon-color="red"
                   title="您确定批量删除这些数据吗？" @confirm="delBatch" width=180>
      <template #reference>
        <el-button style="height: 25px" 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.introImg" 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 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].bookingDateVOList.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.row , 0)">
          详情
        </el-button>
        <el-button size="small" @click="ReviseOrView(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;服装名称：' + outfitName" direction="ltr"
             @closed="closedDrawer">
    <div style="margin-bottom: 20px">选择当天时间</div>
    <div v-for="(item,index) in drawerDate.bookingTimeVOList" style="margin-bottom: 40px">
      <div style="margin-bottom: 15px"><span>时间点</span></div>
      <div style="display: flex;">
        <el-time-select v-model="timePickArr[index]"
                        format='HH:mm'
                        style="width: 240px"
                        start="07:00" step="00:05"
                        end="20:00" placeholder="选择时间点" value-format="HH:mm" :style="{ width: '200px' }"
                        @change="saveTime(index)"
                        :disabled="timeAbleArr[index]" />
        <div style="margin-left:15px">
          <el-popconfirm confirm-button-text='确定' cancel-button-text='取消' icon="InfoFilled" icon-color="red"
                         title="是否确认删除" @confirm="subList(item, index)" width=180>
            <template #reference>
              <el-button type="danger" v-if="index > 0">删除</el-button>
            </template>
          </el-popconfirm>
        </div>
      </div>
    </div>
    <el-button type="success" @click="addList">{{ addbtnText }}</el-button>
  </el-drawer>
  <!-- 添加日期弹窗 -->
  <el-dialog v-model="addDateVisible" title="添加日期" width="500">
    <outfitCalendarUtil @calendar-info="handleCalendarInfo"></outfitCalendarUtil>
    <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 outfitCalendarUtil from '@/layout/components/outfitCalendarUtil.vue';
import emitter from "@/utils/emitter";
import { useRouter } from "vue-router";
import {WarnInfo} from "@/utils/messageInfo";
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 addbtnText = ref('添加时间')
const timeAbleArr = ref( //禁用时间段组件
    Array.from({ length: 15 },()=>(false))
)
const outfitName = ref('') //服装名称
const addDateVisible = ref(false)  //添加日期弹窗
const typeList = ref<String[]>([]) //服装类别数组

onMounted(async () => { //页面加载时获取商品列表和分类页表
  getOutfitList()
  getOutfitKind() //获取服装类别
  await getAllPhotoProducts()
  await getSpecialProducts()
  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('handleCalendarInfo',data)
}

const getOutfitList = async () => {
  try {
    const res = await myAxios.post('/photoProducts/list/page', { ...searchParams.value });
    console.log('服装列表--->',res.data);
    // 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.bookingDateVOList)
      })
      console.log('时间--->',appointmentDateArr.value);
    } else {
      ElMessage({
        message: '获取数据失败',
      });
      return;
    }
  } catch (error) {
    ElMessage({
      message: '发生错误',
    });
  }
}

const searchByState = (event : any) => {  //通过商品是否上架/下架搜索
  searchParams.value.isShelves = event
  searchParams.value.current = 1
  getOutfitList()
}
//删除商品
const deleteProduct = async (index: number) => {
  console.log(typeof index)
  const res = await myAxios.post('/photoProducts/delete', { id: index })
  console.log(res)
  if (res.data.code === 1) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    await getOutfitList()
    await getAllPhotoProducts()
    await getSpecialProducts()
  }
}
//详情或编辑 
const ReviseOrView = (row: any , flag : number) => {
  router.push({
    name: '服装详情',
    params: {
      id: row.id,
      flag: flag
    }
  })
};
const getOutfitKind = async ()=> {   //获取服装类别
  const res = await myAxios.post('/photoCategory/list',{})
  for(let key in res.data.data) {
    typeList.value.push(res.data.data[key].name)
  }
}

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

const onSearch = (data : String)=>{ //搜索按钮方法
  searchParams.value.name = data
  searchParams.value.current = 1
  getOutfitList()
}
//批量删除服装信息
const delBatch = async ()=>{
  console.log(idList.value);
  const res = await myAxios.post('/photoProducts/delBatch',{
    idList: idList.value
  })
  console.log(res.data);
  if(res.data.code === 1) {
    ElMessage({
      type: 'success',
      message: '批量删除成功'
    })
    getOutfitList()
    await getAllPhotoProducts()
    await getSpecialProducts()
  } 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);
  outfitName.value = tableData.value[index].name
  timePickArr.value.splice(0,timePickArr.value.length) //删除之前的时间段
  drawerDate.value = dateInfo
  InfoArr.value = dateInfo.bookingTimeVOList
  // console.log('抽屉中的时间信息---->',drawerDate.value);
  dateInfo.bookingTimeVOList.forEach((item:any,index:number)=>{  //格式化时间段框
    timeAbleArr.value[index] = true
    timePickArr.value.push(item.timePoint)
  })
  drawer.value = true
}
const saveTime = (index: number) => {  //将时间点存入抽屉中
  console.log('时间点数组--->',timePickArr.value);
  try {
    drawerDate.value.bookingTimeVOList[index].timePoint = timePickArr.value[index]
  } catch {
    drawerDate.value.bookingTimeVOList[index].timePoint = ''
  }
}
const addList = async ()=>{
  let newIndex = drawerDate.value.bookingTimeVOList.length
  console.log('drawerDate--->',drawerDate.value);
  if(addbtnText.value === '添加时间') {
    drawerDate.value.bookingTimeVOList.push({   //增加当前日期时间
      timePoint: ''
    })
    timePickArr.value.push([])
    addbtnText.value = '保存时间'
  } else {  //当按钮文本为'保存时间'
    if(!judgeNull(drawerDate.value.bookingTimeVOList)) {
      WarnInfo('填写时间')
      return;
    } else {
      addTimePoint(newIndex)  //增加时间
      addbtnText.value = '添加时间'
    }
  }
}
const addTimePoint = async (newIndex: number) => {   //添加时间段方法
  const res = await myAxios.post('/book/add/time',{
    timePoint: drawerDate.value.bookingTimeVOList[newIndex-1].timePoint,
    bookingDateId: drawerDate.value.id
  })
  console.log(res.data.data);
  if(res.data.code === 1) {
    drawerDate.value.bookingTimeVOList[newIndex-1].id = res.data.data
    drawerDate.value.bookingTimeVOList.forEach((item: any,index: number)=>{
      timeAbleArr.value[index] = true
    })
    ElMessage({
      type: 'success',
      message: '添加时间段成功'
    })
  } else {
    ElMessage({
      type: 'error',
      message: '添加失败'
    })
  }
  console.log(res.data);
}
const subList = async (item:any, index: number)=> {
  console.log('item--->',item.id);
  if (item.id !== 0) {
    const res = await myAxios.post('/book/del/time/id', {
      id: item.id,
    })

    if (res.data.code === 1) {
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
    } else {
      ElMessage({
        type: 'error',
        message: '删除失败'
      })
    }
  }
  drawerDate.value.bookingTimeVOList.pop()
  addbtnText.value = '添加时间'
}
const updateDay = async (row:any)=>{  //修改今天是否可以预约
  const res = await myAxios.post('/book/update/status',{id: row.id})
  if(res.data.code === 1) {
    ElMessage({
      type:'success',
      message: '修改成功'
    });
  }
  await getOutfitList()
}
const judgeNull =(List : any)=>{  //时间段和人数统一判空方法
  console.log('List--->',List);
  if (List.some((item:any) => item.timePoint=== '')) {
    return false;
  }
  return true;
}
const closedDrawer =()=>{  //完全关闭抽屉触发
  let newIndex = drawerDate.value.bookingTimeVOList.length
  timeAbleArr.value.forEach((item: any ,index: number)=>{
    timeAbleArr.value[index] = false
  })
  if(!judgeNull(drawerDate.value.bookingTimeVOList)) {
    // console.log('关闭抽屉的删除数组被激活');
    drawerDate.value.bookingTimeVOList.splice(newIndex-1,1)
  }
  addbtnText.value = '添加时间'
}
const deleteDate = async (id: number)=>{  //删除当前日期方法
  console.log(id)
  const res = await myAxios.post('/book/del/id',{id:id})
  // console.log('res--->',res);
  if(res.data.code === 1) {
    getOutfitList()
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
  } else {
    ElMessage({
      type: 'info',
      message: '请求失败'
    })
  }
}
let photoProductId = 0  //服装商品id
const addDate = ( obj : any ) => { //添加日期方法
  console.log('obj--->',obj);
  addDateVisible.value = true
  photoProductId = obj.photoProductId
}
const submitDate = async ()=> {  //提交日期方法
  appointmentDateAddRequestList.value.forEach((item:any,index:number)=>{
    Object.assign(item, {photoProductId : photoProductId})   //添加photoProductId到appointmentDateAddRequestList每一项中
  })
  // console.log('预约---->',appointmentDateAddRequestList.value);
  const res = await myAxios.post("/book/addBatch", appointmentDateAddRequestList.value)
  // console.log('添加日期返回的结果',res.data)
  if(res.data.code === 1) {
    reload()
  }
  await getOutfitList();
  addDateVisible.value = false
  appointmentDateAddRequestList.value = []
  emitter.emit('clear')
}


const typeSelect : any = ref(true)  //类别下拉选项栏的禁用状态
const isBtnShow1 = ref(false)
const isBtnShow2 = ref(true)
const photoProductsMap :any = ref(new Map())
const keysArray : any = ref([])
const value1:any = ref('')
const value2:any = ref('')
let fieldValue1:any = ''
let fieldValue2:any = ''

const getAllPhotoProducts = async () => {
  keysArray.value = []
  const res = await myAxios.post('/photoProducts/list/map');
  photoProductsMap.value = res.data.data
  console.log('Map==================>', photoProductsMap.value);
  for (var key in photoProductsMap.value) {
    keysArray.value.push(key)
  }
  keysArray.value.unshift('无')
}

const editSpecialProducts = () => {
  typeSelect.value = false
  isBtnShow1.value = !isBtnShow1.value
  isBtnShow2.value = !isBtnShow2.value
}

const saveSpecialProducts = async () => {
  typeSelect.value = true
  isBtnShow1.value = !isBtnShow1.value
  isBtnShow2.value = !isBtnShow2.value
  if (value1.value === '无') {
    fieldValue1 = 0
  } else {
    fieldValue1 = photoProductsMap.value[value1.value]
  }
  if (value2.value === '无') {
    fieldValue2 = 0
  } else {
    fieldValue2 = photoProductsMap.value[value2.value]
  }
  let ids = []
  ids.push(fieldValue1)
  ids.push(fieldValue2)
  const res = await myAxios.post('/photoProducts/special/save', {idList: ids});
  if (res.data.data ) {
    ElMessage({
      type: 'success',
      message: '保存成功'
    })
  }
}

const getSpecialProducts = async () => {
  const res = await myAxios.post('/photoProducts/special/get');
  value1.value = res.data.data[0]
  value2.value = res.data.data[1]
  for (var key in photoProductsMap.value) {
    if (value1.value === photoProductsMap.value[key]) {
      value1.value = key
    }
    if (value2.value === photoProductsMap.value[key]) {
      value2.value = key
    }
  }
  if (value1.value === 0) {
    value1.value = '无'
  }
  if (value2.value === 0) {
    value2.value = '无'
  }

}

const loadForm1 = (value: any) => {
  value1.value = value  //三元运算符 flag=1 是关于"商品类别"选项的值  flag=0 是关于“是否为节日限定”选项的值
}

const loadForm2 = (value: any) => {
  value2.value = value  //三元运算符 flag=1 是关于"商品类别"选项的值  flag=0 是关于“是否为节日限定”选项的值
}



</script>

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