<template>
  <el-dialog :title="title" :visible.sync="dialogFormVisible" width="500px" @close="close">
    <el-form ref="form" label-width="80px" :model="form" :rules="rules">
      <el-form-item label="支持项">
        <span style="font-weight: bold; color: #409eff">{{ targetName }}</span>
      </el-form-item>
      <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>

    <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 { vote } from '@/api/rating/pk'
  import { getThumbUrl } from '@/utils/blessing'

  export default {
    name: 'PkVoteEdit',
    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,
        targetName: '',
        form: {
          pkId: '',
          itemId: '',
          userId: '',
        },
        rules: {
          userId: [{ required: true, trigger: 'change', message: '请选择投票的机器人' }],
        },

        // 机器人下拉列表状态
        robotList: [],
        robotQuery: {
          appId: '6a0d7dbe4c5de50f2ba66475',
          pageNo: 1,
          pageSize: 20,
        },
        robotTotal: 0,
        fetchingRobots: false,
      }
    },
    methods: {
      getThumbUrl,
      showEdit(pkId, itemId, itemName) {
        this.dialogFormVisible = true
        this.targetName = itemName
        this.form = this.$options.data().form
        this.form.pkId = pkId
        this.form.itemId = itemId

        // 重置列表并加载第一页
        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()
      },
      save() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            this.saving = true
            try {
              const { msg } = await vote(this.form)
              this.$baseMessage(msg || '投票成功', 'success')
              this.close()
              this.$emit('fetch-data')
            } catch (error) {
              console.error(error)
            } finally {
              this.saving = false
            }
          } else {
            return false
          }
        })
      },
    },
  }
</script>
