<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.type" placeholder="类型" clearable>
              <el-option value="1">评论</el-option>
              <el-option value="2">点赞</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="评论内容" prop="categoryName">
            <el-input v-model="queryParams.categoryName" placeholder="请输入视频名称" clearable @keyup.enter="handleQuery" />
          </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">
      <!-- <template #header>
        <el-row :gutter="10" class="mt30">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd()" v-hasPermi="['workflow:video:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template> -->
      <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="名称" prop="title" align="center" width="160" />
        <!-- <el-table-column label="文件类型" prop="type" align="center" width="160" />
        <el-table-column label="媒体类型" prop="category" align="center" width="160" /> -->
        <el-table-column label="评论数量" prop="commentCounts" align="center" width="100" />
        <el-table-column label="点赞数量" prop="likeCounts" align="center" width="100" />
        <el-table-column label="粉丝数量" prop="fansCounts" align="center" width="100" />
        <el-table-column label="封面图片" align="center" width="200">
          <template #default="{ row }">
            <img alt="封面图片" style="max-width: 50%; max-height: 50%" :src="row.coverUrl" />
          </template>
        </el-table-column>
        <el-table-column label="文件创建时间" align="center" prop="createTime" width="180" />
        <el-table-column label="文件更新时间" align="center" prop="updateTime" width="180" />
        <!-- <el-table-column label="文件过期时间" align="center" prop="expireTime" width="180" /> -->
        <el-table-column label="操作" fixed="right" 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">
        <el-pagination @current-change="handleCurrentChange" layout="total, prev, pager, next" :total="total"> </el-pagination>
      </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.mediaUrl" type="video/mp4" />
          您的浏览器不支持播放该视频。
        </video>

        <div class="video-info">
          <div @click="isstates = 1" :style="{ color: isstates == 1 ? 'red' : '' }">评论{{ object.commentCounts }}条</div>
          <div @click="isstates = 2" :style="{ color: isstates == 2 ? 'red' : '' }">点赞{{ object.likeCounts }}条</div>
          <div @click="isstates = 3" :style="{ color: isstates == 3 ? 'red' : '' }">粉丝{{ object.fansCounts }}条</div>
        </div>
        <!-- 评论列表 -->
        <div class="comment-list" v-if="isstates == 1">
          <div v-for="(item, index) in comments" :key="index" class="comment-item">
            <div class="comment-avatar">
              <el-avatar :src="item.userFace" size="40" />
            </div>
            <div class="comment-content">
              <div class="comment-header">
                <div class="comment-name">{{ item.userNickname }}</div>
                <div class="comment-time">{{ item.create_time }}</div>
              </div>
              <div class="comment-text">
                <div>{{ item.content }}</div>
                <div><el-button type="danger" width="60" @click="delshow(item.id)">删除</el-button></div>
              </div>
            </div>
          </div>
        </div>
        <!-- 点赞列表 -->
        <div class="comment-list" v-if="isstates == 2" :style="{ width: '100%', margin: '0 auto' }">
          <div v-for="(item, index) in likedUsers" :key="index" class="comment-item">
            <div class="comment-avatar">
              <el-avatar :src="item.face" size="40" />
            </div>
            <div class="comment-content">
              <div class="comment-header">
                <div class="comment-name">{{ item.nickname }}</div>
                <div class="comment-time">{{ item.created_time }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 粉丝列表 -->
      <div class="comment-list" v-if="isstates == 3">
        <div v-for="(item, index) in fansList" :key="index" class="comment-item">
          <div class="comment-avatar">
            <el-avatar :src="item.face" size="40" />
          </div>
          <div class="comment-content">
            <div class="comment-header">
              <div class="comment-name">{{ item.nickname }}</div>
              <div class="comment-time">{{ item.createdTime }}</div>
            </div>
            <div class="comment-text">
              <div>{{ item.friend ? '互相关注' : '粉丝' }}</div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button :loading="buttonLoading" type="primary" @click="submitForm">通 过</el-button> -->
          <!-- <el-button 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 { reactive, ref } from 'vue';
import { useRoute } from 'vue-router';
type CategoryOption = {
  categoryId: number;
  categoryName: string;
  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 total = ref<number>(0);
const isstates = ref<number>(1);
// 控制弹出框显示隐藏
const showRefuteDialog = ref(false);
// 存储反驳原因
const refuteReason = ref('');
const route = useRoute(); // 获取当前路由信息
const memberId = ref(route.query.memberId as string); // 获取 memberId 参数

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

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

const data = reactive<PageData<CategoryForm, CategoryQuery>>({
  form: { ...initFormData },
  queryParams: {
    categoryName: undefined,
    current: 1,
    size: 20,
    memberId: memberId.value
  },
  rules: {
    categoryId: [{ required: true, message: '流程分类ID不能为空', trigger: 'blur' }],
    parentId: [{ required: true, message: '请选择上级分类', trigger: 'change' }],
    categoryName: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
  }
});

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

/** 查询流程分类列表 */
const getList = async () => {
  loading.value = true;
  const res = await listCategory(queryParams.value);
  // const data = proxy?.handleTree<CategoryVO>(res.data, 'categoryId', 'parentId');
  if (res.status == 200) {
    categoryList.value = res.data.list;
    total.value = res.data.totalCount;
    loading.value = false;
  }
};

const handleCurrentChange = (val: number) => {
  console.log(`当前页: ${val}`);
  queryParams.value.pageNum = val;
  getList();
};
/** 查询流程分类下拉树结构 */
// 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 = () => {
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};
//点赞列表
const likedUsers = ref<likeVO[]>([]);
//粉丝列表
const fansList = ref<fansListVO[]>([]);
//评论列表
const comments = ref<CommentsVO[]>([]);
/** 查看详情按钮操作 */
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 res = await gerdetail(row.fileId);
  if (res.status == 200) {
    comments.value = res.data.comments;
    likedUsers.value = res.data.likedUsers;
    fansList.value = res.data.fansList;
  }
};
//删除详情评论
const delshow = (id: string) => {
  ElMessageBox.confirm('是否确认删除', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await deldetail(id);
    if (res.status == 200) {
      cancel();
      getList();
    }
  });
};
/** 修改按钮操作 */
const handleUpdate = async (row: CategoryVO) => {};

/** 展开/折叠操作 */
// const handleToggleExpandAll = () => {
//   isExpandAll.value = !isExpandAll.value;
//   toggleExpandAll(categoryList.value, isExpandAll.value);
// };

/** 展开/折叠操作 */
// const toggleExpandAll = (data: CategoryVO[], status: boolean) => {
//   data.forEach((item) => {
//     categoryTableRef.value?.toggleRowExpansion(item, status);
//     if (item.children && item.children.length > 0) toggleExpandAll(item.children, status);
//   });
// };

// /** 修改按钮操作 */
// const handleUpdate = async (row: CategoryVO) => {
//   await getTreeselect();
//   if (row != null) {
//     form.value.parentId = row.parentId;
//   }
//   const res = await getCategory(row.categoryId);
//   reset();
//   Object.assign(form.value, res.data);
//   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.status == 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.status == 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(() => {
  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>
