<template>
  <div class="table_page">
    <div>
      <el-input style="width: 240px; margin-right: 10px;" suffix-icon="Search" placeholder="请输入服装名称"  size="default"
                v-model="outfitName"></el-input>
      <el-button type="primary" @click="onSearch(outfitName)" style="margin-right: 10px;" size="default">
        搜索
      </el-button>
      <el-select v-model="outfitType" @change="(event: any) => searchByType(event)" placeholder="服装类别"
                 style="width: 240px;  margin-right: 10px;" size="default" :clearable="true">
        <el-option v-for="(item,index) in typeList" :key="index" :label="item.label" :value="item.value"/>
      </el-select>
      <el-select v-model="state" placeholder="服装状态" @change="(event: any) => searchByState(event)" size="default"
                 style="width: 240px;  margin-right: 10px;">
        <el-option label="已上架" value="1"/>
        <el-option label="已下架" value="0"/>
      </el-select>
      <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"
              @select="selectChange"
              :header-cell-style="{ 'text-align': 'center' }">
      <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.image" 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="180">
        <template #default="scope">
          <div>
            {{ scope.row.price }} 元
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="categoryId" label="服装类别">
        <template #default="scope">
          <div>
            {{ outfitTypeMap.get(scope.row.categoryId) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="period" label="可租赁天数"></el-table-column>
      <el-table-column label="是否上架">
        <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.$index, 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>
</template>

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

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 outfitName = ref('');
const state = ref('');  //根据商品上架状态select栏
const tableData: any = ref([]);  //实体类商品表格
const reload: any = inject("reload")  //页面重新刷新
const typeList: any = ref([
  {
    value: '',
    label: ''
  }
])
const outfitType = ref('') //商品类别
const outfitTypeMap = new Map()

onBeforeMount(()=>{
  getOutfitList()
  getTypeList()
})

onMounted(() => {
  // console.log('map--->',outfitTypeMap)
})
const getOutfitList = async () => {
  try {
    const res = await myAxios.post('/clothes/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)  //总数据量，用于分页
    } else {
      ElMessage({
        message: '获取数据失败',
      });
      return;
    }
  } catch (error) {
    ElMessage({
      message: '发生错误',
    });
  }
}
const getTypeList = async () => {
  const res = await myAxios.post('/clothesCategory/list/web', {})  //获取商品列表
  console.log('类别--->',res.data)
  for (let key in res.data.data) {     //循环赋值
    typeList.value[key] = {
      value: res.data.data[key].id,
      label: res.data.data[key].name
    }
    outfitTypeMap.set(res.data.data[key].id, res.data.data[key].name);
  }
}

const searchByType = (event: any) => { //通过类别搜索
  searchParams.value.categoryId = event
  searchParams.value.current = 1
  getOutfitList()
}

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('/clothes/delete', {id: index})
  // console.log(res)
  if (res.data.code === 1) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    await getOutfitList()
  } else {
    WarnInfo(res.data.message)
  }
  await getTypeList()
}
//详情或编辑
const ReviseOrView = (row: any, flag: number) => {
  router.push({
    name: '租赁服装详情',
    params: {
      id: row.id,
      flag: flag
    }
  })
}

//下架服装
const handleOff = async (index: number, row: any) => {
  // console.log('此商品--->',row)
  row.isShelves ? row.isShelves = 0 : row.isShelves = 1  //三元运算符  改变那一行的上架值
  const res = await myAxios.post('/clothes/shelves', {id: row.id})
  if (res.data.code === 1) {
    ElMessage({
      type: 'success',
      message: '更新成功'
    })
  }
}

//处理行数大小变化
const handleSizeChange = (newSize: any) => {
  searchParams.value.pageSize = newSize //新的页面数
  getOutfitList()
}
//处理当前表格变化
const handleCurrentChange = (Current: any) => {
  searchParams.value.current = Current
  getOutfitList()
}
//重置按钮
const reset = () => {
  reload()
};

//批量删除
const delBatch = async () => {
  console.log(idList.value);
  const res = await myAxios.post('/clothes/delBatch', {
    idList: idList.value
  })
  console.log(res.data);
  if (res.data.code === 1) {
    ElMessage({
      type: 'success',
      message: '批量删除成功'
    })
    getOutfitList()
  } 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 onSearch = (value: string) => {
  searchParams.value.name = value
  searchParams.value.current = 1
  getOutfitList()
}
</script>

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