<template>
  <div>
    <el-card shadow="always" :body-style="{ padding: '20px' }" v-if="multipleSelection.length > 0">
      <template #header>
        <div class="text-base font-bold card-header">
          <span>所选短剧：</span>
        </div>
      </template>
      <div class="flex flex-wrap items-start ml-6 choose-wrapper">
        <el-form-item label="" class="font-bold">
          <div v-for="(item, index) in multipleSelection" :key="item.id" class="mb-3 mr-3">
            <el-input type="number" :disabled="false" min="1" v-model.number="sortValues[index]" placeholder="排序"
              size="default" style="width: 115px;"></el-input>
            <el-input v-model="item.name" :disabled="true" placeholder="短剧名称" style="width:300px;"
              class="input-with-select">
            </el-input>
            <el-icon class="ml-3 cursor-pointer" @click="chooseDel(item, index)">
              <Delete />
            </el-icon>
          </div>
        </el-form-item>
      </div>
    </el-card>
    <Search :search="search" :reset="resetQuery">
      <template v-slot:body>
        <el-form-item label="短剧" prop="name">
          <el-input v-model="query.videoName" placeholder="请输入短剧名称" clearable />
        </el-form-item>
        <el-form-item label="状态" prop="updateType">
          <el-select v-model="query.updateType" filterable clearable placeholder="请选择状态">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="频道" prop="categoryId">
          <el-cascader v-model="selectType" :options="cooperations" filterable clearable :change-on-select="true"
            @change="handleCascaderChange" />
        </el-form-item>
        <el-form-item label="微信审核状态" prop="wechatPass">
          <el-select v-model="query.wechatPass" filterable clearable placeholder="请选择微信审核状态">
            <el-option v-for="item in wxstatusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </template>
    </Search>
    <div class="table-default">
      <el-table :data="tableData" ref="multipleTableRef" height="380px" class="mt-3" v-loading="loading" row-key="id"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" reserve-selection />
        <el-table-column prop="id" label="剧号" />
        <el-table-column label="封面" show-overflow-tooltip>
          <template #default="scope">
            <div class="flex flex-col items-start justify-center wrapper">
              <el-popover placement="top" :width="200" trigger="click">
                <template #reference>
                  <el-image :src="scope.row.cover_image" class="cursor-pointer" style="width:48px;height:48px;"
                    fit="contain" :lazy="true"></el-image>
                </template>
                <el-image :src="scope.row.cover_image" style="width:100%;" fit="contain"></el-image>
              </el-popover>
              <el-button type="primary" link size="default" @click="dowload(scope.row)">下载</el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="短剧名称" show-overflow-tooltip min-width="250">
          <template #default="scope">
            <div class="wrapper">
              <span class="text-lg font-bold text-blue-400 cursor-pointer content">
                {{ scope.row.name }}
              </span>
              <span>
                【 {{ scope.row.update_type_str }} 】
              </span>
            </div>
            <div class="wrapper">
              <span class="label">上架时间:</span>
              <span class="content">{{ scope.row.shelf_at }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="total_episode_num" label="集数">
          <template #default="scope">
            <div class="flex wrapper">
              <div v-if="scope.row.update_type == 1">
                <span class="content">
                  {{ scope.row.updated_episode_num }}
                </span>
                <span>/</span>
              </div>
              <div>
                <span class="content">
                  {{ scope.row.total_episode_num }}
                </span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="category_str" label="频道" />
        <el-table-column prop="shelf_type_str" label="上架状态" />
        <el-table-column prop="charge_sequence" label="起始集" />
        <el-table-column prop="charge_coin" label="定价">
          <template #header>
            <div class="flex items-center">
              <span>定价</span>
              <el-tooltip placement="top">
                <template #content> 定价为所需看剧币<br />1元等于100币 </template>
                <el-icon>
                  <InfoFilled />
                </el-icon>
              </el-tooltip>
            </div>
          </template>
          <template #default="scope">
            <span>{{ scope.row.charge_coin }}</span>
          </template>
        </el-table-column>
      </el-table>
      <Paginate />
    </div>
    <div class="flex justify-end">
      <el-button type="primary" @click="confirm">{{
        $t('system.confirm')
      }}</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { downloadImage } from '@/utils/index'
import { InfoFilled, Delete } from '@element-plus/icons-vue';
import { provide } from 'vue'
import { useGetList } from '@/hook/curd/useGetList';
import { useDestroy } from '@/hook/curd/useDestroy';
import { useOpen } from '@/hook/curd/useOpen';
import { videoStockVideoCategoryList, videoStockVideoList } from '@/api/video/index'
const api = 'videoStock/video/list';
const multipleTableRef = ref(null); // 初始化为 null
const multipleSelection = ref([]);
const { data, query, search, reset, loading } = useGetList(api);
const selectType = ref([])
const statusOptions = ref([{ label: '连载中', value: '1' }, { label: '完结', value: '2' }]);
const wxstatusOptions = ref([{ label: '未通过', value: 0 }, { label: '已通过', value: 1 }]);
const cooperations = ref([]);
const emit = defineEmits(['confirm']);
const props = defineProps({
  primary: Object,
});
const sortValues = ref([])
const rowSelectFlag = ref(false)// 禁止toggleRowSelection默认触发handleSelectionChange
const handleCascaderChange = (val: any) => {
  console.log(val, 'valval');
  if (val) {
    // 获取最后一级选项的值
    const lastOptionValue = val[val.length - 1];
    // 更新 selectedOptions 的值
    query.value.categoryId = lastOptionValue;
  } else {
    delete query.value.categoryId
  }
}

const resetQuery = () => {
  query.value = Object.assign({ page: query.value.page, limit: query.value.limit, shelfType: 2 });
  search()
  selectType.value = []
}
const initType = () => {
  videoStockVideoCategoryList().then(res => {
    console.log(res);
    cooperations.value = res.data
  })
}
// 下载封面
const dowload = (e: object) => {
  downloadImage(e.cover_image, e.name)
}

const validateData = () => {
  const sortSet = new Set();
  const nameSet = new Set();

  for (const item of multipleSelection.value) {
    if (item.sort === null || item.sort === undefined) {
      ElMessage.error(`${item.name}的排序不能为空`)
      return false;
    }
    if (sortSet.has(item.sort)) {
      ElMessage.error(`${item.name}的排序重复`)
      return false;
    }
    sortSet.add(item.sort);
    if (nameSet.has(item.name)) {
      ElMessage.error(`${item.name}的排序重复`)
      return false;
    }

    nameSet.add(item.name);
  }

  return true;
};

const tableData = computed(() => data.value?.data);
const chooseDel = (row: object, idx: number) => {
  console.log(row, idx, 'row: object, idx: number', multipleSelection.value[idx]);
  multipleSelection.value.splice(idx, 1);
  // multipleTableRef.value.toggleRowSelection(row, false);//第一次回显的时候没有效果 改成下面那种方式
  setRowSelected()
  search()
}

const handleSelectionChange = (val: []) => {
  console.log(val, 'handleSelectionChangehandleSelectionChange');
  if (rowSelectFlag.value) return
  multipleSelection.value = val;
};
const confirm = () => {
  const params = multipleSelection.value.map((el, index) => {
    multipleSelection.value[index].sort = sortValues.value[index]
    return {
      id: el.id,
      sort: sortValues.value[index],
      name: el.name
    }
  })
  console.log(sortValues.value, params, 'sortValues[index]');
  if (validateData()) {
    // 执行提交逻辑
    console.log('数据验证通过');
    emit('confirm', params)
  }
}

if (props.primary) {
  // console.log(props.primary, 'props.primaryprops.primary');
  multipleSelection.value = JSON.parse(JSON.stringify(props.primary)) || []
  if (multipleSelection.value.length > 0) {
    // 初始化 sortValues 数组长度，保持与 multipleSelection 数组一致
    sortValues.value = multipleSelection.value.map(el => el.sort)
  }
}

const setRowSelected = (status: boolean = true) => {
  rowSelectFlag.value = true
  if (multipleTableRef.value) { // 确保 multipleTableRef 有有效的值
    multipleTableRef.value.clearSelection(); // 清除之前的选中状态
    multipleSelection.value.forEach((item) => {
      multipleTableRef.value.toggleRowSelection(item, status);
    });
  } else {
    ElMessage.error('表格实例未找到');
  }
  rowSelectFlag.value = false
}
onMounted(() => {
  query.value = Object.assign({ page: query.value.page, limit: query.value.limit, shelfType: 2, wechatPass: 1 });
  initType()
  search();
  setRowSelected()
});
</script>

<style scoped lang="scss">
.choose-wrapper {
  height: fit-content;
  max-height: 150px;
  overflow: auto;
}

.table-default {
  .set-warpper {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }

  .wrapper {
    margin: 8px;

    .label {
      margin-right: 6px;
    }

    .content {
      font-size: 15px;
    }
  }
}
</style>
