<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <div class="statistic-card">
          <el-row :gutter="20" justify="space-between">
            <!-- 总发布数 -->
            <el-col :span="6">
              <el-statistic :value="totalNum" class="statistic-item">
                <template #title>
                  <div class="statistic-title">
                    <el-icon><Collection /></el-icon>
                    <span>总发布数</span>
                  </div>
                </template>
                <template #prefix>
                  <div class="statistic-icon total-icon">
                    <el-icon><Promotion /></el-icon>
                  </div>
                </template>
              </el-statistic>
            </el-col>
            <!-- 轮播组发布 -->
            <el-col :span="6">
              <el-statistic :value="lbNum" class="statistic-item">
                <template #title>
                  <div class="statistic-title">
                    <el-icon><RefreshRight /></el-icon>
                    <span>轮播组发布</span>
                  </div>
                </template>
                <template #prefix>
                  <div class="statistic-icon carousel-icon">
                    <el-icon><Refresh /></el-icon>
                  </div>
                </template>
              </el-statistic>
            </el-col>
            <!-- 分屏组发布 -->
            <el-col :span="6">
              <el-statistic :value="jmNum" class="statistic-item">
                <template #title>
                  <div class="statistic-title">
                    <el-icon><Grid /></el-icon>
                    <span>分屏组发布</span>
                  </div>
                </template>
                <template #prefix>
                  <div class="statistic-icon split-icon">
                    <el-icon><Menu /></el-icon>
                  </div>
                </template>
              </el-statistic>
            </el-col>
            <!-- 素材发布 -->
            <el-col :span="6">
              <el-statistic :value="scNum" class="statistic-item">
                <template #title>
                  <div class="statistic-title">
                    <el-icon><Files /></el-icon>
                    <span>素材发布</span>
                  </div>
                </template>
                <template #prefix>
                  <div class="statistic-icon material-icon">
                    <el-icon><Document /></el-icon>
                  </div>
                </template>
              </el-statistic>
            </el-col>
          </el-row>
        </div>
        <el-card shadow="hover" :style="{ marginTop: '10px', height: '60px' }">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="40px">
            <el-form-item label="名称" prop="name">
              <el-input v-model="queryParams.name" style="width: 150px" placeholder="请输入名称" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="类型" prop="itemType">
              <el-select v-model="queryParams.itemType" style="width: 150px" placeholder="请选择类型" clearable>
                <el-option v-for="dict in smsb_push_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="时间" style="width: 270px">
              <el-date-picker v-model="dateRangeCreateTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['source:itemPush:add']">新增
              </el-button>
<!--              <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
                v-hasPermi="['source:itemPush:edit']">修改
              </el-button>
              <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
                v-hasPermi="['source:itemPush:remove']">删除
              </el-button>-->
<!--              <el-button type="warning" plain icon="Download" @click="handleExport"
                v-hasPermi="['source:itemPush:export']">导出
              </el-button>-->
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <div class="table-content">
        <el-table v-loading="loading" :data="itemPushList" @selection-change="handleSelectionChange">
<!--          <el-table-column type="selection" width="55" align="center" />-->
          <el-table-column label="" align="left" prop="" width="10" />
          <el-table-column label="ID" align="left" prop="id" width="180" v-if="true" />
          <el-table-column label="名称" align="left" prop="name" width="500"/>
          <el-table-column label="优先级" align="center" width="100" prop="level">
            <template #default="scope">
              <dict-tag :options="smsb_push_level" :value="scope.row.level" />
            </template>
          </el-table-column>
          <el-table-column label="类型" align="center" width="100" prop="itemType">
            <template #default="scope">
              <dict-tag :options="smsb_push_type" :value="scope.row.itemType" />
            </template>
          </el-table-column>
          <el-table-column label="审核状态" align="center" width="100" prop="status">
            <template #default="scope">
              <dict-tag :options="smsb_push_state" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column label="上架状态" align="center" width="100" prop="isUse">
            <template #default="scope">
              <dict-tag :options="smsb_push_isuse" :value="scope.row.isUse" />
            </template>
          </el-table-column>
          <el-table-column label="生效日期" align="left" prop="startDate" width="100">
            <template #default="scope">
              <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="失效日期" align="left" prop="endDate" width="100">
            <template #default="scope">
              <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="创建人" align="left" prop="createUser" width="100" :show-overflow-tooltip="true" />
          <el-table-column label="发布时间" align="left" prop="createTime" :show-overflow-tooltip="true" />
          <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width" width="150">
            <template #default="scope">
              <!-- <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['source:itemPush:edit']"></el-button>
            </el-tooltip> -->
<!--              <el-tooltip content="提交审核" placement="top">
                <el-button link type="primary" icon="Top" @click="handleReview(scope.row)"
                           v-hasPermi="['source:minioData:add']"></el-button>
              </el-tooltip>-->
              <el-tooltip content="下发详情" placement="top">
                <el-button link type="primary" icon="List" @click="handleDevice(scope.row)"
                           v-hasPermi="['source:itemPush:edit']">详情</el-button>
              </el-tooltip>
              <el-tooltip content="下架" placement="top">
                <el-button link type="primary" icon="Bottom" v-if="scope.row.status == 'finish' && scope.row.isUse == '1'"
                           @click="handleRemoveItem(scope.row)" v-hasPermi="['source:itemPush:edit']">下架</el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" v-if="scope.row.isUse == '0'" @click="handleDelete(scope.row)"
                           v-hasPermi="['source:itemPush:remove']">删除</el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改内容发布对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="1500px" style="height: 750px" append-to-body>
      <el-row :gutter="20" style="height: 100%; display: flex">
        <!--设备列表-->
        <el-col :span="6" style="height: 100%; overflow: auto; padding-right: 10px">
          <el-row style="margin-bottom: 13px;margin-top: 5px">
            <el-input v-model="queryParams.deviceName" placeholder="请输入设备名称" clearable style="width: 270px" />
            <el-button type="primary" @click="getDeviceList" style="margin-left: 10px">查询</el-button>
          </el-row>
          <el-table v-loading="loading" border fit highlight-current-row :data="deviceList" @selection-change="handleSelectDevice" style="height: 520px">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="设备名称" align="left" prop="name" :show-overflow-tooltip="true" />
          </el-table>
        </el-col>
        <!--发布名称-->
        <el-col :span="9" style="height: 570px; overflow: auto; padding-left: 10px">
          <el-form ref="itemPushFormRef" :model="form" :rules="rules" style="margin-top: 5px" label-width="60px">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称" />
            </el-form-item>
            <el-row>
              <el-col :span="12">
                <el-form-item label="类型" prop="itemType">
                  <el-select v-model="form.itemType" placeholder="请选择类型" @change="getItemList">
                    <el-option v-for="dict in smsb_push_type" :key="dict.value" :label="dict.label"
                      :value="parseInt(dict.value)"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="优先级" prop="level">
                  <el-select v-model="form.level" @change="pushLevelChange" placeholder="请选择优先级">
                    <el-option v-for="dict in smsb_push_level" :key="dict.value" :label="dict.label"
                               :value="parseInt(dict.value)" ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="日期" prop="dateRange">
              <el-date-picker v-model="form.dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
                start-placeholder="开始日期" end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]" />
            </el-form-item>
            <!-- Days of the Week -->
<!--            <el-form-item label="每周">
              <el-checkbox-group v-model="form.weekDays">
                <el-checkbox label="0">日</el-checkbox>
                <el-checkbox label="1">一</el-checkbox>
                <el-checkbox label="2">二</el-checkbox>
                <el-checkbox label="3">三</el-checkbox>
                <el-checkbox label="4">四</el-checkbox>
                <el-checkbox label="5">五</el-checkbox>
                <el-checkbox label="6">六</el-checkbox>
              </el-checkbox-group>
            </el-form-item>-->
            <!-- Time Periods -->
            <el-form-item label="时间">
              <div v-for="(timePeriod, index) in form.timeRange" :key="index" class="time-period">
                <el-time-picker v-model="timePeriod.start" placeholder="开始时间" format="HH:mm:ss" style="width: 150px;" :disabled="false" />
                <span>至</span>
                <el-time-picker v-model="timePeriod.end" placeholder="结束时间" format="HH:mm:ss" style="width: 150px;"  :disabled="false" />
                <el-button @click="removeTimePeriod(index)" type="danger" style="margin-left: 10px" icon="Delete"></el-button>
              </div>
              <el-button @click="addTimePeriod" type="primary">新增时间段</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <!--发布内容-->
        <el-col :span="9" style="height: 100%; overflow: auto; padding-left: 10px">
          <!--轮播组 -->
          <div v-if="form.itemType === 1 || form.itemType === 3">
            <el-table v-loading="loading" border fit highlight-current-row :data="itemList" style="height: 570px">
              <el-table-column label="ID" width="200" align="left" :show-overflow-tooltip="true">
                <template #default="{ row }">
                  <el-radio v-model="selectedRowId" :label="row.id" @change="handleRadioChange(row)" />
                </template>
              </el-table-column>
              <el-table-column label="名称" align="left" prop="itemName" :show-overflow-tooltip="true" />
<!--              <el-table-column label="资源数量" align="center" prop="sourceNum" width="80" />-->
              <el-table-column label="创建人" align="center" prop="createUser" width="120" :show-overflow-tooltip="true" />
            </el-table>
          </div>
          <!-- 素材 -->
          <div v-if="form.itemType === 4 ">
            <el-table v-loading="loading" border fit highlight-current-row :data="minioDataList" style="height: 570px" @selection-change="handleSelectionMinioChange">
              <el-table-column type="selection" width="40" align="center" />
              <el-table-column label="ID" prop="id" width="170" align="left" :show-overflow-tooltip="true" />
              <el-table-column label="文件" align="left" prop="originalName"  :show-overflow-tooltip="true" />
              <el-table-column label="预览" align="center" prop="screenshot" width="80">
                <template #default="scope">
                  <div v-if="scope.row.type === 1">
                    <!-- 图片类型 -->
                    <image-preview :src="scope.row.screenshot" style="width: 40px; height: 40px; cursor: pointer" />
                  </div>
                  <div v-else-if="scope.row.type === 2">
                    <el-icon class="VideoPlay" @click="viewVideo(scope.row.screenshot)" size="40" style="cursor: pointer">
                      <VideoPlay />
                    </el-icon>
                  </div>
                  <div v-else-if="scope.row.type === 4">
                    <!-- PPT类型 -->
                    <el-icon :size="40" @click="downloadFile(scope.row.fileUrl)" style="cursor: pointer;">
                      <Document />
                    </el-icon>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>
      </el-row>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 下发详情弹窗 -->
    <el-dialog :title="deviceDialog.title" v-model="deviceDialog.visible" width="1400px" append-to-body>
      <!--发布名称-->
      <div>
        <el-descriptions title="详情信息" :column="2" border>
          <el-descriptions-item label="发布名称">
            {{form.name}}
          </el-descriptions-item>
          <el-descriptions-item label="发布类型">
            <dict-tag :options="smsb_push_type" :value="form.itemType" />
          </el-descriptions-item>
          <el-descriptions-item label="开始时间">
            {{form.startDate}}
          </el-descriptions-item>
          <el-descriptions-item label="结束时间">
            {{form.endDate}}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-table v-loading="deviceLoading" border fit highlight-current-row :data="pushSourceList" style="height: 542px; margin-top: 10px">
            <el-table-column label="排序" align="center" prop="sort" width="60" :show-overflow-tooltip="true" />
            <el-table-column label="时长" align="center" prop="duration" width="80" :show-overflow-tooltip="true"/>
            <el-table-column label="资源" align="left" prop="fileName" :show-overflow-tooltip="true"/>
            <el-table-column label="预览" align="center" prop="screenshot" width="120">
              <template #default="scope">
                <div v-if="scope.row.fileType === 1">
                  <image-preview :src="scope.row.screenshot" style="width: 40px; height: 40px; cursor: pointer" />
                </div>
                <div v-else-if="scope.row.fileType === 2">
                  <el-icon class="VideoPlay" @click="viewVideo(scope.row.screenshot)" size="40" style="cursor: pointer">
                    <VideoPlay />
                  </el-icon>
                </div>
                <div v-else-if="scope.row.fileType === 4">
                  <!-- PPT类型 -->
                  <el-icon :size="40" @click="downloadFile(scope.row.fileUrl)" style="cursor: pointer;">
                    <Document />
                  </el-icon>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="12">
          <!--设备列表-->
          <el-button type="primary" v-if="removeItemTag" icon="Bottom" :disabled="removeButtonTag"
                     @click="handleDoRemoveItem()" style="margin-top: 10px"> 下架 </el-button>
          <el-table v-loading="deviceLoading" border fit highlight-current-row :data="pushDeviceList" style="height: 500px; margin-top: 10px"
                    @selection-change="handleDeviceSelectionChange">
            <el-table-column type="selection" v-if="removeItemTag" width="55" align="center" />
            <el-table-column label="设备名称" align="left" prop="deviceName" :show-overflow-tooltip="true" />
            <el-table-column label="发布排序" align="center" prop="sortNum" width="80" :show-overflow-tooltip="true" />
            <el-table-column label="发布状态" align="center" prop="pushState" width="100" :show-overflow-tooltip="true">
              <template #default="scope">
                <dict-tag :options="smsb_push_device_state" :value="scope.row.pushState" />
              </template>
            </el-table-column>
            <el-table-column label="发布时间" align="left" prop="createTime" width="160" :show-overflow-tooltip="true" />
            <el-table-column label="操作" v-if="removeItemTag" align="center" class-name="small-padding fixed-width"
                             width="80">
              <template #default="scope">
                <el-tooltip content="下架" placement="top">
                  <el-button link type="primary" icon="Bottom" @click="handleDoRemoveItem(scope.row)"
                             v-hasPermi="['source:itemPush:edit']">下架</el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用于展示播放的视频 -->
    <el-dialog v-model="videoDialogVisible" append-to-body>
      <video width="100%" controls :src="videoUrl"></video>
    </el-dialog>
  </div>
</template>

<script setup name="ItemPush" lang="ts">
import {
  addItemPush,
  delItemPush,
  getItemPush,
  listItemPush,
  pushStatistics,
  reviewItemPush,
  updateItemPush,
  validateTime,
} from '@/api/smsb/source/item_push';
import {ItemPushForm, ItemPushQuery, ItemPushVO} from '@/api/smsb/source/item_push_type';
import {DeviceQuery, DeviceVO} from '@/api/smsb/device/device_type';
import {listDevice} from '@/api/smsb/device/device';
import {ItemQuery, ItemVO} from '@/api/smsb/source/item_type';
import {listItem, listItemPushSource} from '@/api/smsb/source/item';
import {ItemPushDeviceVO} from '@/api/smsb/source/item_push_device_type';
import {listItemPushDeviceV2, removeItemPushDevice} from '@/api/smsb/source/item_push_device';
import {MinioDataVO} from "@/api/smsb/source/minioData_type";
import {listMinioData} from "@/api/smsb/source/minioData";
import {ItemFileRelVO} from "@/api/smsb/source/itemFile_type";

const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const {smsb_push_state, smsb_push_device_state, smsb_push_type, smsb_push_level,smsb_push_isuse} = toRefs<any>(
  proxy?.useDict('smsb_push_state', 'smsb_push_device_state', 'smsb_push_type', 'smsb_push_level','smsb_push_isuse')
);

const itemPushList = ref<ItemPushVO[]>([]);
const itemList = ref<ItemVO[]>([]);
const minioDataList = ref<MinioDataVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const deviceLoading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const removePushId = ref<number | string>();
const removeIds = ref<Array<string | number>>([]);
const deviceIds = ref<Array<string | number>>([]);
const itemIds = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const deviceTotal = ref(0);
const itemTotal = ref(0);
const totalNum = ref(0);
const lbNum = ref(0);
const jmNum = ref(0);
const scNum = ref(0);
const dateRangeCreateTime = ref<[DateModelType, DateModelType]>(['', '']);
const deviceList = ref<DeviceVO[]>([]);
const pushDeviceList = ref<ItemPushDeviceVO[]>([]);
const pushSourceList = ref<ItemFileRelVO[]>([]);
// 存储选中行的唯一标识
const selectedRowId = ref<number | null>(null);
const selectedMinioDataIds = ref<Array<number | string>>([]);
const removeItemTag = ref(false);
const removeButtonTag = ref(true);
const queryFormRef = ref<ElFormInstance>();
const itemPushFormRef = ref<ElFormInstance>();
const videoUrl = ref('');
const videoDialogVisible = ref(false);

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const deviceDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ItemPushForm = {
  name: undefined,
  level: 200,
  itemType: 1, // "分屏组"类型
  deviceIds: undefined,
  itemIds: undefined,
  dateRange: undefined,
  weekDays: ['0', '1', '2', '3', '4', '5', '6'],
  timeRange: []
};
const data = reactive<PageData<ItemPushForm, ItemPushQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    name: undefined,
    level: undefined,
    itemType: undefined,
    status: undefined,
    params: {
      createTime: undefined
    }
  },
  rules: {}
});

const dialogData = reactive<DialogPageData<DeviceQuery>>({
  dialogQueryParams: {
    pageNum: 1,
    pageSize: 10000,
    pushId: undefined
  }
});

const itemData = reactive<TransPageData<ItemQuery>>({
  transQueryParams: {
    pageNum: 1,
    pageSize: 10000,
    itemType: undefined,
    types: undefined
  }
});

const { queryParams, form, rules } = toRefs(data);
const { dialogQueryParams } = toRefs(dialogData);
const { transQueryParams } = toRefs(itemData);

const getStatistics = async () => {
  const res = await pushStatistics();
  console.log(res.data);
  totalNum.value = res.data.totalNum;
  lbNum.value = res.data.lbNum;
  jmNum.value = res.data.jmNum;
  scNum.value = res.data.scNum;
};

/** 查询内容发布列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.params = {};
  proxy?.addDateRange(queryParams.value, dateRangeCreateTime.value, 'CreateTime');
  const res = await listItemPush(queryParams.value);
  itemPushList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 查询设备列表 */
const getDeviceList = async () => {
  dialogQueryParams.value.name = queryParams.value.deviceName;
  const res = await listDevice(dialogQueryParams.value);
  deviceList.value = res.rows;
  deviceTotal.value = res.total;
  loading.value = false;
};

const getItemList = async () => {
  transQueryParams.value.itemType = form.value.itemType;
  if (form.value.itemType === 1 || form.value.itemType === 3) {
    const res = await listItem(transQueryParams.value);
    itemList.value = res.rows;
    itemTotal.value = res.total;
  }
  if (form.value.itemType === 4) {
    if (form.value.level === 400) {
      transQueryParams.value.types = [1, 2, 3, 4];
    }else {
      transQueryParams.value.types = [1, 2, 3];
    }
    const res = await listMinioData(transQueryParams.value);
    minioDataList.value = res.rows;
  }
};
const pushLevelChange = async () => {
  if (form.value.itemType === 4) {
    if (form.value.level === 400) {
      transQueryParams.value.types = [1, 2, 3, 4];
    }else {
      transQueryParams.value.types = [1, 2, 3];
    }
    const res = await listMinioData(transQueryParams.value);
    minioDataList.value = res.rows;
  }
}
// 播放视频
const viewVideo = (url: string) => {
  videoUrl.value = url;
  videoDialogVisible.value = true;
};
const downloadFile = (fileUrl) => {
  if (fileUrl) {
    // 创建一个隐藏的a标签来触发下载
    const link = document.createElement('a');
    link.href = fileUrl;
    link.download = ''; // 浏览器会自动使用URL中的文件名
    link.target = '_blank';
    link.style.display = 'none';

    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  } else {
    proxy?.$modal.msgError('文件地址不存在，无法下载');
  }
};
const addTimePeriod = () => {
  const now = new Date();
  now.setHours(0, 0, 0, 0);
  const end = new Date();
  end.setHours(23, 59, 59, 0);
  if (form.value.timeRange.length >= 5) {
    proxy?.$modal.msgError('时间段最多支持添加5个！');
    return;
  }
  form.value.timeRange.push({start: new Date(now), end: new Date(end)});
};

const removeTimePeriod = (index: number) => {
  form.value.timeRange.splice(index, 1);
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
  deviceDialog.visible = false;
  videoDialogVisible.value = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  itemPushFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const handleDevice = async (row?: ItemPushVO) => {
  removeItemTag.value = false;
  const pushId = row.id;
  deviceDialog.title = '下发详情';
  deviceDialog.visible = true;
  dialogQueryParams.value.pushId = pushId;
  // dialogQueryParams.value.pageSize = 1000;
  pushDeviceList.value = [];
  const pushInfo = await getItemPush(pushId);
  Object.assign(form.value, pushInfo.data);
  await getItemDeviceList(pushId);
  await getItemSourceList(pushId);
};
const handleRemoveItem = async (row?: ItemPushVO) => {
  removeItemTag.value = true;
  removeButtonTag.value = true;
  removeIds.value = [];
  const pushId = row.id;
  deviceDialog.title = '下架';
  deviceDialog.visible = true;
  dialogQueryParams.value.pushId = pushId;
  removePushId.value = pushId;
  dialogQueryParams.value.pageSize = 1000;
  pushDeviceList.value = [];
  const pushInfo = await getItemPush(pushId);
  Object.assign(form.value, pushInfo.data);
  await getItemDeviceList(pushId);
  await getItemSourceList(pushId);
};
const handleDoRemoveItem = async (row?: ItemPushDeviceVO) => {
  const deviceIds = Array<number | string>();
  if (null != row) {
    deviceIds.push(row.deviceId);
  }
  if (removeIds.value.length > 0) {
    removeIds.value.forEach((deviceId) => {
      deviceIds.push(deviceId);
    });
  }
  const removeParam = {
    pushId: removePushId.value,
    deviceIds: deviceIds
  };
  await removeItemPushDevice(removeParam);
  await getItemDeviceList(removePushId.value);
};

const getItemDeviceList = async (pushId: number | string) => {
  deviceLoading.value = true;
  dialogQueryParams.value.pushId = pushId;
  const res = await listItemPushDeviceV2(dialogQueryParams.value);
  pushDeviceList.value = res.data;
  deviceLoading.value = false;
};

const getItemSourceList = async (pushId: number | string) => {
  deviceLoading.value = true;
  const res = await listItemPushSource(pushId);
  pushSourceList.value = res.data;
  deviceLoading.value = false;
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRangeCreateTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ItemPushVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

const handleDeviceSelectionChange = (selection: ItemPushDeviceVO[]) => {
  removeIds.value = selection.map((item) => item.deviceId);
  removeButtonTag.value = removeIds.value.length == 0;
};

/** 多选框选中数据 */
const handleSelectDevice = (selection: DeviceVO[]) => {
  deviceIds.value = selection.map((item) => item.id);
  form.value.deviceIds = deviceIds.value;
};

const handleSelectItem = (selection: ItemVO[]) => {
  itemIds.value = selection.map((item) => item.id);
  form.value.itemIds = itemIds.value;
};
const handleSelectionMinioChange = (selection: MinioDataVO[]) => {
  // 获取当前已选中的 ID 列表
  const currentSelectedIds = [...selectedMinioDataIds.value];

  // 提取当前选中项的 ID
  const newSelectedIds = selection.map(item => item.id);

  // 构建新的有序 ID 列表：
  // 1. 保留仍然被选中的 ID（保持原有顺序）
  // 2. 添加新选中的 ID（按当前 selection 顺序追加）
  const orderedIds = [
    ...currentSelectedIds.filter(id => newSelectedIds.includes(id)),
    ...newSelectedIds.filter(id => !currentSelectedIds.includes(id))
  ];

  // 更新选中 ID 列表
  selectedMinioDataIds.value = orderedIds;

  // 绑定到 form.itemIds
  form.value.itemIds = orderedIds;
  console.log('当前选中的文件:', form.value.itemIds)
}
const handleRadioChange = (row: ItemVO) => {
  const itemIds = [row.id];
  form.value.itemIds = itemIds;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '内容发布';
  selectedRowId.value = null;
  queryParams.value.deviceName = null;
  getDeviceList();
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ItemPushVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getItemPush(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改内容发布';
  await getDeviceList();
};

/** 提交按钮 */
const submitForm = () => {
  itemPushFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateItemPush(form.value).finally(() => (buttonLoading.value = false));
      } else {
        // 校验时间冲突
        const resTime = await validateTime(form.value).finally(() => (buttonLoading.value = false));
        if (resTime.data.code !== 200) {
          await proxy?.$modal.confirm("排期时间存在冲突，是否覆盖之前排期").finally(() => (buttonLoading.value = false));
          console.log(resTime.data)
          await addItemPush(form.value).finally(() => (buttonLoading.value = false));
        } else {
          await addItemPush(form.value).finally(() => (buttonLoading.value = false));
        }
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
      await getStatistics();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ItemPushVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除已选择的数据项？').finally(() => (loading.value = false));
  await delItemPush(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
  await getStatistics();
};

const handleReview = async (row?: ItemPushVO) => {
  const id = row?.id;
  if (row.status !== 'draft') {
    proxy?.$modal.msgError('只有未提交状态可以提交审核');
    return;
  }
  await proxy?.$modal.confirm('是否确认提交审核名称为"' + row.name + '"的数据项？').finally(() => (loading.value = false));
  await reviewItemPush(id);
  proxy?.$modal.msgSuccess('提交成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'source/itemPush/export',
    {
      ...queryParams.value
    },
    `itemPush_${new Date().getTime()}.xlsx`
  );
};
watch(() => deviceDialog.visible, (newValue) => {
  if (!newValue) {
    getList();
    getStatistics();
  }
});
onMounted(() => {
  getList();
  getStatistics();
  getItemList();
});
</script>
<style scoped>
.time-period {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.time-period span {
  margin: 0 10px;
}

.dialog-footer {
  text-align: right;
}
.statistic-card {
  border-radius: 1px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
  border: 1px solid #ebeef5;
  padding: 10px 0;
  height: 100px;
  background: #fff;
  width: calc(100% - 3px);
}

.statistic-item {
  text-align: center;
  padding: 10px 0;
}

.statistic-title {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 14px;
  color: #606266;
  font-weight: 500;
  margin-bottom: 8px;
}

.statistic-icon {
  width: 40px;
  height: 40px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 10px;
  color: white;
  font-size: 18px;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.15);
}

.total-icon {
  background: linear-gradient(135deg, #409eff, #2282ff);
}

.carousel-icon {
  background: linear-gradient(135deg, #e6a23c, #d48c1f);
}

.split-icon {
  background: linear-gradient(135deg, #67c23a, #48ab1f);
}

.material-icon {
  background: linear-gradient(135deg, #909399, #73767a);
}

:deep(.statistic-item .el-statistic__content) {
  font-size: 24px;
  font-weight: 700;
  color: #303133;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  :deep(.el-col) {
    flex: 0 0 50%;
    max-width: 50%;
    margin-bottom: 10px;
  }

  :deep(.el-row) {
    flex-wrap: wrap;
  }

  .statistic-card {
    padding: 10px 0;
  }
}

@media (max-width: 768px) {
  :deep(.el-col) {
    flex: 0 0 100%;
    max-width: 100%;
  }

  .statistic-title {
    font-size: 13px;
  }

  .statistic-icon {
    width: 36px;
    height: 36px;
    font-size: 16px;
  }

  :deep(.statistic-item .el-statistic__content) {
    font-size: 20px;
  }
}
</style>
