<template>
  <div class="message-container">
    <a-spin size="large" :spinning="messageLoading">
      <!-- 留言输入区域 -->
      <div class="message-input-area">
        <div class="user-avatar">
          <a-avatar :style="avatarStyle(user.name)">
            {{ user.name.substr(0, 1) }}
          </a-avatar>
          <span class="user-name">{{ user.name }}</span>
        </div>
        <div class="input-wrapper">
          <a-textarea
            v-model="messageText"
            placeholder="写下你的留言..."
            class="text-input"
            :autoSize="{ minRows: 3, maxRows: 6 }"
          />
          <div class="action-area">
            <div></div> <!-- 占位，保持右对齐 -->
            <a-button
              type="primary"
              :loading="submitting"
              :disabled="messageText.trim() === ''"
              @click="onSubmit"
              class="submit-btn"
            >
              发送
            </a-button>
          </div>
        </div>
      </div>

      <!-- 留言列表分割线 -->
      <div class="message-divider" v-if="messageList.length">
        <span class="divider-text">全部留言</span>
      </div>

      <!-- 留言统计 -->
      <div class="message-stats" v-if="messageList.length">
        <span>共 {{ messageList.length }} 条留言</span>
      </div>

      <!-- 空状态 -->
      <a-empty v-if="!messageList.length" description="暂无留言，发表第一条留言吧" />

      <!-- 留言列表 -->
      <div class="comment-list" v-else>
        <div
          v-for="message in sortedMessages"
          :key="message.id"
          class="comment-item"
        >
          <!-- 留言主体 -->
          <div class="comment-main">
            <div class="comment-avatar">
              <a-avatar :style="commentAvatarStyle(message.f_created_by)">
                {{ message.f_created_by.substr(0, 1) }}
              </a-avatar>
            </div>
            <div class="comment-content">
              <div class="comment-author">
                <span class="author-name">{{ message.f_created_by }}</span>
                <span class="author-badge" v-if="isCurrentUser(message.f_created_by)">我</span>
              </div>
              <div class="comment-text">{{ message.f_content }}</div>
              <div class="comment-footer">
                <span class="comment-time">{{ format(message.f_create_date) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 加载更多 -->
      <div class="load-more" v-if="messageList.length > 5">
        <a-button type="link">查看更多留言</a-button>
      </div>
    </a-spin>
  </div>
</template>

<script>
import { formatDate } from '@vue2-client/utils/util'
import { mapState } from 'vuex'
import { postByServiceName } from '@vue2-client/services/api/restTools'
import { workFlowViewApi } from '@vue2-client/services/api/workFlow'

export default {
  name: 'LeaveMessage',
  props: {
    projectName: {
      type: String,
      required: true
    },
    workflowId: {
      type: String,
      required: true
    },
  },
  data () {
    return {
      messageList: [],
      submitting: false,
      summaryVisible: false,
      messageText: '',
      messageLoading: false,
      colorMap: {}
    }
  },
  mounted () {
    this.getMessage()
  },
  computed: {
    ...mapState('account', ['user']),
    // 对留言列表按创建时间倒序排序
    sortedMessages () {
      // 创建一个副本，避免直接修改原数组
      return [...this.messageList].sort((a, b) => {
        // 否则按ID倒序排序
        return b.id - a.id
      })
    }
  },
  methods: {
    format (date) {
      return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
    },
    onSubmit () {
      this.submitting = true
      this.submitMessage({
        f_created_by: this.user.name,
        f_content: this.messageText.trim()
      }).then(() => {
        this.submitting = false
        this.$message.success('留言成功')
        this.messageText = ''
        this.getMessage()
        this.$emit('refresh')
      }).catch(() => {
        this.submitting = false
        this.$message.error('留言失败，请重试')
      })
    },
    // 获取留言
    getMessage () {
      this.messageLoading = true
      postByServiceName(workFlowViewApi.getWorkFlowLeaveMessage, {
        workflowId: this.workflowId
      }).then(res => {
        this.messageList = res
        this.messageLoading = false
      })
    },
    // 提交留言
    submitMessage (data) {
      data.f_workflow_id = this.workflowId
      return postByServiceName('/entity/save/t_workflow_leave_message', data)
    },
    // 生成头像样式
    avatarStyle (name) {
      return {
        background: this.getAvatarColor(name),
        color: '#fff'
      }
    },
    // 生成评论头像样式
    commentAvatarStyle (name) {
      return {
        background: this.getAvatarColor(name),
        color: '#fff',
        fontSize: '16px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center'
      }
    },
    // 根据用户名生成固定的头像颜色
    getAvatarColor (name) {
      if (!name) return '#1890ff'

      // 如果已经生成过这个用户的颜色，直接返回
      if (this.colorMap[name]) {
        return this.colorMap[name]
      }

      // 预定义一组好看的颜色
      const colors = [
        '#1890ff', '#52c41a', '#722ed1', '#fa8c16', '#eb2f96',
        '#13c2c2', '#faad14', '#a0d911', '#fa541c', '#2f54eb'
      ]

      // 根据名字计算一个固定的索引
      let hash = 0
      for (let i = 0; i < name.length; i++) {
        hash = name.charCodeAt(i) + ((hash << 5) - hash)
      }

      const index = Math.abs(hash) % colors.length
      this.colorMap[name] = colors[index]
      return colors[index]
    },
    // 判断是否是当前用户
    isCurrentUser (name) {
      return name === this.user.name
    }
  }
}
</script>

<style lang="less" scoped>
.message-container {
  padding: 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}

// 留言统计
.message-stats {
  margin-bottom: 20px;
  color: #8c8c8c;
  font-size: 14px;
}

// 留言输入区域
.message-input-area {
  margin-bottom: 32px;
  background: #f9fafb;
  border-radius: 8px;
  padding: 16px;

  .user-avatar {
    display: flex;
    align-items: center;
    margin-bottom: 12px;

    .ant-avatar {
      margin-right: 8px;
    }

    .user-name {
      font-size: 14px;
      font-weight: 500;
      color: #262626;
    }
  }

  .input-wrapper {
    width: 100%;
  }

  .text-input {
    margin-bottom: 12px;
    border-radius: 4px;
    resize: none;
    background: #fff;

    /deep/ .ant-input {
      padding: 12px 16px;
      font-size: 14px;
    }
  }

  .action-area {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .submit-btn {
    padding: 0 16px;
    border-radius: 4px;
    font-size: 14px;
  }
}

// 分割线
.message-divider {
  position: relative;
  text-align: center;
  margin: 24px 0;

  &::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 0;
    width: 100%;
    height: 1px;
    background: #f0f0f0;
    z-index: 0;
  }

  .divider-text {
    position: relative;
    display: inline-block;
    padding: 0 16px;
    background: #fff;
    font-size: 14px;
    color: #8c8c8c;
    z-index: 1;
  }
}

// 留言列表
.comment-list {
  .comment-item {
    padding: 16px 0;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }
  }

  .comment-main {
    display: flex;

    .comment-avatar {
      margin-right: 16px;
      flex-shrink: 0;
    }

    .comment-content {
      flex: 1;
      overflow: hidden;

      .comment-author {
        margin-bottom: 8px;
        display: flex;
        align-items: center;

        .author-name {
          font-size: 15px;
          font-weight: 600;
          color: #262626;
        }

        .author-badge {
          margin-left: 8px;
          background: #e6f7ff;
          color: #1890ff;
          padding: 0 6px;
          border-radius: 10px;
          font-size: 12px;
          line-height: 18px;
        }
      }

      .comment-text {
        font-size: 15px;
        line-height: 1.6;
        color: #333;
        margin-bottom: 8px;
        word-break: break-word;
      }

      .comment-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 4px;

        .comment-time {
          font-size: 13px;
          color: #8c8c8c;
        }
      }
    }
  }
}

// 加载更多
.load-more {
  text-align: center;
  margin-top: 16px;
}

// 空状态
/deep/ .ant-empty {
  margin: 32px 0;

  .ant-empty-description {
    color: #8c8c8c;
  }
}
</style>
