<template>
  <div class="split-root">
    <div class="p-2 flex">
      <!--    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">-->
      <!--      <div v-show="showSearch" class="mb-[10px]"></div>-->
      <!-- 左侧示意图 -->
      <div class="w-1/3 p-2 border-r">示意图</div>
      <!-- 中间 Table -->
      <div class="w-1/3 p-2 border-r table-container">
        <el-radio-group v-model="screenNum" @change="screenChange">
          <el-radio-button label="第一屏" value="1" v-if="splitScreen !== 4" />
          <el-radio-button label="第二屏" value="2" v-if="splitScreen !== 4" />
          <el-radio-button label="第三屏" value="3" v-if="splitScreen === 3" />
          <el-radio-button label="播放框" value="4" v-if="splitScreen === 4" />
        </el-radio-group>
        <el-table :data="minioDataList" ref="minioTable"
          @selection-change="handleSelectionFile"
          @select="handleSelect"
          @select-all="handleSelectAll"
          style="margin-top: 20px">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="原名" align="left" prop="originalName" width="150" :show-overflow-tooltip="true" />
          <el-table-column label="类型" align="center" prop="type" width="80">
            <template #default="scope">
              <dict-tag :options="smsb_source_type" :value="scope.row.type" />
            </template>
          </el-table-column>
          <el-table-column label="大小" align="center" prop="size" />
          <el-table-column label="时长" align="center" prop="duration" />
          <el-table-column label="截图" align="center" prop="screenshot">
            <template #default="scope">
              <image-preview :src="scope.row.screenshot" style="width: 40px; height: 40px; cursor: pointer" />
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="fileTotal > 0" :total="fileTotal" v-model:page="dialogQueryParams.pageNum"
          v-model:limit="dialogQueryParams.pageSize" @pagination="getFileList" />
      </div>
      <!-- 右侧内容 -->
      <div class="w-1/3 p-2">
        <div v-if="screenNum === '1'" class="table-container">
          <el-table ref="selectedTable" :data="selectedFiles1" border>
            <!-- 显示排序数字 -->
            <el-table-column label="排序" width="80">
              <template #default="{ row }">
                <span class="order-number">{{ row.order }}</span>
              </template>
            </el-table-column>
            <el-table-column label="文件名">
              <template #default="{ row }">
                <span>{{ row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column label="播放时长">
              <template #default="{ row }">
                <el-input-number v-model="row.duration" :min="1" :max="300"></el-input-number>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-if="screenNum === '2'" class="table-container">
          <el-table ref="selectedTable" :data="selectedFiles2" border>
            <!-- 显示排序数字 -->
            <el-table-column label="排序" width="80">
              <template #default="{ row }">
                <span class="order-number">{{ row.order }}</span>
              </template>
            </el-table-column>
            <el-table-column label="文件名">
              <template #default="{ row }">
                <span>{{ row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column label="播放时长">
              <template #default="{ row }">
                <el-input-number v-model="row.duration" :min="1" :max="300"></el-input-number>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-if="screenNum === '3'" class="table-container">
          <el-table ref="selectedTable" :data="selectedFiles3" border>
            <!-- 显示排序数字 -->
            <el-table-column label="排序" width="80">
              <template #default="{ row }">
                <span class="order-number">{{ row.order }}</span>
              </template>
            </el-table-column>
            <el-table-column label="文件名">
              <template #default="{ row }">
                <span>{{ row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column label="播放时长">
              <template #default="{ row }">
                <el-input-number v-model="row.duration" :min="1" :max="300"></el-input-number>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-if="screenNum === '4'" class="table-container">
          <el-table ref="selectedTable" :data="selectedFiles4" border>
            <!-- 显示排序数字 -->
            <el-table-column label="排序" width="80">
              <template #default="{ row }">
                <span class="order-number">{{ row.order }}</span>
              </template>
            </el-table-column>
            <el-table-column label="文件名">
              <template #default="{ row }">
                <span>{{ row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column label="播放时长">
              <template #default="{ row }">
                <el-input-number v-model="row.duration" :min="1" :max="300"></el-input-number>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <div class="button-container">
      <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">关 闭</el-button>
    </div>
    <div class="button-container">
      <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">关 闭</el-button>
    </div>
  </div>
</template>

<script setup name="ItemSplit" lang="ts">
import { MinioDataQuery, MinioDataVO } from '@/api/smsb/source/minioData_type';
import { splitItemInfo, updateItem, updateItemSplit } from '@/api/smsb/source/item';
import { listMinioData } from '@/api/smsb/source/minioData';
import { ItemSplitScreenVO } from '@/api/smsb/source/item_split_screen_type';
import { ElTable } from 'element-plus';
import { SplitUploadForm } from '@/api/smsb/source/item_type';

const route = useRoute();
const minioTable = ref(ElTable);
// 选中的文件
const selectedFiles1 = ref<{ id: number; name: string; duration: number; order: number }[]>([]);
const selectedFiles2 = ref<{ id: number; name: string; duration: number; order: number }[]>([]);
const selectedFiles3 = ref<{ id: number; name: string; duration: number; order: number }[]>([]);
const selectedFiles4 = ref<{ id: number; name: string; duration: number; order: number }[]>([]);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { smsb_source_type } = toRefs<any>(proxy?.useDict('smsb_source_type'));
const dialogData = reactive<DialogPageData<MinioDataQuery>>({
  dialogQueryParams: {
    pageNum: 1,
    pageSize: 10,
    params: {}
  }
});
const minioDataList = ref<MinioDataVO[]>([]);
const screenNum = ref<string>();
const itemSplitVo = ref<ItemSplitScreenVO>();
const splitScreen = ref(0);
const buttonLoading = ref(false);
const itemId = ref<string>();
const fileTotal = ref(0);
const { dialogQueryParams } = toRefs(dialogData);
const uploadForm = reactive<SplitUploadForm>({
  itemId: undefined,
  selectedFiles1: undefined,
  selectedFiles2: undefined,
  selectedFiles3: undefined,
  selectedFiles4: undefined
});

const screenChange = () => {
  console.log(screenNum.value);
  // minioTable.value.clearSelection();
};

const getParamItemId = () => {
  itemId.value = route.params.itemId as string;
  console.log(itemId.value);
  getItemInfo();
};

const getItemInfo = async () => {
  const res = await splitItemInfo(itemId.value);
  console.log(res.data);
  itemSplitVo.value = res.data;
  splitScreen.value = res.data.splitScreen;
  if (splitScreen.value === 4) {
    screenNum.value = '4';
  } else {
    screenNum.value = '1';
  }
};

// 多选框选中文件数据（与 index.vue 保持一致，支持增量、去重、排序）
const handleSelectionFile = (selection: MinioDataVO[]) => {
  let selectedFilesRef;
  if (screenNum.value === '1') selectedFilesRef = selectedFiles1;
  if (screenNum.value === '2') selectedFilesRef = selectedFiles2;
  if (screenNum.value === '3') selectedFilesRef = selectedFiles3;
  if (screenNum.value === '4') selectedFilesRef = selectedFiles4;
  if (!selectedFilesRef) return;

  selection.forEach((item) => {
    if (!selectedFilesRef.value.some((f) => String(f.id) === String(item.id))) {
      selectedFilesRef.value.push({
        id: item.id,
        name: item.originalName,
        type: item.type,
        duration: item.type === 1 ? 10 : item.duration,
        order: 0
      });
    }
  });
  // 重新排序
  selectedFilesRef.value = selectedFilesRef.value.map((f, idx) => ({ ...f, order: idx + 1 }));
};

// 取消单个选中
const handleSelect = (selection: MinioDataVO[], row: MinioDataVO) => {
  let selectedFilesRef;
  if (screenNum.value === '1') selectedFilesRef = selectedFiles1;
  if (screenNum.value === '2') selectedFilesRef = selectedFiles2;
  if (screenNum.value === '3') selectedFilesRef = selectedFiles3;
  if (screenNum.value === '4') selectedFilesRef = selectedFiles4;
  if (!selectedFilesRef) return;

  if (!selection.some((item) => String(item.id) === String(row.id))) {
    selectedFilesRef.value = selectedFilesRef.value.filter((f) => String(f.id) !== String(row.id));
    selectedFilesRef.value = selectedFilesRef.value.map((f, idx) => ({ ...f, order: idx + 1 }));
  }
};

// 取消全选
const handleSelectAll = (selection: MinioDataVO[]) => {
  let selectedFilesRef;
  if (screenNum.value === '1') selectedFilesRef = selectedFiles1;
  if (screenNum.value === '2') selectedFilesRef = selectedFiles2;
  if (screenNum.value === '3') selectedFilesRef = selectedFiles3;
  if (screenNum.value === '4') selectedFilesRef = selectedFiles4;
  if (!selectedFilesRef) return;

  const currentPageIds = new Set(minioDataList.value.map((item) => String(item.id)));
  const selectedIds = new Set(selection.map((item) => String(item.id)));
  selectedFilesRef.value = selectedFilesRef.value.filter((f) => !currentPageIds.has(String(f.id)) || selectedIds.has(String(f.id)));
  selectedFilesRef.value = selectedFilesRef.value.map((f, idx) => ({ ...f, order: idx + 1 }));
};
/** 查询文件资源列表 */
const getFileList = async () => {
  const res = await listMinioData(dialogQueryParams.value);
  minioDataList.value = res.rows.map((data) => ({
    ...data,
    size: (parseFloat(data.size) / 1024).toFixed(3) + 'MB'
  }));
  fileTotal.value = res.total;
  // 加载后自动恢复选中（与 index.vue 保持一致）
  nextTick(() => {
    let selectedFilesRef;
    if (screenNum.value === '1') selectedFilesRef = selectedFiles1;
    if (screenNum.value === '2') selectedFilesRef = selectedFiles2;
    if (screenNum.value === '3') selectedFilesRef = selectedFiles3;
    if (screenNum.value === '4') selectedFilesRef = selectedFiles4;
    if (!selectedFilesRef) return;
    if (selectedFilesRef.value?.length) {
      const selectedIds = new Set(selectedFilesRef.value.map((f) => f.id));
      minioDataList.value.forEach((row) => {
        if (selectedIds.has(row.id)) {
          minioTable.value?.toggleRowSelection(row, true);
        }
      });
    }
  });
};

/** 提交按钮 */
const submitForm = async () => {
  buttonLoading.value = true;
  uploadForm.itemId = itemId.value;
  uploadForm.selectedFiles1 = selectedFiles1.value;
  uploadForm.selectedFiles2 = selectedFiles2.value;
  uploadForm.selectedFiles3 = selectedFiles3.value;
  uploadForm.selectedFiles4 = selectedFiles4.value;
  console.log(uploadForm);
  await updateItemSplit(uploadForm).finally(() => (buttonLoading.value = false));
  proxy?.$modal.msgSuccess('编辑成功');
  // 跳转页面进行数据关联
  proxy.$router.push('/source/item');
};
const cancel = () => {
  proxy.$router.push('/source/item');
};

onMounted(() => {
  getParamItemId();
  getFileList();
});
</script>
<style scoped>
.table-container {
  height: 900px;
  /* 设置固定高度，根据需要调整 */
  overflow-y: auto;
  /* 当内容超出时显示滚动条 */
}

.button-container {
  display: flex;
  justify-content: center;
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 10px 0;
  background-color: white;
  /* 可选：根据需要设置背景色 */
  box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
  /* 可选：添加阴影效果 */
}
</style>
