<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="search">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item label="排序" prop="status">
            <el-select v-model="queryParams.column" placeholder="排序" clearable>
              <el-option label="审核状态" value="status">审核状态</el-option>
              <el-option label="评论" value="commentsCounts">评论</el-option>
              <el-option label="点赞" value="likeCounts">点赞</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="排序方式" prop="status">
            <el-select v-model="queryParams.asc" placeholder="排序方式" clearable>
              <el-option label="正序" value="true">正序</el-option>
              <el-option label="倒序" value="false">倒序</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="queryParams.mobile" placeholder="请输入手机号" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="时间" prop="publishTime">
            <el-date-picker
              v-model="dateRange"
              @change="timefun"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="审核状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择审核状态" clearable>
              <el-option v-for="item in feedbackstatus" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <el-table
        ref="categoryTableRef"
        v-loading="loading"
        :data="categoryList"
        row-key="categoryId"
        border
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <!-- <el-table-column label="视频id" prop="fileId" align="center" width="100" /> -->
        <el-table-column label="名称" prop="nickname" align="center" width="130" />
        <el-table-column label="手机号" prop="mobile" align="center" width="100" />
        <el-table-column label="审核状态" prop="status" align="center" width="100">
          <template #default="{ row }">
            {{ isfun(row.status) }}
          </template>
        </el-table-column>
        <el-table-column label="原因" prop="reason" align="center" width="100" />
        <el-table-column label="内容" prop="title" align="center" width="100" />
        <el-table-column label="宽" prop="width" align="center" width="100" />
        <el-table-column label="高" prop="height" align="center" width="100" />
        <el-table-column label="评论数量" prop="commentsCounts" align="center" width="100" />
        <el-table-column label="点赞数量" prop="likeCounts" align="center" width="100" />
        <el-table-column label="封面图片" align="center" width="200">
          <template #default="{ row }">
            <img alt="封面图片" style="max-width: 20%; max-height: 20%" :src="row.firstFrameImg" />
          </template>
        </el-table-column>
        <el-table-column label="时间" align="center" prop="createTime" width="180" />
        <el-table-column label="操作" fixed="right" width="180" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看" placement="top">
              <el-button link type="primary" @click="handleAdd(scope.row)" v-hasPermi="['workflow:video:add']">查看</el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" @click="handleDelete(scope.row)" v-hasPermi="['workflow:video:remove']">删除</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <pagination v-if="totalref > 0" :total="totalref" v-model:page="queryParams.current" v-model:limit="queryParams.size" @pagination="getList" />
      </div>
    </el-card>
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <div v-if="shouldShowVideo" class="video-container">
        <video controls width="80%">
          <source :src="object.url" type="video/mp4" />
          您的浏览器不支持播放该视频。
        </video>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="isfun1(object.status)" :loading="buttonLoading" type="primary" @click="submitForm">通 过</el-button>
          <el-button v-if="isfun1(object.status)" type="danger" @click="showRefuteDialog = true">反 驳</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="showRefuteDialog" title="输入反驳原因">
      <el-form>
        <el-form-item label="反驳原因">
          <el-input v-model="refuteReason" type="textarea" :rows="4"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showRefuteDialog = false">取消</el-button>
          <el-button type="primary" @click="submitRefute">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Category" lang="ts">
import { listCategory, updateaudit, updateaforbid, gerdetail, deldetail } from '@/api/workflow/category';
import { CategoryVO, CategoryQuery, CategoryForm, Formaget, CommentsVO, likeVO, fansListVO } from '@/api/contentCenter/types';
import { getDictionaryByKey } from '@/utils/dict';
import { log } from 'node:console';
type CategoryOption = {
  categoryId: number;
  children?: CategoryOption[];
};

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const categoryList = ref<CategoryVO[]>([]);
const object = ref<CategoryVO>();
const categoryOptions = ref<CategoryOption[]>([]);
const buttonLoading = ref(false);
const showSearch = ref(true);
const isExpandAll = ref(true);
const loading = ref(false);
const shouldShowVideo = ref(false);
const queryFormRef = ref<ElFormInstance>();
const categoryFormRef = ref<ElFormInstance>();
const categoryTableRef = ref<ElTableInstance>();
const totalref = ref<number>(0);
const isstates = ref<number>(1);
// 控制弹出框显示隐藏
const showRefuteDialog = ref(false);
// 存储反驳原因
const refuteReason = ref('');
//时间选择器
const dateRange = ref([]);
// 提交反驳原因的方法
const submitRefute = async () => {
  // 这里可以添加提交反驳原因的逻辑，例如调用 API
  console.log('提交的反驳原因:', refuteReason.value);
  const data: Formaget = { vlogId: object.value.fileId, status: 2, reason: refuteReason.value };
  const res = await updateaudit(data);
  if (res.code === 200) {
    ElMessage({
      message: '操作成功',
      type: 'success'
    });
    showRefuteDialog.value = false;
    cancel();
    refuteReason.value = '';
  }
};
const feedbackstatus = ref([]);

const getByKey = async () => {
  const orderStatustype = await getDictionaryByKey('cms_video_status');
  feedbackstatus.value = orderStatustype;
};
const isfun = (status: string) => {
  const sta = feedbackstatus.value.filter((item) => item.value == status)[0]?.label;
  return sta;
};
const isfun1 = (status: string) => {
  if (status == '0') {
    return true;
  }
  if (status == '2') {
    return true;
  }
  if (status == '3') {
    return true;
  } else {
    return false;
  }
};
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: CategoryForm = {
  categoryId: undefined,
  parentId: undefined,
  orderNum: 0,
  type: 1
};

const data = reactive<PageData<CategoryForm, CategoryQuery>>({
  form: { ...initFormData },
  queryParams: {
    current: 1,
    size: 10,
    mobile: undefined,
    startTime: undefined,
    endTime: undefined,
    status: undefined,
    asc: undefined,
    column: undefined
  },
  rules: {
    // categoryId: [{ required: true, message: '流程分类ID不能为空', trigger: 'blur' }],
    // parentId: [{ required: true, message: '请选择上级分类', trigger: 'change' }],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 获取视频列表 */
const getList = async () => {
  loading.value = true;
  const res = await listCategory(queryParams.value);
  // const {{}}
  // const data = proxy?.handleTree<CategoryVO>(res.data, 'categoryId', 'parentId');
  const { records, total } = (res.data || {}) as { records: any[]; total: number };
  if (res.code == 200) {
    categoryList.value = records;
    totalref.value = total;
    loading.value = false;
  }
};

const handleCurrentChange = (val: number) => {
  queryParams.value.current = val;
  getList();
};
const timefun = (val: any) => {
  queryParams.value.startTime = JSON.stringify(val[0]);
  queryParams.value.endTime = JSON.stringify(val[1]);
};
/** 查询流程分类下拉树结构 */
// const getTreeselect = async () => {
//   const res = await listCategory();
//   categoryOptions.value = [];
//   // 处理树形数据
//   const data = proxy?.handleTree<CategoryOption>(res.data, 'categoryId', 'parentId');
//   if (data) {
//     categoryOptions.value = data; // 将处理后的树形数据赋值
//   }
// };

// 取消按钮
const cancel = () => {
  reset();
  dialog.visible = false;
};

// 表单重置
const reset = () => {
  form.value = { ...initFormData };
  categoryFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.current = 1; // 查询时重置为第一页
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value.mobile = undefined;
  queryParams.value.startTime = undefined;
  queryParams.value.endTime = undefined;
  queryParams.value.status = undefined;
  queryParams.value.asc = undefined;
  queryParams.value.column = undefined;
  dateRange.value = [];
  handleQuery();
};
/** 查看详情按钮操作 */
const handleAdd = async (row?: CategoryVO) => {
  nextTick(() => {
    object.value = JSON.parse(JSON.stringify(row));
    shouldShowVideo.value = false;
    // 强制视频元素重新渲染
    nextTick(() => {
      shouldShowVideo.value = true;
      dialog.visible = true;
      dialog.title = '视频查看';
    });
  });
};

/** 提交按钮 */
const submitForm = () => {
  ElMessageBox.confirm('是否通过？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const data: Formaget = { vlogId: object.value.fileId, status: 1, reason: refuteReason.value };
      const res = await updateaudit(data);
      if (res.code == 200) {
        ElMessage({
          message: '操作成功',
          type: 'success'
        });
        dialog.visible = false;
        getList();
      } else {
        ElMessage({
          message: res.msg,
          type: 'error'
        });
      }
    })
    .catch(() => {
      // 用户点击取消
      console.log('用户取消操作');
    });
};

/** 删除按钮操作 */
const handleDelete = async (row: CategoryVO) => {
  ElMessageBox.confirm('是否确认删除', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await updateaforbid(row.fileId);
    if (res.code == 200) {
      ElMessage({
        message: '删除成功',
        type: 'success'
      });
      getList();
    } else {
      ElMessage({
        message: res.msg,
        type: 'error'
      });
    }
  });
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'contentManage/video/export',
    {
      ...queryParams.value
    },
    `video_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getByKey();
  getList();
});
</script>
<style scoped lang="scss">
.video-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.video-container .video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.video-info {
  width: 100%;
  display: flex;
  justify-content: space-around;
  margin-top: 10px;
  font-size: 20px;
  font-weight: bold;
  & > div {
    cursor: pointer;
  }
}
.comment-list {
  width: 100%;
}
.comment-item {
  display: flex;
  width: 100%;
  .comment-avatar {
    padding: 10px;
  }
  .comment-content {
    padding: 10px;
    width: 100%;
    .comment-header {
      width: 100%;
      display: flex;
      justify-content: space-between;
      .comment-name {
        color: rgb(145, 145, 145);
      }
    }

    .comment-text {
      display: flex;
      width: 100%;
      justify-content: space-between;
      .el-button {
        width: 50px;
        height: 20px;
      }
    }
  }
}
</style>
