<template>
  <div class="app-container live-page">
        <div class="live-page__header">
      <h2 class="live-page__title">弹幕任务</h2>
    </div>

<div class="live-panel live-panel--table">
<el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary" plain icon="el-icon-refresh" size="mini" @click="handleReload" v-hasPermi="['live:task:add']"
        >刷新</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['live:task:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete()" v-hasPermi="['live:task:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning" plain icon="el-icon-download" size="mini" :loading="exportLoading" @click="handleExport" v-hasPermi="['live:task:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success" plain icon="el-icon-download" size="mini" :loading="exportLoading" @click="handleImport" v-hasPermi="['live:task:export']"
        >导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="taskList" @selection-change="handleSelectionChange" class="live-table">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="人物名称" align="center" prop="taskName" />
      <el-table-column label="弹幕内容" align="center" prop="content" />
      <el-table-column label="触发类型" align="center" prop="triggerType" :formatter="triggerTypeFormatter" />
      <el-table-column label="触发时间" align="center" prop="triggerValue" :formatter="triggerValueFormatter" />
      <!--      <el-table-column label="完成状态" align="center" prop="finishStatus" :formatter="finishStatusFormatter" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['live:task:edit']"
          >修改</el-button>
          <el-button
            size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['live:task:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"
    />
    <!-- 添加或修改直播间自动化任务配置对话框 -->
    </div>

<el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="直播间ID" prop="liveId" v-show="false">
          <el-input :disabled="liveAbled" v-model="form.liveId" placeholder="请输入直播间ID" />
        </el-form-item>
        <el-form-item label="人物名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入人物名称" />
        </el-form-item>
        <el-form-item label="弹幕内容" prop="content">
          <el-input v-model="form.content" placeholder="请输入弹幕内容" />
        </el-form-item>
        <el-form-item label="触发时间" prop="content">
          <el-time-picker
            default-value="2025-01-01 00:00:00"
            v-model="form.triggerValue"
            :picker-options="{
      selectableRange: '00:00:00 - 23:59:59'
    }"

            placeholder="任意时间点">
          </el-time-picker>
        </el-form-item>
        <!--        <el-form-item label="触发类型" prop="triggerType">-->
        <!--          <el-select v-model="form.triggerType" placeholder="请选择触发类型">-->
        <!--            <el-option label="请选择字典生成" value="" />-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="触发值" prop="triggerValue">-->
        <!--          <el-input v-model="form.triggerValue" placeholder="请输入触发值" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="任务内容">-->
        <!--          <editor v-model="form.content" :min-height="192"/>-->
        <!--        </el-form-item>-->
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '' " :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :on-error="handleFileError" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-link type="info" style="font-size:12px;float:right" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：表头需为「时间、昵称、台词」，时间格式 HH:mm:ss；仅支持 xls/xlsx</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTaskBarrage, getTask, delTask, addTask, updateTask, exportTaskBarrage,importTemplate } from "@/api/live/task";
import { getToken } from "@/utils/auth";

export default {
  name: "Barrage",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      liveAbled: false,
      // 直播间自动化任务配置表格数据
      taskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        liveId: null,
        taskName: null,
        taskType: null,
        triggerType: null,
        triggerValue: null,
        content: null,
        status: null,
        createdTime: null,
        updatedTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        liveId: [
          { required: true, message: "直播间ID不能为空", trigger: "blur" }
        ],
        taskName: [
          { required: true, message: "人物名称不能为空", trigger: "blur" }
        ],
        taskType: [
          { required: true, message: "任务类型：1-定时推送卡片商品 2-定时发送红包 ", trigger: "change" }
        ],
        content: [
          { required: true, message: "任务内容不能为空", trigger: "blur" }
        ],
        triggerType: [
          { required: true, message: "触发类型：相对直播开始时间不能为空", trigger: "change" }
        ],
        triggerValue: [
          { required: true, message: "触发值：绝对时间用yyyy-MM-dd HH:mm:ss，相对时间用分钟数不能为空", trigger: "blur" }
        ],
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/live/task/importData",
      },
      liveId: null,
      socket: null,
      isLoading: false, // 是否正在加载
      hasMore: true, // 是否还有更多数据
      listSeq: 0, // 列表请求序号，防止竞态回写旧数据
    };
  },
  watch: {
    // 监听路由的 query 参数变化
    '$route.query': {
      handler(newQuery) {
        if (this.$route.params.liveId) {
          this.liveId = this.$route.params.liveId;
        }else {
          this.liveId = this.$route.query.liveId;
        }
        if(this.liveId == null) {
          return;
        }
        this.liveAbled = true
        this.queryParams.liveId = this.liveId;
        this.upload.url = process.env.VUE_APP_BASE_API + "/live/task/importData?liveId=" + this.liveId;
        this.getList();
      },
      // 初始化时立即执行一次
      immediate: true
    }
  },
  created() {
    this.socket = (this.$store.state.liveWs[String(this.liveId)] || this.$store.state.liveWs[this.liveId])
  },
  methods: {
    triggerTypeFormatter(row, column, value){
      if (!value) return '--'; // 空值处理
      switch (value) {
        case 1:
          return "相对直播开始时间";
        case 2:
          return "相对时间";
        default:
          return "--";
      }
    },
    triggerValueFormatter(row, column, value) {
      if (!value) return '--'; // 空值处理

      // 创建日期对象（兼容时间戳和字符串）
      let date;
      if (typeof value === 'number') {
        // 处理时间戳（注意：如果是10位时间戳需要乘以1000）
        date = new Date(value.toString().length === 10 ? value * 1000 : value);
      } else if (typeof value === 'string') {
        // 处理字符串格式（尝试直接转换）
        date = new Date(value);
      } else {
        return '格式错误';
      }
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        return '无效时间';
      }
      // 格式化日期为 "yyyy-MM-dd HH:mm:ss"
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');

      return `${hours}:${minutes}:${seconds}`;
    },
    /** 查询直播间自动化任务配置列表 */
    getList() {
      if(this.liveId == null) {
        this.$message.error("页面错误，请联系管理员");
        return;
      }
      this.loading = true;
      const seq = ++this.listSeq;
      listTaskBarrage(this.queryParams).then(res => {
        if (seq !== this.listSeq) {
          return;
        }
        this.taskList = Array.isArray(res.rows) ? res.rows : [];
        this.total = res.total || 0;
        this.loading = false;
      }).catch(() => {
        if (seq === this.listSeq) {
          this.loading = false;
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        liveId: this.liveId,
        taskName: null,
        taskType: null,
        triggerType: null,
        triggerValue: null,
        content: null,
        status: 1,
        createdTime: null,
        updatedTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加直播间弹幕脚本";
    },
    handleReload() {
      this.getList()
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      this.form = row;
      this.open = true;
      this.title = "修改直播间弹幕脚本";
    },
    /** 提交按钮 */
    submitForm() {
      this.form.liveId = this.liveId;
      if(this.liveId == null) {
        this.msgError("请选择直播间");
        return;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.taskType = 3
          if (this.form.id != null) {
            updateTask(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTask(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      // 工具栏批量删除不要把 click Event 当成 row
      const isRowDelete = row && row.id != null && (typeof row.id === 'number' || typeof row.id === 'string');
      const ids = isRowDelete ? row.id : this.ids;
      const idList = Array.isArray(ids) ? ids.filter(id => id != null && id !== '') : (ids != null && ids !== '' ? [ids] : []);
      if (idList.length === 0) {
        this.$message.warning('请选择要删除的数据');
        return;
      }
      this.$confirm('是否确认删除直播间弹幕脚本配置编号为"' + idList.join(',') + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return delTask(idList.join(','));
      }).then(() => {
        this.msgSuccess("删除成功");
        // 先本地移除，避免列表接口竞态导致“删了还显示”
        const idSet = new Set(idList.map(id => String(id)));
        this.taskList = (this.taskList || []).filter(item => !idSet.has(String(item.id)));
        this.total = Math.max(0, (this.total || 0) - idList.length);
        this.ids = [];
        this.single = true;
        this.multiple = true;
        if (this.taskList.length === 0 && this.queryParams.pageNum > 1) {
          this.queryParams.pageNum = 1;
        }
        this.getList();
        try {
          if (this.socket && this.socket.send && isRowDelete) {
            this.socket.send(JSON.stringify({
              cmd: 'delAutoTask',
              data: row.absValue,
              liveId: this.liveId,
              userType: 1
            }));
          }
        } catch (e) {}
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有直播间弹幕脚本数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportTaskBarrage(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
    },
    handleImport() {
      this.upload.title = "弹幕脚本导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      if (response && response.code === 200) {
        this.msgSuccess(response.msg || "导入成功");
        this.getList();
      } else {
        this.msgError((response && response.msg) || "导入失败");
      }
    },
    handleFileError() {
      this.upload.isUploading = false;
      this.msgError("导入失败，请稍后重试");
    },
    // 提交上传文件
    submitFileForm() {
      if (!this.liveId) {
        this.$message.error("错误直播间，请联系管理员处理");
        return ;
      }
      this.upload.url = process.env.VUE_APP_BASE_API + "/live/task/importData?liveId=" + this.liveId;
      this.$refs.upload.submit();
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then((response) => {
        this.download(response.msg);
      });
    },
  }
};
</script>

<style scoped>
.loading-indicator {
  padding: 10px;
  text-align: center;
  color: #606266;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-indicator .el-icon-loading {
  margin-right: 5px;
  animation: rotate 1s linear infinite;
}

.no-more {
  padding: 10px;
  text-align: center;
  color: #909399;
  font-size: 12px;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>
