<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]">
        <el-card shadow="hover" :style="{ height: '70px' }">
          <el-row :gutter="20" align="middle">
            <!-- 节目总数 -->
            <el-col :span="8" style="display: flex; justify-content: center; align-items: center">
              <el-statistic :value="totalNum">
                <template #title>
                  <div style="display: inline-flex; align-items: center">节目总数</div>
                </template>
              </el-statistic>
            </el-col>
            <!-- 轮播总数 -->
            <el-col :span="8" style="display: flex; justify-content: center; align-items: center">
              <el-statistic :value="lbNum">
                <template #title>
                  <div style="display: inline-flex; align-items: center">轮播总数</div>
                </template>
              </el-statistic>
            </el-col>
            <!-- 节目总数 -->
            <el-col :span="8" style="display: flex; justify-content: center; align-items: center">
              <el-statistic :value="jmNum">
                <template #title>
                  <div style="display: inline-flex; align-items: center">节目总数</div>
                </template>
              </el-statistic>
            </el-col>
          </el-row>
        </el-card>
        <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="itemName">
              <el-input v-model="queryParams.itemName" 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_item_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="时间" style="width: 250px">
              <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-date-picker>
            </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="handleAddL" v-hasPermi="['source:item:add']"> 新增轮播组 </el-button>
              <el-button type="primary" plain icon="Plus" @click="handleAddJ" v-hasPermi="['source:item:add']"> 新增分屏组 </el-button>
              <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['source:item:edit']"
                >修改
              </el-button>
              <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['source:item:remove']"
                >删除
              </el-button>
              <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['source:item:export']"> 导出 </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <el-table v-loading="loading" :data="itemList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="ID" align="left" prop="id" v-if="true" width="180" :show-overflow-tooltip="true" />
        <el-table-column label="名称" align="left" prop="itemName" />
        <el-table-column label="类型" align="center" prop="itemType" width="100">
          <template #default="scope">
            <dict-tag :options="smsb_item_type" :value="scope.row.itemType" />
          </template>
        </el-table-column>
        <el-table-column label="分屏" align="center" prop="splitScreen" width="100">
          <template #default="scope">
            <dict-tag :options="smsb_split_screen" :value="scope.row.splitScreen" />
          </template>
        </el-table-column>
        <el-table-column label="资源数量" align="center" prop="sourceNum" width="100" />
        <el-table-column label="创建人" align="left" prop="createUser" width="120" :show-overflow-tooltip="true" />
        <el-table-column label="创建时间" align="left" prop="createTime" width="160" />
        <el-table-column label="更新时间" align="left" prop="updateTime" width="160" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['source:item:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['source:item:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <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="1200px" append-to-body>
      <div class="dialog-container">
        <!-- 左侧文件列表 -->
        <div class="table-container">
          <!-- 界面名称输入框 -->
          <el-input v-model="itemName" placeholder="请输入轮播组名称" class="interface-input"></el-input>

          <el-table :data="minioDataList" @selection-change="handleSelectionFile">
            <el-table-column type="selection" width="55" align="center" />
            <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="left" prop="originalName" width="150" :show-overflow-tooltip="true" />
            <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="selected-container">
          <el-table ref="selectedTable" :data="selectedFiles" 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 :disabled="row.type !== 1" v-model="row.duration" :min="1" :max="300"></el-input-number>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <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="splitDialog.title" v-model="splitDialog.visible" width="1200px" append-to-body>
      <div class="dialog-container">
        <!-- 左侧示意图 -->
        <div class="table-container">示意图</div>

        <!-- 右侧基础信息 -->
        <div class="selected-container">
          <el-form ref="itemFormRef" :model="form" :rules="rules" label-width="60px">
            <el-form-item label="名称" prop="itemName">
              <el-input v-model="form.itemName" placeholder="请输入分屏组名称" />
            </el-form-item>
            <el-row>
              <el-col :span="10">
                <el-form-item label="分辨率" prop="width">
                  <el-input-number
                    v-model="form.width"
                    controls-position="right"
                    placeholder="请输入宽度"
                    :min="0"
                    style="width: 180px"
                    maxlength="6"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="" prop="height" width="10px">
                  <el-input-number
                    v-model="form.height"
                    controls-position="right"
                    placeholder="请输入高度"
                    :min="0"
                    style="width: 180px"
                    maxlength="6"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="分屏" prop="splitScreen">
              <el-radio-group v-model="form.splitScreen">
                <el-radio v-for="dict in smsb_split_screen" :key="dict.value" :value="parseInt(dict.value)">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="坐标" prop="position">
              <el-row>
                <el-col :span="12">
                  <el-input-number
                    v-model="position1"
                    controls-position="right"
                    placeholder="请输入坐标1"
                    :min="0"
                    style="width: 180px"
                    maxlength="6"
                  />
                </el-col>
                <el-col :span="12">
                  <el-input-number
                    v-model="position2"
                    controls-position="right"
                    placeholder="请输入坐标2"
                    :min="0"
                    style="width: 180px; margin-left: 15px"
                    maxlength="6"
                    v-if="form.splitScreen !== 2"
                  />
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="宽高" prop="position" v-if="form.splitScreen === 4">
              <el-row>
                <el-col :span="12">
                  <el-input-number
                    v-model="positionW"
                    controls-position="right"
                    placeholder="请输入坐标1"
                    :min="0"
                    style="width: 180px"
                    maxlength="6"
                  />
                </el-col>
                <el-col :span="12">
                  <el-input-number
                    v-model="positionH"
                    controls-position="right"
                    placeholder="请输入坐标2"
                    :min="0"
                    style="width: 180px; margin-left: 15px"
                    maxlength="6"
                  />
                </el-col>
              </el-row>
            </el-form-item>
            <el-row>
              <el-col :span="12">
                <el-form-item label="跑马灯" prop="hasPmd">
                  <el-radio-group v-model="form.hasPmd">
                    <el-radio v-for="dict in smsb_yes_no" :key="dict.value" :value="parseInt(dict.value)">{{ dict.label }} </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="位置" prop="positionPmd">
                  <el-radio-group v-model="form.positionPmd">
                    <el-radio-button label="上方" value="1" />
                    <el-radio-button label="下方" value="2" />
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="内容" prop="contentPmd">
              <el-input v-model="form.contentPmd" type="textarea" placeholder="请输入跑马灯内容" />
            </el-form-item>
            <el-row>
              <el-col :span="12">
                <el-form-item label="天气" prop="hasWeather">
                  <el-radio-group v-model="form.hasWeather">
                    <el-radio v-for="dict in smsb_yes_no" :key="dict.value" :value="parseInt(dict.value)">{{ dict.label }} </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="时间" prop="hasTime">
                  <el-radio-group v-model="form.hasTime">
                    <el-radio v-for="dict in smsb_yes_no" :key="dict.value" :value="parseInt(dict.value)">{{ dict.label }} </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitSplit">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Item" lang="ts">
import { listItem, getItem, delItem, addItem, updateItem, itemStatistics } from '@/api/smsb/source/item';
import { ItemVO, ItemQuery, ItemForm } from '@/api/smsb/source/item_type';
import { MinioDataQuery, MinioDataVO } from '@/api/smsb/source/minioData_type';
import { listMinioData } from '@/api/smsb/source/minioData';
import Sortable from 'sortablejs';
import { nextTick } from 'vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { smsb_item_type, smsb_split_screen, smsb_source_type, smsb_yes_no } = toRefs<any>(
  proxy?.useDict('smsb_item_type', 'smsb_split_screen', 'smsb_source_type', 'smsb_yes_no')
);

const itemList = ref<ItemVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const fileTotal = ref(0);
const totalNum = ref(0);
const lbNum = ref(0);
const jmNum = ref(0);
const position1 = ref(0);
const position2 = ref(0);
const positionW = ref(0);
const positionH = ref(0);
const itemName = ref<string>('');
const queryFormRef = ref<ElFormInstance>();
const itemFormRef = ref<ElFormInstance>();
const minioDataList = ref<MinioDataVO[]>([]);
const dateRangeCreateTime = ref<[DateModelType, DateModelType]>(['', '']);

// 选中的文件
const selectedFiles = ref<{ id: number; name: string; duration: number; order: number; type: number }[]>([]);
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

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

const initFormData: ItemForm = {
  itemName: undefined,
  itemType: undefined,
  splitScreen: 2,
  selectedFiles: undefined,
  width: undefined,
  height: undefined,
  background: undefined,
  position: undefined,
  hasPmd: 0,
  positionPmd: '1',
  contentPmd: undefined,
  hasWeather: 0,
  hasTime: 0
};
const data = reactive<PageData<ItemForm, ItemQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    itemName: undefined,
    itemType: undefined,
    splitScreen: undefined,
    createUser: undefined,
    params: {}
  },
  rules: {}
});

const dialogData = reactive<DialogPageData<MinioDataQuery>>({
  dialogQueryParams: {
    pageNum: 1,
    pageSize: 10,
    params: {}
  }
});

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

/** 查询节目管理列表 */
const getList = async () => {
  loading.value = true;
  // const res = await listItem(queryParams.value);
  const res = await listItem(proxy?.addDateRange(queryParams.value, dateRangeCreateTime.value, 'CreateTime'));
  itemList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};
/** 查询文件资源列表 */
const getFileList = async () => {
  const res = await listMinioData(dialogQueryParams.value);
  minioDataList.value = res.rows;
  minioDataList.value.forEach((data) => {
    data.size = parseFloat(data.size / 1024).toFixed(3) + 'MB';
  });
  fileTotal.value = res.total;
};

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

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

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

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

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

/** 多选框选中文件数据 */
const handleSelectionFile = (selection: MinioDataVO[]) => {
  selectedFiles.value = selection.map((item: any, index: number) => ({
    id: item.id,
    name: item.originalName,
    type: item.type,
    duration: item.type === 1 ? 10 : item.duration, // 默认播放时长 10s
    order: index + 1 // 默认排序号
  }));
};

// 重新编号排序
const updateOrder = () => {
  selectedFiles.value.forEach((item, index) => {
    item.order = index + 1;
  });
};

// 删除选中文件
const removeFile = (file: any) => {
  selectedFiles.value = selectedFiles.value.filter((f) => f.id !== file.id);
};

/** 新增轮播按钮操作 */
const handleAddL = () => {
  reset();
  dialog.visible = true;
  dialog.title = '新增轮播组';
  form.value.itemType = 1;
  getFileList();
};

/** 新增节目按钮操作 */
const handleAddJ = () => {
  reset();
  splitDialog.visible = true;
  splitDialog.title = '新增分屏组';
  form.value.itemType = 2;
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ItemVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getItem(_id);
  if (1 === res.data.itemType) {
    Object.assign(form.value, res.data);
    dialog.visible = true;
    dialog.title = '修改节目管理';
  } else {
    // 跳转页面进行数据关联
    proxy.$router.push('/source/split/edit/' + res.data.id);
  }
};

/** 提交按钮 */
const submitForm = async () => {
  buttonLoading.value = true;
  if (form.value.id) {
    await updateItem(form.value).finally(() => (buttonLoading.value = false));
  } else {
    if (form.value.itemType === 1) {
      form.value.selectedFiles = selectedFiles.value;
      form.value.itemName = itemName.value;
    }
    await addItem(form.value).finally(() => (buttonLoading.value = false));
  }
  proxy?.$modal.msgSuccess('操作成功');
  dialog.visible = false;
  await getList();
};

const submitSplit = async () => {
  // 根据分辨率判断横屏还是竖屏
  const isWidth = form.value.width > form.value.height;
  // 2分屏的坐标
  if (form.value.splitScreen === 2) {
    if (isWidth) {
      form.value.position = '(0,' + position1.value + '),(' + form.value.height + ',' + position1.value + ')';
    } else {
      form.value.position = '(0,' + position1.value + '),(' + form.value.width + ',' + position1.value + ')';
    }
  }
  // 3分屏的坐标
  if (form.value.splitScreen === 3) {
    if (isWidth) {
      const xy1 = '(0,' + position1.value + '),(' + form.value.height + ',' + position1.value + ')';
      const xy2 = '(0,' + position2.value + '),(' + form.value.height + ',' + position2.value + ')';
      form.value.position = xy1 + ',' + xy2;
    } else {
      const xy1 = '(0,' + position1.value + '),(' + form.value.width + ',' + position1.value + ')';
      const xy2 = '(0,' + position2.value + '),(' + form.value.width + ',' + position2.value + ')';
      form.value.position = xy1 + ',' + xy2;
    }
  }
  // 播放框
  if (form.value.splitScreen === 4) {
    const xy1 = '(' + (position1.value - positionW.value / 2) + ',' + (position2.value + positionH.value / 2) + ')';
    const xy2 = '(' + (position1.value + positionW.value / 2) + ',' + (position2.value + positionH.value / 2) + ')';
    const xy3 = '(' + (position1.value - positionW.value / 2) + ',' + (position2.value - positionH.value / 2) + ')';
    const xy4 = '(' + (position1.value + positionW.value / 2) + ',' + (position2.value - positionH.value / 2) + ')';
    form.value.position = xy1 + ',' + xy2 + ',' + xy3 + ',' + xy4;
  }
  const res = await addItem(form.value).finally(() => (buttonLoading.value = false));
  proxy?.$modal.msgSuccess('操作成功');
  splitDialog.visible = false;
  const itemId = res.data;
  // 跳转页面进行数据关联
  proxy.$router.push('/source/split/edit/' + itemId);
};
/** 删除按钮操作 */
const handleDelete = async (row?: ItemVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除节目管理编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delItem(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'source/item/export',
    {
      ...queryParams.value
    },
    `item_${new Date().getTime()}.xlsx`
  );
};

const getItemStatistics = async () => {
  const res = await itemStatistics();
  console.log(res.data);
  totalNum.value = res.data.totalNum;
  lbNum.value = res.data.lbNum;
  jmNum.value = res.data.jmNum;
};

onMounted(() => {
  getList();
  getItemStatistics();
  nextTick(() => {
    const tableEl = document.querySelector('.selected-container .el-table__body-wrapper tbody') as HTMLElement;
    Sortable.create(tableEl, {
      animation: 150,
      handle: '.order-number', // 允许拖拽
      onEnd(event) {
        const { oldIndex, newIndex } = event;
        const movedItem = selectedFiles.value.splice(oldIndex!, 1)[0];
        selectedFiles.value.splice(newIndex!, 0, movedItem);
        updateOrder(); // 拖拽后重新排序
      }
    });
  });
});
</script>
<style scoped>
.dialog-container {
  display: flex;
  gap: 20px;
}

.table-container {
  flex: 1;
}

.selected-container {
  flex: 1;
}

.interface-input {
  margin-bottom: 10px;
}

.order-number {
  cursor: grab;
  display: inline-block;
  width: 30px;
  text-align: center;
  font-weight: bold;
}
</style>
