<template>
  <div class="download-container">
    <div class="selection-section">
      <div class="selection-item">
        <label class="selection-label">项目选择：</label>
        <el-select v-model="selectedProjectGuid"
                   placeholder="请选择项目"
                   filterable
                   clearable
                   size="large"
                   style="width: 300px;"
                   @change="handleProjectChange">
          <el-option v-for="project in projectOptions"
                     :key="project.guid"
                     :label="project.hotel_name"
                     :value="project.guid" />
        </el-select>
      </div>

      <div class="selection-item">
        <label class="selection-label">房型选择：</label>
        <el-select v-model="selectedRoomTypeGuid"
                   placeholder="请选择房型"
                   filterable
                   clearable
                   size="large"
                   style="width: 300px;"
                   :disabled="!selectedProjectGuid"
                   @change="handleRoomTypeChange">
          <el-option v-for="roomType in roomTypeOptions"
                     :key="roomType.guid"
                     :label="roomType.room_name"
                     :value="roomType.guid" />
        </el-select>
      </div>
    </div>

    <div class="table-section">
      <el-table v-loading="loading"
                :data="panelListData"
                style="width: 100%; margin-top: 20px;"
                stripe
                border>
        <el-table-column prop="panel_list_name" label="面板组名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="gang_series" label="系列" min-width="120" />
        <!--<el-table-column prop="model_type" label="类型" min-width="120" />-->
        <!--<el-table-column prop="panel_count" label="面板数量" width="100" align="center" />-->
        <el-table-column prop="cdr_filename" label="CDR文件名" min-width="300" show-overflow-tooltip />
        <el-table-column prop="created_at" label="生成时间" min-width="160">
          <template #default="{ row }">
            {{ row.created_at.replace(/[T]/g, ' ') }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center">
          <template #default="{ row }">
            <el-button size="small"
                       type="primary"
                       icon="Download"
                       @click="downloadCDRFile(row)"
                       :disabled="!row.cdr_filename">
              下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="panelListData.length === 0 && !loading" class="no-data">
        暂无数据，请先选择项目和房型
      </div>
    </div>
  </div>
</template>

<script setup>
  import { ref, onMounted, watch, computed, inject } from 'vue';
  import { createAxiosInstance } from '../../axios.js'
  import { ElMessage, ElLoading } from 'element-plus'
  import { Download, Document } from '@element-plus/icons-vue'

  const cloudHttp = inject('cloudHttp')
  const localHttp = inject('localHttp')
  const config = inject('config')

  // 数据加载状态
  const loading = ref(false);
  // 项目选择
  const selectedProjectGuid = ref('');
  const projectOptions = ref([]);
  // 房型选择
  const selectedRoomTypeGuid = ref('');
  const allRoomTypes = ref([]);
  const roomTypeOptions = computed(() => {
    if (!selectedProjectGuid.value) {
      return [];
    }
    // 查找选中的项目
    const selectedProject = projectOptions.value.find(project => project.guid === selectedProjectGuid.value);
    if (!selectedProject || !selectedProject.room_data_json) {
      return [];
    }
    // 解析项目的room_data_json（可能是字符串或数组）
    const roomTypeGuids = typeof selectedProject.room_data_json === 'string'
      ? JSON.parse(selectedProject.room_data_json)
      : selectedProject.room_data_json;
    // 根据项目的room_data_json过滤房型
    return allRoomTypes.value.filter(roomType =>
      roomTypeGuids.includes(roomType.guid)
    );
  });
  // 面板组数据
  const panelListData = ref([]);

  /**
   * 获取数据
   */
  const fetchData = async (endpoint, query = {}) => {
    try {
      const rs = await localHttp.post(endpoint, JSON.stringify(query));
      return rs.data.isok && rs.data.response ? JSON.parse(rs.data.response) : [];
    } catch (error) {
      console.error(`获取${endpoint}数据失败:`, error);
      ElMessage.error(`获取数据失败: ${error.message}`);
      return [];
    }
  };

  /**
   * 获取所有项目
   */
  const loadProjects = async () => {
    loading.value = true;
    try {
      const projects = await fetchData('PanelSelection/WebProjectQuery');
      projectOptions.value = projects;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 获取所有房型
   */
  const loadRoomTypes = async () => {
    loading.value = true;
    try {
      const roomTypes = await fetchData('PanelSelection/WebRoomTypeQuery');
      allRoomTypes.value = roomTypes;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 获取面板组数据
   */
  const loadPanelList = async () => {
    if (!selectedProjectGuid.value || !selectedRoomTypeGuid.value) {
      panelListData.value = [];
      return;
    }

    loading.value = true;
    try {
      const panelLists = await fetchData('PanelSelection/WebPanelListQuery');
      // 查找选中的房型
      const selectedRoomType = allRoomTypes.value.find(roomType => roomType.guid === selectedRoomTypeGuid.value);
      if (!selectedRoomType || !selectedRoomType.panel_group_count) {
        panelListData.value = [];
        return;
      }
      // 解析房型的panel_group_count（可能是字符串或数组）
      const panelGuids = typeof selectedRoomType.panel_group_count === 'string'
        ? JSON.parse(selectedRoomType.panel_group_count)
        : selectedRoomType.panel_group_count;
      // 根据房型的panel_group_count过滤面板组
      panelListData.value = panelLists.filter(panel =>
        panelGuids.includes(panel.guid)
      );
    } finally {
      loading.value = false;
    }
  };

  /**
   * 项目选择变化
   */
  const handleProjectChange = () => {
    selectedRoomTypeGuid.value = '';
    panelListData.value = [];
    // 可以根据需要添加根据项目加载特定房型的逻辑
  };

  /**
   * 房型选择变化
   */
  const handleRoomTypeChange = () => {
    loadPanelList();
  };

  /**
   * 下载CDR文件
   */
  const downloadCDRFile = (row) => {
    if (!row.cdr_filename) {
      ElMessage.warning('该面板组尚未生成CDR文件');
      return;
    }

    try {
      // 构建文件URL
      const fileUrl = config.PicAds + row.cdr_filename;

      // 创建a标签并模拟点击下载
      const link = document.createElement('a');
      link.href = fileUrl;
      link.target = '_blank';

      // 从文件名中提取不带路径的文件名
      const fileName = row.cdr_filename.split('/').pop();
      link.download = fileName || 'panel.cdr';

      // 将a标签添加到页面，触发点击，然后移除
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      ElMessage.success('CDR文件下载已开始');
    } catch (error) {
      console.error('下载CDR文件失败:', error);
      ElMessage.error('下载CDR文件失败: ' + error.message);
    }
  };

  /**
   * 页面挂载时加载数据
   */
  onMounted(async () => {
    await Promise.all([
      loadProjects(),
      loadRoomTypes()
    ]);
  });
</script>

<style scoped>
  .download-container {
    padding: 20px;
    min-height: calc(100vh - 120px);
  }

  .selection-section {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;
    flex-wrap: wrap;
  }

  .selection-item {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .selection-label {
    font-weight: 600;
    font-size: 14px;
    min-width: 80px;
  }

  .table-section {
    background-color: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    min-height: 400px;
  }

  .no-data {
    text-align: center;
    padding: 60px 0;
    color: #909399;
    font-size: 14px;
  }
</style>
