<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="请选择评价机器人"
          :popper-append-to-body="false"
          style="width: 100%"
        >
          <el-option v-for="item in robotList" :key="item.id" :label="item.nickname" :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 label="评分" prop="scoreType">
        <el-radio-group v-model="form.scoreType">
          <el-radio :label="5">夯</el-radio>
          <el-radio :label="4">顶级</el-radio>
          <el-radio :label="3">人上人</el-radio>
          <el-radio :label="2">NPC</el-radio>
          <el-radio :label="1">拉</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button :loading="loading" type="primary" @click="save">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { getListBase as getRobotList } from '@/api/system/robot'
  import { score } from '@/api/rating/topicOperate'
  import { getThumbUrl } from '@/utils/blessing'

  export default {
    name: 'TopicItemRatingEdit',
    directives: {
      loadmore: {
        bind(el, binding) {
          // 在 bind 阶段由于使用了 :popper-append-to-body="false" 可以确保 DOM 存在于 el 内部
          // 但是下拉框容器渲染可能有延迟，我们可以通过 setTimeout 确保获取到 DOM
          setTimeout(() => {
            const SELECTWRAP_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')
            if (SELECTWRAP_DOM) {
              SELECTWRAP_DOM.addEventListener('scroll', function () {
                // 判断滚动到底部的条件，加一个小容差 2px 防止不同浏览器下的精度问题
                const condition = this.scrollHeight - this.scrollTop <= this.clientHeight + 2
                if (condition) {
                  binding.value()
                }
              })
            }
          }, 0)
        },
      },
    },
    data() {
      return {
        title: '评价项打分',
        dialogFormVisible: false,
        loading: false,
        form: {
          topicId: '',
          itemId: '',
          scoreType: '',
          userId: '',
        },
        rules: {
          userId: [{ required: true, trigger: 'change', message: '请选择评价机器人' }],
          scoreType: [{ required: true, trigger: 'change', message: '请选择评分' }],
        },
        robotList: [],
        robotQuery: {
          pageNo: 1,
          pageSize: 20,
          appId: '6a0d7dbe4c5de50f2ba66475',
        },
        robotTotal: 0,
        fetchingRobots: false,
      }
    },
    methods: {
      getThumbUrl,
      async showEdit(row, topicId) {
        this.title = `给 ${row.name} 打分`
        this.form = this.$options.data().form
        this.form.topicId = topicId
        this.form.itemId = row.id
        this.dialogFormVisible = true

        this.robotQuery.pageNo = 1
        this.robotList = []
        this.robotTotal = 0
        await this.fetchRobotList()
      },
      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.robotList = []
        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()
      },
      save() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            this.loading = true
            try {
              const { msg } = await score(this.form)
              this.$baseMessage(msg || '评分成功', 'success')
              this.close()
              this.$emit('fetch-data')
            } catch (error) {
              console.error(error)
            } finally {
              this.loading = false
            }
          } else {
            return false
          }
        })
      },
    },
  }
</script>
