<template>
  <el-dialog :title="title" :visible.sync="dialogFormVisible" width="600px" @close="close">
    <el-form ref="form" label-width="100px" :model="form" :rules="rules">
      <el-form-item label="参与机器人" prop="userId">
        <el-select v-model="form.userId" v-loadmore="loadMoreRobots" filterable placeholder="请选择参与评论的机器人" style="width: 100%">
          <el-option v-for="item in robotList" :key="item.id" :label="item.nickname || item.id" :value="item.id">
            <div style="display: flex; align-items: center">
              <el-image
                v-if="item.avatar"
                :src="getThumbUrl(item.avatar)"
                style="width: 24px; height: 24px; border-radius: 50%; margin-right: 10px"
              />
              <span>{{ item.nickname || '未知用户' }}</span>
            </div>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item v-if="!isReply" label="PK赛" prop="pkId">
        <el-select v-model="form.pkId" v-loadmore="loadMorePks" filterable placeholder="请选择PK赛" style="width: 100%">
          <el-option v-for="item in pkList" :key="item.id" :label="getPkLabel(item)" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="评论内容" prop="content">
        <el-input v-model="form.content" maxlength="500" :placeholder="contentPlaceholder" :rows="4" show-word-limit type="textarea" />
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button :loading="saving" type="primary" @click="save">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { getListBase as getRobotList } from '@/api/system/robot'
  import { getList as getPkList, comment } from '@/api/rating/pk'
  import { getThumbUrl } from '@/utils/blessing'

  export default {
    name: 'PkCommentEdit',
    directives: {
      loadmore: {
        bind(el, binding) {
          setTimeout(() => {
            const SELECTWRAP_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')
            if (SELECTWRAP_DOM) {
              SELECTWRAP_DOM.addEventListener('scroll', function () {
                const condition = this.scrollHeight - this.scrollTop <= this.clientHeight + 2
                if (condition) {
                  binding.value()
                }
              })
            }
          }, 0)
        },
      },
    },
    data() {
      return {
        title: '立即评论',
        dialogFormVisible: false,
        saving: false,
        isReply: false,
        contentPlaceholder: '请输入您的评论文字',
        form: {
          userId: '',
          pkId: '',
          content: '',
          parentCommentId: '',
          replyToCommentId: '',
        },
        rules: {
          userId: [{ required: true, trigger: 'change', message: '请选择机器人' }],
          pkId: [{ required: true, trigger: 'change', message: '请选择PK赛' }],
          content: [{ required: true, trigger: 'blur', message: '请输入评论内容' }],
        },

        // 机器人列表
        robotList: [],
        robotQuery: { pageNo: 1, pageSize: 20, appId: '6a0d7dbe4c5de50f2ba66475' },
        robotTotal: 0,
        fetchingRobots: false,

        // PK列表
        pkList: [],
        pkQuery: { pageNo: 1, pageSize: 20 },
        pkTotal: 0,
        fetchingPks: false,
      }
    },
    methods: {
      getThumbUrl,
      getPkLabel(item) {
        if (!item) return ''
        const left = item.leftItem ? item.leftItem.name : '未知'
        const right = item.rightItem ? item.rightItem.name : '未知'
        return `[${item.topic ? item.topic.title : '未知主题'}] ${left} vs ${right}`
      },
      showEdit(replyToRow = null, parentCommentId = null) {
        this.dialogFormVisible = true
        this.form = this.$options.data().form

        if (replyToRow) {
          this.isReply = true
          this.title = '回复评论'
          this.contentPlaceholder = `回复 @${replyToRow.user ? replyToRow.user.nickname : '未知用户'}:`
          this.form.pkId = replyToRow.pkId
          this.form.parentCommentId = parentCommentId || replyToRow.id
          this.form.replyToCommentId = replyToRow.id
        } else {
          this.isReply = false
          this.title = '立即评论'
          this.contentPlaceholder = '请输入您的评论文字'
          this.pkList = []
          this.pkQuery.pageNo = 1
          this.pkTotal = 0
          this.fetchPkList()
        }

        this.robotList = []
        this.robotQuery.pageNo = 1
        this.robotTotal = 0
        this.fetchRobotList()
      },
      close() {
        this.$refs['form'].resetFields()
        this.dialogFormVisible = false
      },

      // -- 机器人列表加载 --
      async fetchRobotList() {
        if (this.fetchingRobots) return
        this.fetchingRobots = true
        try {
          const { data } = await getRobotList(this.robotQuery)
          this.robotList = this.robotList.concat(data.list || [])
          this.robotTotal = data.totalCount || 0
        } catch (error) {
          console.error(error)
        } finally {
          this.fetchingRobots = false
        }
      },
      loadMoreRobots() {
        if (this.robotList.length >= this.robotTotal || this.fetchingRobots) return
        this.robotQuery.pageNo += 1
        this.fetchRobotList()
      },

      // -- PK 列表加载 --
      async fetchPkList() {
        if (this.fetchingPks) return
        this.fetchingPks = true
        try {
          const { data } = await getPkList(this.pkQuery)
          this.pkList = this.pkList.concat(data.list || [])
          this.pkTotal = data.totalCount || 0
        } catch (error) {
          console.error(error)
        } finally {
          this.fetchingPks = false
        }
      },
      loadMorePks() {
        if (this.pkList.length >= this.pkTotal || this.fetchingPks) return
        this.pkQuery.pageNo += 1
        this.fetchPkList()
      },

      save() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            this.saving = true
            try {
              const { msg } = await comment(this.form)
              this.$baseMessage(msg || (this.isReply ? '回复成功' : '评论成功'), 'success')
              this.close()
              this.$emit('fetch-data')
            } catch (error) {
              console.error(error)
            } finally {
              this.saving = false
            }
          } else {
            return false
          }
        })
      },
    },
  }
</script>
