<template>
  <div class="copywriting-library-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>
            <el-option label="标题" value="1"></el-option>
            <el-option label="描述" value="2"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="语言">
          <el-select v-model="condition.language" placeholder="语言" @change="fetchData" clearable>
            <el-option label="英语" value="en"></el-option>
            <el-option label="中文" value="zh"></el-option>
            <el-option label="日语" value="ja"></el-option>
            <el-option label="韩语" value="ko"></el-option>
            <el-option label="法语" value="fr"></el-option>
            <el-option label="德语" value="de"></el-option>
            <el-option label="西班牙语" value="es"></el-option>
            <el-option label="葡萄牙语" value="pt"></el-option>
            <el-option label="俄语" value="ru"></el-option>
            <el-option label="印地语" value="hi"></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>
    </div>

    <el-divider></el-divider>

    <!-- Table Header actions -->
    <div class="header-actions">
      <el-button type="primary" @click="showAddDialog">新增文案</el-button>
      <div class="header-right">
        <el-button icon="el-icon-refresh" @click="fetchData">刷新</el-button>
      </div>
    </div>

    <!-- Main table -->
    <el-table
      :data="tableData"
      border
      style="width: 100%;"
      v-loading="loading">
      <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-column label="操作" align="center" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </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>

    <!-- Add/Edit Dialog -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <el-form-item label="文案类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择文案类型">
            <el-option label="标题" value="1"></el-option>
            <el-option label="描述" value="2"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="语言" prop="language">
          <el-select v-model="form.language" placeholder="请选择语言">
            <el-option label="英语" value="en"></el-option>
            <el-option label="中文" value="zh"></el-option>
            <el-option label="日语" value="ja"></el-option>
            <el-option label="韩语" value="ko"></el-option>
            <el-option label="法语" value="fr"></el-option>
            <el-option label="德语" value="de"></el-option>
            <el-option label="西班牙语" value="es"></el-option>
            <el-option label="葡萄牙语" value="pt"></el-option>
            <el-option label="俄语" value="ru"></el-option>
            <el-option label="印地语" value="hi"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="关联应用">
          <el-select v-model="form.appId" filterable placeholder="请选择关联应用">
            <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="分类">
          <app-category-selector v-model="form.category" />
        </el-form-item>

        <el-form-item label="文案内容" prop="text">
          <text-input-list 
            v-if="!form.id"
            v-model="form.text" 
            placeholder="请输入文案内容"
            :maxLength="form.type === '1' ? 30 : 90"
          ></text-input-list>

          <el-input
            v-if="form.id"
            type="textarea"
            :rows="4"
            v-model="form.text"
            placeholder="请输入文案内容"
            :maxlength="form.type === 1 ? 30 : 90"
            show-word-limit
          ></el-input>
        </el-form-item>

        
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getBusinText,
  getBusinTextDel,
  getBusinTextEdit,
  getBusinTextAdd,
  getSelectApps
} from "@/api/cloud";
import AppCategorySelector from "@/components/Selectors/AppCategorySelector";
import TextInputList from "@/views/createDelivery/childComponents/TextInputList.vue";

export default {
  name: 'CopywritingLibrary',
  components: {
    AppCategorySelector,
    TextInputList
  },
  data() {
    return {
      // 表格数据
      tableData: [],
      loading: false,
      total: 0,
      currentPage: 1,
      pageSize: 20,
      
      // 筛选条件
      condition: {
        appId: "",
        type: "1",
        startDate: "",
        endDate: "",
        category: "",
        language: ""
      },
      
      // 应用选择器数据
      selectApps: [],
      
      // 日期选择器配置
      pickerOptions2: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              const start = new Date();
              picker.$emit("pick", [start, start]);
            }
          },
          {
            text: "昨天",
            onClick(picker) {
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
              picker.$emit("pick", [start, start]);
            }
          },
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      
      // 弹窗相关
      dialogVisible: false,
      dialogTitle: "",
      form: {
        id: "",
        text: [],
        type: "1",
        appId: "",
        category: "",
        language: "en"
      },
      rules: {
        text: [
          { 
            required: true, 
            validator: (rule, value, callback) => {
              if (this.form.id) {
                // 编辑模式，检查文本是否为空
                if (!value || value === '') {
                  callback(new Error('请输入文案内容'));
                } else {
                  callback();
                }
              } else {
                // 新增模式，检查数组是否为空
                if (!value || value.length === 0) {
                  callback(new Error('请输入至少一条文案内容'));
                } else {
                  callback();
                }
              }
            }, 
            trigger: "blur" 
          }
        ],
        type: [
          { required: true, message: "请选择文案类型", trigger: "change" }
        ]
      }
    };
  },
  
  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 = "";
        }
      }
    }
  },
  
  created() {
    // 设置默认日期为最近7天
    const end = new Date();
    const start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
    this.condition.startDate = start;
    this.condition.endDate = end;
    
    this.fetchApps();
    this.fetchData();
  },
  
  methods: {
    // 获取应用列表
    async fetchApps() {
      try {
        const params = {
          platformId: 5,
          menuCode: "game.Overview,android",
        };
        const response = await getSelectApps(params);
        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 || ''
        };
        
        const response = await getBusinText(params);

        if (response && response.result) {
          this.tableData = response.result.data.content || [];
          this.total = response.result.data.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();
    },
    
    // 新增文案
    showAddDialog() {
      this.dialogTitle = "新增文案";
      this.form = {
        id: "",
        text: [],
        type: "1",
        appId: "",
        category: "",
        language: "en"
      };
      this.dialogVisible = true;
    },
    
    // 编辑文案
    handleEdit(row) {
      this.dialogTitle = "编辑文案";
      
      this.form = {
        id: row.id,
        text: row.text || "",
        type: row.type + "",
        appId: row.appId || "",
        category: row.category || "",
        language: row.language || "en"
      };
      this.dialogVisible = true;
    },
    
    // 删除文案
    handleDelete(row) {
      this.$confirm("确认删除该文案?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          try {
            const response = await getBusinTextDel({ id: row.id });
            if (response.status === 200) {
              this.$message.success("删除成功");
              this.fetchData();
            } else {
              this.$message.error("删除失败");
            }
          } catch (error) {
            console.error("删除文案失败:", error);
            this.$message.error("删除文案失败");
          }
        })
        .catch(() => {});
    },
    
    // 提交表单
    submitForm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          try {
            let response;
            if (this.form.id) {
              // 编辑
              response = await getBusinTextEdit({
                id: this.form.id,
                text: this.form.text,
                type: this.form.type,
                appId: this.form.appId,
                category: this.form.category,
                language: this.form.language
              });
            } else {
              // 新增
              response = await getBusinTextAdd({
                textList: this.form.text,
                type: this.form.type,
                appId: this.form.appId,
                category: this.form.category,
                language: this.form.language
              });
            }
            
            if (response && response.result) {
              this.$message.success(this.form.id ? "编辑成功" : "添加成功");
              this.dialogVisible = false;
              this.fetchData();
            } else {
              this.$message.error(this.form.id ? "编辑失败" : "添加失败");
            }
          } catch (error) {
            console.error(this.form.id ? "编辑文案失败:" : "添加文案失败:", error);
            this.$message.error(this.form.id ? "编辑失败" : "添加失败");
          }
        }
      });
    },

    getLanguageName(language) {
      const languageNames = {
        en: "英语",
        zh: "中文",
        ja: "日语",
        ko: "韩语",
        fr: "法语",
        de: "德语",
        es: "西班牙语",
        pt: "葡萄牙语",
        ru: "俄语",
        hi: "印地语"
      };
      return languageNames[language] || language;
    }
  }
};
</script>

<style scoped>
.copywriting-library-container {
  padding: 20px;
}

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

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

.text-content {
  word-break: break-all;
  line-height: 1.5;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
