<template>
  <div class="bg-white rounded-md p-4 rounded-6px">
    <div class="operateDiv flex justify-between">
      <div>
        <el-button type="primary" @click="linkTo">同步课堂管理</el-button>
        <el-button type="primary" @click="handleExport">批量下载</el-button>
        <el-button type="danger" @click="handleDelete()">删除</el-button>
      </div>
      <div class="flex items-center space-x-4">
        <el-input v-model="searchForm.keyword" placeholder="请输入搜索的关键词" size="small" :suffix-icon="Search" />
        <el-button type="primary" @click="initData">搜索</el-button>
      </div>
    </div>
    <el-divider />
    <el-table :data="tableData" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="ttv_id" label="#"></el-table-column>
      <el-table-column prop="tt_hdh" label="互动号" show-overflow-tooltip></el-table-column>
      <el-table-column prop="ttv_flv_file" label="录制视频源文件"></el-table-column>
      <el-table-column prop="ttv_datetime" label="录制时间"></el-table-column>
      <el-table-column prop="ttv_filesize" label="文件大小"></el-table-column>
      <el-table-column prop="ttv_zdymc" label="自定义名称"></el-table-column>
      <el-table-column prop="ttv_sfzh" label="是否转换"></el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button type="primary" text @click="handleEdit(row)">上传&编辑加工视频</el-button>
          <el-divider direction="vertical" />
          <el-popover placement="bottom" :width="160" trigger="click">
            <div class="text-center">
              <el-button type="text" @click="lookDetail(1, row.ttv_mp4_file)">观看原始视频</el-button>
              <el-button type="text" @click="lookDetail(2, row.ttv_flv_file, '原始FLV视频')">下载原始FLV视频</el-button>
              <el-button type="text" @click="lookDetail(2, row.ttv_mp4_file, '原始MP4视频')">下载原始MP4视频</el-button>
              <el-button type="text" @click="lookDetail(1, row.ttv_upload_file)">观看加工视频</el-button>
              <el-button type="text" @click="lookDetail(2, row.ttv_upload_file, '加工视频')">下载加工视频</el-button>
            </div>
            <template #reference>
              <el-button type="text">更多</el-button>
            </template>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <div class="flex justify-end my-10">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="limit" :page-sizes="[10, 20, 50, 100]" :pager-count="5" :small="true" layout="total,sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <el-dialog v-model="dialogVisible" title="编辑" width="500px" destroy-on-close :close-on-click-modal="false" @close="handleClose">
      <el-form ref="ruleFormRef" label-position="right" label-width="100px" :model="ruleForm">
        <el-form-item label="自定义名称:" prop="ttv_zdymc">
          <el-input v-model="ruleForm.ttv_zdymc" size="small"></el-input>
        </el-form-item>
        <el-form-item label="上传文件:" prop="ttv_upload_file">
          <file-upload-progress v-model:part="ruleForm.ttv_upload_file" :limit="1" class="w-520px" accept=".mp4">
            <template #default>
              <el-button type="primary" size="large">点击上传</el-button>
            </template>
          </file-upload-progress>
        </el-form-item>
      </el-form>
      <div class="mt-5 text-center">
        <el-button type="primary" plain @click="handleClose()">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import { getFullUrl } from "@/utils/helper";
import { Search } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
const router = useRouter();

const searchForm = ref({});

watch(() => searchForm.value, () => {
  initData();
}, { deep: true })

const total = ref(0)
const limit = ref(10)
const currentPage = ref(1);
const tableData = ref([]);
initData();
async function initData() {
  let obj = {
    page: currentPage.value,
    limit: limit.value,
  };
  let { code, data } = await request({ url: "/txwx/tbkt_video/index", data: Object.assign(obj, searchForm.value) });
  if (code == 1) {
    tableData.value = data.page_data;
    total.value = Number(data.total_rows);
  }
}

function handleSizeChange(val) {
  limit.value = val;
  currentPage.value = 1;
  initData();
}

function handleCurrentChange(val) {
  currentPage.value = val;
  initData();
}


const multiSelection = ref([]);
const handleSelectionChange = (val) => {
  multiSelection.value = val;
}

const linkTo = () => {
  router.back();
};


const handleDelete = (row) => {
  if (!row && multiSelection.value.length == 0) {
    ElMessage.error("请先选择数据！");
    return
  }
  ElMessageBox.confirm('确定要删除该数据吗？', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: "warning",
  })
    .then(async () => {
      let ttv_id;
      if (row) {
        ttv_id = row.ttv_id;
      } else {
        ttv_id = [];
        multiSelection.value.map(item => {
          ttv_id.push(item.ttv_id);
        })
      }
      let res = await request({ url: "/txwx/tbkt_video/delete", data: { ttv_id: ttv_id } });
      if (res.code == 1) {
        ElMessage.success("删除成功！");
        initData();
      }
    })
    .catch(() => { })
}


const handleExport = () => {
  let arr = [];
  multiSelection.value.map((item) => {
    arr.push(item.ttv_id);
  });
  let obj = {
    limit: "99999",
    ttv_id: arr.join(",")
  };
  download("/txwx/tbkt_video/index", obj);
}

const lookDetail = (type, file, name) => {
  if (!file) {
    ElMessage.error("暂无视频文件！");
    return
  }
  // type 1：查看；2：下载
  if (type == 1) {
    window.open(getFullUrl(file));
  } else if (type == 2) {
    const arr = file.split(".")
    const ext = arr[arr.length - 1];
    let blob = new Blob([getFullUrl(file)], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }); //type为所需要下载的文件格式，以xlsx文件为例
    let url = window.URL.createObjectURL(blob);
    let fileName = `${name}.${ext}`;
    if ("download" in document.createElement("a")) {
      let a = document.createElement("a");
      a.href = url;
      a.download = fileName;
      a.style.display = "none";
      document.body.appendChild(a);
      a.click();
      URL.revokeObjectURL(a.href);
      document.body.removeChild(a);
    } else {
      navigator.msSaveBlob(blob, fileName);
    }
  }
}


const dialogVisible = ref(false);
const ruleForm = ref({
  ttv_zdymc: "",
  ttv_upload_file: "",
});
const currentId = ref("");
const handleClose = () => {
  dialogVisible.value = false;
  currentId.value = "";
  for (let key in ruleForm.value) {
    ruleForm.value[key] = "";
  }
}

const handleEdit = async (row) => {
  dialogVisible.value = true;
  currentId.value = row.ttv_id;
  let { code, data } = await request({ url: "/txwx/tbkt_video/detail", data: { ttv_id: row.ttv_id } });
  if (code == 1) {
    for (let key in ruleForm.value) {
      ruleForm.value[key] = data.one_info[key];
    }
  }
}

const submit = async () => {
  let obj = {
    ttv_id: currentId.value,
    txwx_tbkt_video: ruleForm.value
  }
  let { code } = await request({ url: "/txwx/tbkt_video/edit", data: obj });
  if (code == 1) {
    ElMessage.success("保存成功！");
    initData();
    handleClose();
  }
}

</script>

<style lang="scss" scoped>
@use "~/styles/table.scss";
@use "~/styles/pagination.scss";
</style>