<script lang="ts" setup>
import { onMounted, ref } from 'vue';

import { Plus } from '@element-plus/icons-vue';
import {
  ElButton,
  ElIcon,
  ElInput,
  ElMessage,
  ElRate,
  ElUpload,
} from 'element-plus';

// @ts-ignore
import { addComment, querycomment } from '#/api/knowledge/comment';
// @ts-ignore
import AttachmentViewer from '#/components/AttachmentViewer.vue';
// @ts-ignore
import { getSingleImageUploadConfig } from '#/components/upload/config';

// @ts-ignore

const props = defineProps({
  taskId: {
    type: Number,
    default: 0,
  },
  taskDetail: {
    type: Object,
    default: () => {},
  },
});
// 模拟评论数据
const comments: any = ref([]);
// 评分
const rating = ref(0);
// 评价内容
const commentContent = ref('');
const uploadRef = ref(null) as any;
// 评论图片
const commentImages = ref<any[]>([]);
// 图片预览相关
// const previewVisible = ref(false);
// const previewImages = ref<string[]>([]);
// 上传图片成功
const handleUploadSuccess = (file: any) => {
  if (file.code === 200) {
    commentImages.value.push({
      fileName: file.data.fileName,
      url: file.data.url,
    });
  }
};
// 移除上传的图片
// const removeImage = (index: number) => {
//   commentImages.value = [];
//   uploadRef?.value?.clearFiles();
// };

// 提交评论
const submitComment = async () => {
  if (commentContent.value.trim() === '' || commentImages.value.length === 0) {
    ElMessage.warning('请输入评论内容或上传图片');
    return;
  }
  try {
    await addComment({
      targetId: Number(props.taskId),
      targetType: 'task',
      attachments: commentImages.value.map((item) => item.fileName).join(','),
      content: commentContent.value,
    });
    commentContent.value = '';
    commentImages.value = [];
    querycommentfn();
  } catch {
    ElMessage.error('评论提交失败');
  }
};

const commentsloading = ref(true);

const querycommentfn = async () => {
  commentsloading.value = true;
  try {
    const res = await querycomment({
      targetId: Number(props.taskId),
      targetType: 'task',
    });
    if (res.code === 200) {
      comments.value = res.data || [];
    }
  } catch {
    // console.log(error);
  } finally {
    commentsloading.value = false;
  }
};

// 当前选中的tab
const activeTab = ref('comment');

const replyOpen = ref({}) as any;
const toggleReply = (index: any) => {
  replyOpen.value[index] = !replyOpen.value[index];
};
const childContent = ref('');
const replayEvent = async (item: any, index: any) => {
  if (!childContent.value.trim()) {
    ElMessage.warning('请输入评论内容');
    return;
  }

  try {
    await addComment({
      targetId: Number(props.taskId),
      targetType: 'task',
      parentId: item.id,
      // attachments: commentImages.value.map((item) => item.fileName).join(','),
      content: childContent.value,
    });
    childContent.value = '';
    replyOpen.value[index] = !replyOpen.value[index];
    querycommentfn();
  } catch {
    ElMessage.error('评论提交失败');
  }
};
// 查阅统计数据
const consultStats = ref({
  readCount: props.taskDetail.viewerName?.split(',').length || 0,
  unreadCount: props.taskDetail.unreadUserName?.split(',').length || 0,
  readers: props.taskDetail.viewerName?.split(',') || [],
  unreaders: props.taskDetail.unreadUserName?.split(',') || [],
});

// 处理tab切换
const handleTabChange = (tab: string) => {
  activeTab.value = tab;
};

// 获取名字的最后两个字
const getLastTwoChars = (name: string) => {
  return name?.slice(-2);
};

onMounted(() => {
  querycommentfn();
});
</script>

<template>
  <div class="comment-container">
    <!-- 评价表单 -->
    <div class="comment-form">
      <div class="form-header">
        <div class="rating-section">
          <span class="rating-text">评价：</span>
          <ElRate
            v-model="rating"
            :texts="['1分', '2分', '3分', '4分', '5分']"
            show-text
          />
        </div>
      </div>
      <div class="form-content">
        <div class="input-section">
          <div class="rating-section">
            <span class="rating-text">评价：</span>
            <ElInput
              v-model="commentContent"
              type="textarea"
              :rows="3"
              placeholder="请对执行任务的情况进行点评，您的点评会帮助执行人更好的完善工作哦~"
              class="comment-input"
            />
          </div>
          <div class="rating-section">
            <span class="rating-text">照片：</span>

            <ElUpload
              ref="uploadRef"
              v-bind="getSingleImageUploadConfig()"
              :on-success="handleUploadSuccess"
            >
              <!-- <img
                v-if="commentImages.length > 0"
                :src="commentImages[0].url"
                class="avatar"
              /> -->
              <div class="flex h-full w-full items-center justify-center">
                <ElIcon class="el-upload__icon">
                  <Plus size="18" />
                </ElIcon>
              </div>
            </ElUpload>
          </div>
        </div>
      </div>
      <ElButton style="margin-top: 8px" @click="submitComment" type="primary">
        提交
      </ElButton>
    </div>
    <div>
      <div class="consult-container">
        <!-- Tabs切换 -->
        <ElTabs v-model="activeTab" @tab-change="handleTabChange" class="mb-4">
          <ElTabPane label="评论" name="comment" />
          <ElTabPane :label="`${consultStats.readCount}人已阅`" name="read" />
          <ElTabPane
            :label="`${consultStats.unreadCount}人未阅`"
            name="unread"
          />
        </ElTabs>

        <!-- 人员列表 -->
        <div v-if="activeTab === 'comment'" class="readers-list">
          <div
            v-for="(item, index) in comments"
            :key="index"
            class="comment_item"
          >
            <div class="reader-item mb-2 mr-2" style="flex-shrink: 0">
              {{ getLastTwoChars(item.username) }}
            </div>
            <div class="comment_content">
              <span style="font-size: 15px; font-weight: 900">{{
                item.username
              }}</span>
              <div>{{ item.content }}</div>
              <div>
                <AttachmentViewer :files="item.attachmentsUrl" />
              </div>
              <div
                style="
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                "
              >
                <span style="color: #a4aab2">{{ item.createTime }}</span>
                <span class="reply_btn" @click="toggleReply(index)">回复</span>
              </div>
              <div
                v-if="item.children && item.children.length > 0"
                style="
                  margin-left: 16px;
                  margin-top: 8px;
                  border-left: 2px solid #dcdfe6;
                  padding-left: 8px;
                "
              >
                <div v-for="value in item.children" :key="value.id">
                  <div>
                    <span>{{ value?.username }}：</span>
                    <span>{{ value?.content }}</span>
                  </div>
                </div>
              </div>
              <div
                style="margin-left: 16px; margin-top: 8px"
                v-if="replyOpen[index]"
              >
                <ElInput
                  v-model="childContent"
                  maxlength="200"
                  style="width: 240px"
                  placeholder="请输入内容"
                  show-word-limit
                  type="textarea"
                />
                <div style="margin-top: 8px">
                  <ElButton
                    type="primary"
                    size="small"
                    @click="replayEvent(item, index)"
                  >
                    提交
                  </ElButton>
                  <ElButton size="small" @click="toggleReply(index)">
                    收起
                  </ElButton>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div v-else-if="activeTab === 'read'" class="readers-list">
          <div
            v-for="(reader, index) in consultStats.readers"
            :key="index"
            class="reader-item mb-2 mr-2"
          >
            {{ getLastTwoChars(reader) }}
          </div>
        </div>

        <div v-else class="readers-list">
          <div
            v-for="(unreader, index) in consultStats.unreaders"
            :key="index"
            class="reader-item unread mb-2 mr-2"
          >
            {{ getLastTwoChars(unreader) }}
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 图片预览组件 -->
  <!-- <ElImageViewer
    v-if="previewVisible"
    :url-list="previewImages"
    @close="closePreview"
  /> -->
</template>

<style scoped lang="scss">
.comment-container {
  width: 100%;
  font-size: 14px;

  .comment-form {
    margin-bottom: 24px;
    padding: 16px 0;

    .form-header {
      margin-bottom: 12px;
    }

    .rating-section {
      display: flex;
      align-items: center;

      .rating-text {
        color: var(--text-color-secondary);
        font-size: 14px;
        margin-right: 8px;
        white-space: nowrap;
      }

      .rating-stars {
        margin-right: 0;
      }
    }

    .form-content {
      .input-section {
        width: 100%;

        .upload-section {
          margin-bottom: 12px;

          :deep(.el-upload--picture-card) {
            width: 60px;
            height: 60px;
          }

          :deep(.el-upload-list--picture-card .el-upload-list__item) {
            width: 60px;
            height: 60px;
          }
        }

        .comment-input {
          margin-bottom: 12px;

          :deep(.el-textarea__inner) {
            border-radius: 4px;
            resize: none;
          }
        }

        .form-footer {
          .footer-left {
            display: flex;
            align-items: center;

            .cc-select {
              width: 200px;
              margin-right: 12px;
            }

            .comment-btn {
              padding: 4px 12px;
            }
          }
        }
      }
    }
  }

  .comment-list {
    .comment-item {
      margin-bottom: 20px;
      padding: 0;
      background-color: transparent;
      border: none;
      font-size: 14px;

      .comment-header {
        margin-bottom: 8px;

        .username-section {
          display: flex;
          align-items: center;

          .username {
            font-weight: 500;
            color: var(--text-color-primary);
            margin-right: 8px;
          }

          .department {
            color: var(--text-color-secondary);
            font-size: 13px;
            margin-right: 16px;
          }

          .rating-section {
            display: flex;
            align-items: center;

            .rating-stars {
              margin-right: 8px;
            }

            .rating-level {
              color: #f7ba2a;
              font-size: 13px;
            }
          }
        }
      }

      .comment-content {
        color: var(--text-color-primary);
        line-height: 1.5;
        margin-bottom: 12px;
        padding-right: 20px;
      }

      .comment-images {
        display: flex;
        gap: 12px;
        margin-bottom: 12px;

        .comment-image {
          width: 60px;
          height: 60px;
          border-radius: 4px;
          object-fit: cover;
          cursor: pointer;
          transition: transform 0.2s;

          &:hover {
            transform: scale(1.05);
          }
        }
      }

      /* 评论时间样式 */
      .comment-time {
        font-size: 12px;
        color: #999999;
        margin-top: 8px;
      }

      /* 评论操作样式 */
      .comment-footer {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        margin-top: 4px;

        .comment-actions {
          display: flex;
          align-items: center;

          .reply-icon {
            margin-right: 4px;
            color: #409eff;
            font-size: 12px;
          }

          .reply-btn {
            color: #409eff;
            font-size: 12px;
            cursor: pointer;

            &:hover {
              text-decoration: underline;
            }
          }
        }
      }

      /* 回复表单样式 */
      .reply-form {
        margin-top: 12px;
        padding: 12px;
        background-color: var(--bg-color-light);
        border-radius: 4px;
        border: 1px solid var(--border-color);

        .reply-input {
          margin-bottom: 12px;

          :deep(.el-textarea__inner) {
            border-radius: 4px;
            resize: none;
          }
        }

        .reply-footer {
          display: flex;
          justify-content: flex-end;
          gap: 8px;

          :deep(.el-button) {
            padding: 4px 12px;
          }
        }
      }

      /* 回复列表样式 */
      .reply-list {
        margin-top: 12px;
        margin-left: 40px;

        .reply-item {
          margin-bottom: 12px;
          padding: 8px 12px;
          background-color: var(--bg-color-light);
          border-radius: 4px;
          border-left: 3px solid #409eff;

          .reply-header {
            margin-bottom: 4px;

            .reply-username {
              font-weight: 500;
              color: var(--text-color-primary);
              font-size: 13px;
              margin-right: 4px;
            }

            .reply-department {
              color: var(--text-color-secondary);
              font-size: 13px;
            }
          }

          .reply-content {
            color: var(--text-color-primary);
            font-size: 13px;
            line-height: 1.4;
            margin-bottom: 4px;
          }

          .reply-time {
            font-size: 12px;
            color: #999999;
            text-align: left;
          }
        }
      }
    }
  }
}

.comment_item {
  display: flex;
  // align-items: center;
  // justify-content: space-between;
  width: 100%;
  // padding: 8px 16px;
  border-radius: 4px;
  // background-color: #f5f7fa;
  margin-bottom: 8px;
  font-size: 12px;
  color: #606266;

  .comment_content {
    margin-top: 6px;
    display: flex;
    flex-direction: column;
    gap: 8px;
    .reply_btn {
      color: #409eff;
      cursor: pointer;
      &:hover {
        text-decoration: underline;
      }
    }
  }
}
.consult-container {
  width: 100%;
  padding: 16px 0;
  font-size: 14px;

  .readers-list {
    display: flex;
    flex-wrap: wrap;
  }

  .reader-item {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    border-radius: 50%;
    background-color: #409eff;
    color: white;
    font-size: 12px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      background-color: #66b1ff;
      transform: scale(1.1);
    }

    &.unread {
      background-color: #dcdfe6;
      color: #606266;

      &:hover {
        background-color: #e4e7ed;
      }
    }
  }
}
</style>
