<template>
  <div class="text-table-selecter-container">
    <!-- Filter section -->
    <div class="filter-section">
      <el-form :inline="true" :model="condition" class="filter-form">
        <el-form-item label="关联应用">
          <el-select v-model="condition.appId" placeholder="关联应用" @change="fetchData" filterable clearable>
            <el-option
              v-for="item in selectApps"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="日期范围">
          <zx-date-picker end-date="today" interval-days="7" v-model="dateTime" @change="fetchData" clearable></zx-date-picker>
        </el-form-item>

        <el-form-item label="文案类型">
          <el-select 
            v-model="condition.type" 
            placeholder="文案类型" 
            @change="fetchData" 
            clearable
            :disabled="!!fixedType"
          >
            <el-option label="标题" value="1"></el-option>
            <el-option label="描述" value="2"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="分类">
          <app-category-selector v-model="condition.category" @change="fetchData" />
        </el-form-item>
        
        <el-form-item label="语言">
          <el-select v-model="condition.language" placeholder="语言" @change="fetchData" clearable>
            <el-option 
              v-for="option in languageOptions" 
              :key="option.value" 
              :label="option.label" 
              :value="option.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>

    <el-divider></el-divider>

    <!-- Table Header actions -->
    <div class="header-actions">
      <div class="selected-info" v-if="selectedRows.length > 0">
        已选择 <span class="selected-count">{{ selectedRows.length }}</span> 条文案
        <el-button size="mini" type="text" @click="clearSelection">清空选择</el-button>
      </div>
      <div class="header-right">
        <el-button icon="el-icon-refresh" @click="fetchData">刷新</el-button>
      </div>
    </div>

    <!-- Main table -->
    <el-table
      ref="multipleTable"
      :data="tableData"
      border
      style="width: 100%;"
      v-loading="loading"
      row-key="id"
      :row-class-name="rowClassName"
      @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="text" label="文案内容" min-width="350">
        <template slot-scope="scope">
          <div class="text-content">{{ scope.row.text || '无内容' }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="文案类型" width="120">
        <template slot-scope="scope">
          <el-tag :type="scope.row.type == 1 ? 'primary' : 'success'">
            {{ scope.row.type == 1 ? '标题' : '描述' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="language" label="语言" width="100">
        <template slot-scope="scope">
          <el-tag type="info" size="small">
            {{ getLanguageName(scope.row.language) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="datadate" label="创建时间" width="180"></el-table-column>
    </el-table>

    <!-- Pagination -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="total"
        layout="total, prev, pager, next, sizes">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import {
  getBusinText,
  getSelectApps
} from "@/api/cloud";
import AppCategorySelector from "@/components/Selectors/AppCategorySelector";
import { languageOptions } from "@/const/language";

export default {
  name: 'TextTableSelecter',
  components: {
    AppCategorySelector
  },
  props: {
    // 双向绑定的选中文案数组
    value: {
      type: Array,
      default: () => []
    },
    // 固定的文案类型，如果传入则不可更改
    type: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      // 语言选项
      languageOptions,
      // 表格数据
      tableData: [],
      loading: false,
      total: 0,
      currentPage: 1,
      pageSize: 20,
      
      // 筛选条件
      condition: {
        appId: "",
        type: "",
        startDate: "",
        endDate: "",
        category: "",
        language: ""
      },
      
      // 应用选择器数据
      selectApps: [],
      
      // 选中的行数据
      selectedRows: [],
      
      // 已选中的行ID映射，用于保存跨页选择
      selectedRowMap: {}
    };
  },
  computed: {
    dateTime: {
      get() {
        if (this.condition.startDate && this.condition.endDate) {
          return [this.condition.startDate, this.condition.endDate];
        } else {
          return [];
        }
      },
      set(v) {
        if (v && v.length === 2) {
          this.condition.startDate = v[0];
          this.condition.endDate = v[1];
        } else {
          this.condition.startDate = "";
          this.condition.endDate = "";
        }
      }
    },
    // 固定的文案类型
    fixedType() {
      return this.type || "";
    }
  },
  watch: {
    // 监听外部value变化，更新内部选中状态
    value: {
      handler(newVal) {
        console.log('Value changed:', newVal);




        
        // 更新选中的行ID映射
        this.selectedRowMap = {};
        if (Array.isArray(newVal)) {
          newVal.forEach(item => {
            if (item && item.id) {
              this.selectedRowMap[item.id] = item;
            }
          });
        }
        // 如果表格已加载，更新表格选中状态
        this.$nextTick(() => {
          this.updateTableSelection();
        });
        
        // 同步更新selectedRows
        this.selectedRows = Object.values(this.selectedRowMap);
      },
      immediate: true,
      deep: true
    },
    // 监听固定类型变化
    type: {
      handler(newVal) {
        if (newVal) {
          this.condition.type = newVal;
          this.fetchData();
        }
      },
      immediate: true
    }
  },
  created() {
    // 初始化默认条件
    if (this.type) {
      this.condition.type = this.type;
    }
    
    // 设置默认排序
    this.condition.sortField = 'datadate';
    this.condition.sortOrder = 'desc';
    
    console.log('初始化条件:', this.condition);
    
    // 先获取应用列表，然后获取文案数据
    this.fetchApps().then(() => {
      this.fetchData();
    });
    
    // 确保初始化时选中状态正确
    if (Array.isArray(this.value) && this.value.length > 0) {
      console.log('Initial value in created:', this.value);
      this.value.forEach(item => {
        if (item && item.id) {
          this.selectedRowMap[item.id] = item;
        }
      });
      this.selectedRows = Object.values(this.selectedRowMap);
    }
  },
  
  mounted() {
    // 确保表格渲染后选中状态正确
    this.$nextTick(() => {
      this.updateTableSelection();
      console.log('Table mounted, selection updated');
    });
  },
  methods: {
    // 获取应用列表
    async fetchApps() {
      try {
        const params = {
          platformId: 5,
          menuCode: "game.Overview,android",
        };
        console.log('获取应用列表参数:', params);
        const response = await getSelectApps(params);
        console.log("应用列表响应:", response);
        if (response.status === 200) {
          this.selectApps = response.result.data || [];
        }
      } catch (error) {
        console.error("获取应用列表失败:", error);
        this.$message.error("获取应用列表失败");
      }
    },

    // 获取文案列表
    async fetchData() {
      this.loading = true;
      try {
        // 构造请求参数
        const params = {
          page: this.currentPage,
          size: this.pageSize,
          appId: this.condition.appId || '',
          type: this.condition.type || '',
          startDate: this.condition.startDate || '',
          endDate: this.condition.endDate || '',
          category: this.condition.category || '',
          language: this.condition.language || '',
          sortField: this.condition.sortField || 'datadate',
          sortOrder: this.condition.sortOrder || 'desc'
        };
        
        // 移除空字符串参数，避免后端处理问题
        Object.keys(params).forEach(key => {
          if (params[key] === '') {
            delete params[key];
          }
        });
        
        console.log('文案列表请求参数:', params);
        
        const response = await getBusinText(params);
        console.log('API响应:', response);
        
        if (response && response.result) {
          console.log('响应结果结构:', response.result);
          
          // 尝试不同的数据解析路径
          if (response.result.data && response.result.data.content) {
            // 标准分页格式：data.content
            this.tableData = response.result.data.content;
            this.total = response.result.data.total || 0;
          } else if (response.result.data && Array.isArray(response.result.data)) {
            // 数组格式：data是数组
            this.tableData = response.result.data;
            this.total = response.result.data.length;
          } else if (response.result.data && response.result.data.value) {
            // value格式：data.value是数组
            this.tableData = response.result.data.value;
            this.total = response.result.data.total || response.result.count || this.tableData.length;
          } else if (Array.isArray(response.result)) {
            // 直接result是数组
            this.tableData = response.result;
            this.total = response.result.length;
          } else {
            console.error('无法识别响应数据结构', response.result);
            this.tableData = [];
            this.total = 0;
          }
          
          console.log('解析后的表格数据:', this.tableData);
          console.log('总数:', this.total);

          // 确保表格数据中每个项都有必要的属性
          this.tableData = this.tableData.map(item => {
            const processedItem = {...item};
            
            // 确保有language属性
            if (!processedItem.language) {
              processedItem.language = 'en';
            }
            
            // 确保type属性格式正确
            if (processedItem.type && typeof processedItem.type === 'string') {
              processedItem.type = parseInt(processedItem.type, 10) || 1;
            }
            
            // 确保文本内容存在
            if (!processedItem.text && processedItem.content) {
              processedItem.text = processedItem.content;
            }
            
            return processedItem;
          });

          // 更新表格选中状态
          this.$nextTick(() => {
            this.updateTableSelection();
          });
        } else {
          console.error('响应没有result字段', response);
          this.tableData = [];
          this.total = 0;
        }
      } catch (error) {
        console.error("获取文案列表失败:", error);
        this.$message.error("获取文案列表失败");
      } finally {
        this.loading = false;
      }
    },

    
    // 分页处理
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchData();
    },
    
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchData();
    },
    
    // 处理表格选择变化
    handleSelectionChange(rows) {
      console.log('Selection changed:', rows);
      
      // 更新当前页的选中状态到映射中
      rows.forEach(row => {
        // 确保每个选中的行对象都有language属性
        if (!row.language) {
          row.language = 'en'; // 默认为英语
        }
        this.selectedRowMap[row.id] = row;
      });
      
      // 当前页中未被选中的行，从映射中移除
      this.tableData.forEach(row => {
        if (!rows.some(selectedRow => selectedRow.id === row.id)) {
          delete this.selectedRowMap[row.id];
        }
      });
      
      // 更新选中的行数组
      this.selectedRows = Object.values(this.selectedRowMap);
      console.log('Updated selectedRows:', this.selectedRows);
      
      // 向父组件发送更新
      // this.$emit('input', this.selectedRows);
      this.$emit('change', this.selectedRows);
    },
    
    // 更新表格选中状态
    updateTableSelection() {
      if (!this.$refs.multipleTable) return;
      
      // 先清空所有选择
      this.$refs.multipleTable.clearSelection();
      
      // 根据selectedRowMap选中对应行
      this.$nextTick(() => {
        this.tableData.forEach(row => {
          if (this.selectedRowMap[row.id]) {
            this.$refs.multipleTable.toggleRowSelection(row, true);
          }
        });
      });
    },
    
    // 清空选择
    clearSelection() {
      this.selectedRowMap = {};
      this.selectedRows = [];
      if (this.$refs.multipleTable) {
        this.$refs.multipleTable.clearSelection();
      }
      this.$emit('input', []);
      this.$emit('change', []);
      console.log('Selection cleared');
    },
    
    // 行样式
    rowClassName({row, rowIndex}) {
      // 这个方法用于调试，在表格行上添加一个类名，使其可见
      return 'text-table-row';
    },
    
    // 根据语言代码获取语言名称
    getLanguageName(code) {
      const languageNames = {
        en: "英语",
        zh: "中文",
        ja: "日语",
        ko: "韩语",
        fr: "法语",
        de: "德语",
        es: "西班牙语",
        pt: "葡萄牙语",
        ru: "俄语",
        hi: "印地语"
      };
      return languageNames[code] || code;
    }
  }
};
</script>

<style scoped>
.text-table-selecter-container {
  padding: 10px;
}

.filter-section {
  margin-bottom: 10px;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.selected-info {
  display: flex;
  align-items: center;
}

.header-right {
  margin-left: auto;
}

.selected-count {
  color: #409EFF;
  font-weight: bold;
  margin: 0 5px;
}

.text-content {
  white-space: pre-wrap;
  word-break: break-all;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

/* 确保表格行可见 */
.text-table-row {
  background-color: #ffffff; /* 白色背景 */
}

/* 确保表格内容文本可见 */
.el-table {
  color: #333;
}

.el-table--border th, .el-table--border td {
  border: 1px solid #ebeef5;
}

/* 增强表格样式 */
.el-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}
</style>
