<template>
  <div class="app-container">

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="视频名称" prop="videoName">
        <el-input
          v-model="queryParams.videoName"
          placeholder="请输入视频名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <el-input
          v-model="queryParams.category"
          placeholder="请输入分类"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="queryParams.remark"
          placeholder="请输入备注"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="可见公司" prop="companyId">
        <el-select
          v-model="queryParams.companyId"
          placeholder="请选择可见公司"
          clearable
          filterable
          style="width: 200px"
        >
          <el-option
            v-for="company in allCompanyOptions"
            :key="company.companyId"
            :label="company.companyName"
            :value="company.companyId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['live:liveVideo: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:liveVideo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="multiple"
          @click="handleBatchUpdateCategory"
        >批量修改分类</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="liveVideoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="videoId" />
      <el-table-column label="视频名称" align="center" prop="videoName" />
      <el-table-column label="分类" align="center" prop="category" />
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="视频地址" align="center" prop="videoUrl">
        <template slot-scope="scope">
          <video
            :src="scope.row.videoUrl"
            controls
            controlsList="nodownload"
            class="video-player"
            @contextmenu.prevent
          ></video>
        </template>
      </el-table-column>
      <el-table-column label="时长" align="center" prop="duration" :formatter="formatDuration"/>
      <el-table-column label="转码状态" align="center" prop="finishStatus">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.finishStatus == 1">转码成功</el-tag>
          <el-tag v-else-if="scope.row.finishStatus == 0">转码中</el-tag>
          <el-tag v-else>---</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateVideoInfo(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateCompanyIds(scope.row)"
          >修改公司范围</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"
    />

    <!-- 添加或修改直播视频对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <live-video-upload
          :type = "1"
          :isPrivate = "isPrivate"
          :fileKey.sync = "form.fileKey"
          :fileSize.sync = "form.fileSize"
          :videoUrl.sync="form.videoUrl"
          :fileName.sync="form.fileName"
          :line_1.sync="form.lineOne"
          :thumbnail.sync="form.thumbnail"
          :uploadType.sync="form.uploadType"
          :isTranscode.sync="form.isTranscode"
          :transcodeFileKey.sync="form.transcodeFileKey"
          @video-duration="handleVideoDuration"
          @change="handleVideoChange"
          ref="videoUpload"
          append-to-body
        />
        <el-form-item label="视频名称" prop="videoName">
          <el-input v-model="form.videoName" placeholder="请输入视频名称" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-input v-model="form.category" placeholder="请输入分类" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" placeholder="请输入排序号" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="公司列表" prop="companyIds">
          <div style="margin-bottom: 10px;">
            <el-button size="mini" type="text" @click="selectAllCompanies">全选</el-button>
            <el-button size="mini" type="text" @click="unselectAllCompanies">全不选</el-button>
            <el-button size="mini" type="text" @click="reverseSelectCompanies">反选</el-button>
            <span style="margin-left: 20px; color: #909399; font-size: 12px;">
              已选择 {{ form.companyIds ? form.companyIds.length : 0 }} 个公司
            </span>
          </div>
          <el-select
            v-model="form.companyIds"
            multiple
            filterable
            placeholder="请选择公司"
            style="width: 100%"
            collapse-tags
            :loading="companyOptionsLoading"
          >
            <el-option
              v-for="company in allCompanyOptions"
              :key="company.companyId"
              :label="company.companyName"
              :value="company.companyId"
            />
          </el-select>
        </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="修改视频信息" :visible.sync="editVideoInfoDialog" width="800px" append-to-body>
      <el-form ref="editVideoInfoForm" :model="editVideoInfoForm" label-width="120px">
        <el-form-item label="视频名称" prop="videoName">
          <el-input v-model="editVideoInfoForm.videoName" placeholder="请输入视频名称" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-input v-model="editVideoInfoForm.category" placeholder="请输入分类" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="editVideoInfoForm.sort" :min="0" placeholder="请输入排序号" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="editVideoInfoForm.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitEditVideoInfo">确 定</el-button>
        <el-button @click="cancelEditVideoInfo">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改公司范围对话框 -->
    <el-dialog title="修改公司范围" :visible.sync="editCompanyIdsDialog" width="800px" append-to-body>
      <el-form ref="editCompanyIdsForm" :model="editCompanyIdsForm" label-width="120px">
        <el-form-item label="视频名称">
          <el-input v-model="editCompanyIdsForm.videoName" :disabled="true" />
        </el-form-item>
        <el-form-item label="公司列表" prop="companyIds">
          <div style="margin-bottom: 10px;">
            <el-button size="mini" type="text" @click="selectAllCompaniesForEdit">全选</el-button>
            <el-button size="mini" type="text" @click="unselectAllCompaniesForEdit">全不选</el-button>
            <el-button size="mini" type="text" @click="reverseSelectCompaniesForEdit">反选</el-button>
            <span style="margin-left: 20px; color: #909399; font-size: 12px;">
              已选择 {{ editCompanyIdsForm.companyIds ? editCompanyIdsForm.companyIds.length : 0 }} 个公司
            </span>
          </div>
          <el-select
            v-model="editCompanyIdsForm.companyIds"
            multiple
            filterable
            placeholder="请选择公司"
            style="width: 100%"
            collapse-tags
            :loading="companyOptionsLoading"
          >
            <el-option
              v-for="company in allCompanyOptions"
              :key="company.companyId"
              :label="company.companyName"
              :value="company.companyId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitEditCompanyIds">确 定</el-button>
        <el-button @click="cancelEditCompanyIds">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 批量修改分类对话框 -->
    <el-dialog title="批量修改分类" :visible.sync="batchUpdateCategoryDialog" width="500px" append-to-body>
      <el-form ref="batchUpdateCategoryForm" :model="batchUpdateCategoryForm" label-width="100px">
        <el-form-item label="分类" prop="category">
          <el-input v-model="batchUpdateCategoryForm.category" placeholder="请输入分类" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBatchUpdateCategory">确 定</el-button>
        <el-button @click="cancelBatchUpdateCategory">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLiveVideo, getLiveVideo, delLiveVideo, addLiveVideo, updateLiveVideo, exportLiveVideo, batchUpdateCategory } from "@/api/live/liveVideo";
import { getCompanyList } from "@/api/company/company";
import LiveVideoUpload from "@/components/LiveVideoUpload/index.vue";

export default {
  name: "LiveVideo",
  components: { LiveVideoUpload },
  data() {
    return {
      //字典
      videoTypeOptions: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 直播视频表格数据
      liveVideoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        liveId: -1,
        videoUrl: null,
        videoType: -1,
        sort: null,
        videoName: null,
        remark: null,
        category: null,
        companyId: null,
      },
      // 表单参数
      form: {
        uploadType: 1,
        isTranscode:0,
        transcodeFileKey:null,
        companyIds: []
      },
      // 表单校验
      rules: {
      },
      isPrivate:null,
      // 是否显示修改视频信息对话框
      editVideoInfoDialog: false,
      // 修改视频信息表单
      editVideoInfoForm: {
        videoId: null,
        videoName: '',
        category: '',
        sort: null,
        remark: ''
      },
      // 是否显示修改公司范围对话框
      editCompanyIdsDialog: false,
      // 修改公司范围表单
      editCompanyIdsForm: {
        videoId: null,
        videoName: '',
        companyIds: []
      },
      // 是否显示批量修改分类对话框
      batchUpdateCategoryDialog: false,
      // 批量修改分类表单
      batchUpdateCategoryForm: {
        category: ''
      },
      // 所有公司选项（用于下拉选择）
      allCompanyOptions: [],
      // 公司选项加载状态
      companyOptionsLoading: false
    };
  },
  created() {
    this.getList();
    this.getAllCompanyOptions();
  },
  mounted() {
    this.getAllCompanyOptions();
  },
  methods: {
    handleVideoDuration(duration) {
      this.form.duration = duration;
    },
    handleVideoChange(videoUrl,lineOne){
      this.videoUrl = videoUrl;
      this.form.videoUrl = videoUrl;
      console.log(this.videoUrl)
    },
    // 操作日志类型字典翻译
    formatDuration(row, column) {
      if(row.duration == null) return "00:00"
      const h = Math.floor(row.duration / 3600);
      const m = Math.floor((row.duration % 3600) / 60);
      const s = Math.floor(row.duration % 60);

      // 补零处理
      const format = (num) => num.toString().padStart(2, '0');

      return h > 0
        ? `${h}:${format(m)}:${format(s)}`
        : `${format(m)}:${format(s)}`;
    },
    /** 查询直播视频列表 */
    getList() {
      this.loading = true;
      listLiveVideo(this.queryParams).then(response => {
        this.liveVideoList = response.rows;
        this.liveVideoList.forEach(item => {
          item.videoUrl = item.videoUrl.replace(".m3u8", ".mp4");
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    videoTypeFormatter(row, column) {
      return this.selectDictLabel(this.videoTypeOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        videoId: null,
        liveId: null,
        videoUrl: null,
        videoType: null,
        videoName: null,
        category: null,
        sort: null,
        createTime: null,
        createBy: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        uploadType: 1,
        isTranscode: 0,
        transcodeFileKey: null,
        companyIds: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        liveId: -1,
        videoUrl: null,
        videoType: -1,
        sort: null,
        videoName: null,
        remark: null,
        category: null,
        companyId: null,
      };
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.videoId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加直播视频";
      this.videoUrl = '';
      setTimeout(() => {
        this.$refs.videoUpload.reset();
      }, 500);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const videoId = row.videoId || this.ids
      getLiveVideo(videoId).then(response => {
        this.form = response.data;

        // 处理companyIds，可能是字符串或数组
        if (response.data.companyIds) {
          if (typeof response.data.companyIds === 'string') {
            this.form.companyIds = response.data.companyIds
              ? response.data.companyIds.split(',').map(Number)
              : [];
          } else if (Array.isArray(response.data.companyIds)) {
            this.form.companyIds = response.data.companyIds.map(Number);
          }
        } else {
          this.form.companyIds = [];
        }

        this.open = true;
        this.title = "修改直播视频";
      });
    },
    /** 获取所有公司选项 */
    getAllCompanyOptions() {
      this.companyOptionsLoading = true;
      getCompanyList().then(response => {
        if (response.code === 200 && response.data) {
          this.allCompanyOptions = response.data || [];
        } else {
          this.allCompanyOptions = [];
        }
        this.companyOptionsLoading = false;
      }).catch(() => {
        this.allCompanyOptions = [];
        this.companyOptionsLoading = false;
      });
    },
    /** 全选公司 */
    selectAllCompanies() {
      this.form.companyIds = this.allCompanyOptions.map(item => item.companyId);
    },
    /** 全不选公司 */
    unselectAllCompanies() {
      this.form.companyIds = [];
    },
    /** 反选公司 */
    reverseSelectCompanies() {
      const allIds = this.allCompanyOptions.map(item => item.companyId);
      const selectedIds = this.form.companyIds || [];
      this.form.companyIds = allIds.filter(id => !selectedIds.includes(id));
    },
    /** 全选公司（修改公司范围） */
    selectAllCompaniesForEdit() {
      this.editCompanyIdsForm.companyIds = this.allCompanyOptions.map(item => item.companyId);
    },
    /** 全不选公司（修改公司范围） */
    unselectAllCompaniesForEdit() {
      this.editCompanyIdsForm.companyIds = [];
    },
    /** 反选公司（修改公司范围） */
    reverseSelectCompaniesForEdit() {
      const allIds = this.allCompanyOptions.map(item => item.companyId);
      const selectedIds = this.editCompanyIdsForm.companyIds || [];
      this.editCompanyIdsForm.companyIds = allIds.filter(id => !selectedIds.includes(id));
    },
    /** 打开修改视频信息对话框 */
    handleUpdateVideoInfo(row) {
      const videoId = row.videoId;
      getLiveVideo(videoId).then(response => {
        if (response.code === 200) {
          this.editVideoInfoForm = {
            videoId: response.data.videoId,
            videoName: response.data.videoName || '',
            category: response.data.category || '',
            sort: response.data.sort || null,
            remark: response.data.remark || ''
          };
          this.editVideoInfoDialog = true;
        }
      }).catch(() => {
        this.msgError("获取数据失败");
      });
    },
    /** 取消修改视频信息 */
    cancelEditVideoInfo() {
      this.editVideoInfoDialog = false;
      this.editVideoInfoForm = {
        videoId: null,
        videoName: '',
        category: '',
        sort: null,
        remark: ''
      };
    },
    /** 提交修改视频信息 */
    submitEditVideoInfo() {
      const data = {
        videoId: this.editVideoInfoForm.videoId,
        videoName: this.editVideoInfoForm.videoName,
        category: this.editVideoInfoForm.category,
        sort: this.editVideoInfoForm.sort,
        remark: this.editVideoInfoForm.remark
      };

      updateLiveVideo(data).then(response => {
        if (response.code === 200) {
          this.msgSuccess("修改成功");
          this.editVideoInfoDialog = false;
          this.getList();
        } else {
          this.msgError(response.msg || "修改失败");
        }
      }).catch(() => {
        this.msgError("修改失败");
      });
    },
    /** 打开修改公司范围对话框 */
    handleUpdateCompanyIds(row) {
      const videoId = row.videoId;
      getLiveVideo(videoId).then(response => {
        if (response.code === 200) {
          this.editCompanyIdsForm = {
            videoId: response.data.videoId,
            videoName: response.data.videoName || '',
            companyIds: []
          };

          // 处理companyIds，可能是字符串或数组
          if (response.data.companyIds) {
            if (typeof response.data.companyIds === 'string') {
              this.editCompanyIdsForm.companyIds = response.data.companyIds
                ? response.data.companyIds.split(',').map(Number)
                : [];
            } else if (Array.isArray(response.data.companyIds)) {
              this.editCompanyIdsForm.companyIds = response.data.companyIds.map(Number);
            }
          }

          this.editCompanyIdsDialog = true;
        }
      }).catch(() => {
        this.msgError("获取数据失败");
      });
    },
    /** 取消修改公司范围 */
    cancelEditCompanyIds() {
      this.editCompanyIdsDialog = false;
      this.editCompanyIdsForm = {
        videoId: null,
        videoName: '',
        companyIds: []
      };
    },
    /** 提交修改公司范围 */
    submitEditCompanyIds() {
      const data = {
        videoId: this.editCompanyIdsForm.videoId,
        companyIds: Array.isArray(this.editCompanyIdsForm.companyIds)
          ? this.editCompanyIdsForm.companyIds
          : []
      };

      updateLiveVideo(data).then(response => {
        if (response.code === 200) {
          this.msgSuccess("修改成功");
          this.editCompanyIdsDialog = false;
          this.getList();
        } else {
          this.msgError(response.msg || "修改失败");
        }
      }).catch(() => {
        this.msgError("修改失败");
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.videoType = -1;
          this.form.liveId = -1;
          if (!this.form.videoName) {
            this.form.videoName = this.form.fileName;
          }
          if (!this.form.remark) {
            this.form.remark = this.form.fileName;
          }
          if(this.form.videoUrl == null || this.form.videoUrl == "") {
            this.msgError("请上传视频");
            return;
          }
          this.form.videoUrl = this.form.videoUrl.replace('.mp4', '.m3u8');

          // 确保companyIds是数组
          const submitData = {
            ...this.form,
            companyIds: Array.isArray(this.form.companyIds) ? this.form.companyIds : []
          };

          if (this.form.videoId != null) {
            // 修改
            updateLiveVideo(submitData).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.reset();
            });
          } else {
            // 新增
            addLiveVideo(submitData).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.reset();
            });
          }

        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const videoIds = row.videoId || this.ids;
      this.$confirm('是否确认删除直播视频编号为"' + videoIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delLiveVideo(videoIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有直播视频数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportLiveVideo(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    /** 批量修改分类 */
    handleBatchUpdateCategory() {
      if (this.ids.length === 0) {
        this.msgWarning("请选择要修改的视频");
        return;
      }
      this.batchUpdateCategoryForm.category = '';
      this.batchUpdateCategoryDialog = true;
    },
    /** 取消批量修改分类 */
    cancelBatchUpdateCategory() {
      this.batchUpdateCategoryDialog = false;
      this.batchUpdateCategoryForm.category = '';
    },
    /** 提交批量修改分类 */
    submitBatchUpdateCategory() {
      const data = {
        videoIds: this.ids,
        category: this.batchUpdateCategoryForm.category
      };

      batchUpdateCategory(data).then(response => {
        if (response.code === 200) {
          this.msgSuccess("批量修改成功");
          this.batchUpdateCategoryDialog = false;
          this.getList();
        } else {
          this.msgError(response.msg || "批量修改失败");
        }
      }).catch(() => {
        this.msgError("批量修改失败");
      });
    }
  }
};
</script>

<style scoped>
.video-player {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>
