<template>
  <!-- 主播库 -->
  <div class="anchor-library">
    <el-splitter>
      <el-splitter-panel :size="75">
        <div class="demo-panel">
          <!-- 主播列表 -->
          <div class="anchor-list" v-if="list.length > 0">
            <div class="anchor-card" v-for="(item, index) in list" :key="index">
              <div class="card-content">
                <div class="card-avatar">
                  <img :src="item.headerIcon" alt="" />
                </div>
                <div class="personal-info">
                  <div class="name">{{ item.anchorId }}</div>
                  <div class="info-row">
                    <div class="gender" :class="item.gender == 1 ? 'male' : 'female'">
                      {{ item.gender == 1 ? '男' : '女' }}
                    </div>
                    <div class="country">{{ item.country }}</div>
                  </div>
                </div>
                <div class="card-actions">
                  <div class="action-btn" @click="handleEdit(item)">
                    <img :src="iconEditor" alt="编辑" />
                  </div>
                  <div class="action-btn" @click="handleDelete(item)">
                    <img :src="iconDelete" alt="删除" />
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="empty-tip" v-else>您还没有主播，快去添加吧！</div>
        </div>
      </el-splitter-panel>

      <!-- 右侧添加主播表单 -->
      <el-splitter-panel :size="25" :resizable="false">
        <div class="form-panel">
          <div class="form-title">
            <img class="title-icon" :src="iconEmbellish" alt="" />
            <span>{{ isEditing ? '修改主播' : '添加我的主播' }}</span>
            <img class="title-icon" :src="iconEmbellish" alt="" />
          </div>

          <div class="form-content">
            <!-- 主播名称 -->
            <div class="form-row">
              <el-input v-model="formData.anchorName" placeholder="请输入主播名称" @blur="handleBlur" />
            </div>

            <!-- 国家 -->
            <div class="form-row">
              <el-select-v2
                v-model="formData.country"
                :options="countryOptions"
                placeholder="请选择国家"
                filterable
                style="width: 100%"
              />
            </div>

            <!-- 性别 -->
            <div class="form-row">
              <el-select-v2
                v-model="formData.gender"
                :options="genderOptions"
                placeholder="请选择性别"
                style="width: 100%"
              />
            </div>

            <!-- 按钮 -->
            <div class="confirm-btn" @click="handleSubmit">确认</div>
            <div class="reset-btn" @click="handleReset">重置</div>
            <div class="reset-btn" v-if="isEditing" @click="handleCancel">取消</div>
          </div>
        </div>
      </el-splitter-panel>
    </el-splitter>

    <!-- 删除确认弹窗 -->
    <el-dialog v-model="showDeleteDialog" title="提示" width="300" align-center>
      <span>确认删除此主播？</span>
      <template #footer>
        <el-button @click="showDeleteDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmDelete">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getAnchorList, addAnchor, delAnchor, editAnchor, getAnchorAvatar } from '@/api/pk-mini'
import { getMainUserData } from '@/utils/pk-mini/storage'
import { getCountryNamesArray } from '@/utils/pk-mini/countryUtil'
import { ElMessage, ElLoading } from 'element-plus'

// 导入本地图片
import iconEditor from '@/assets/pk-mini/Editor.png'
import iconDelete from '@/assets/pk-mini/Delete.png'
import iconEmbellish from '@/assets/pk-mini/embellish.png'

function getUserId(user) {
  return user?.id || user?.userId || user?.uid || null
}

const currentUser = ref({})
const list = ref([])

// 表单
const formData = ref({
  anchorName: '',
  country: null,
  gender: null,
  anchorIcon: ''
})
const isEditing = ref(false)
const editingId = ref(null)

// 弹窗
const showDeleteDialog = ref(false)
const deleteItem = ref(null)

// 选项
const countryOptions = ref([])
const genderOptions = [
  { value: 1, label: '男' },
  { value: 2, label: '女' }
]

// 加载主播列表
async function loadAnchorList() {
  const userId = getUserId(currentUser.value)
  if (!userId) return

  try {
    const res = await getAnchorList({ id: userId })
    list.value = res || []
  } catch (e) {
    console.error('加载主播库失败', e)
  }
}

// 主播名称失焦查询头像
async function handleBlur() {
  if (!formData.value.anchorName) return

  const loading = ElLoading.service({
    lock: true,
    text: '正在查询主播...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    const res = await getAnchorAvatar({ name: formData.value.anchorName })
    formData.value.anchorIcon = res
    ElMessage.success('查询成功')
  } catch (e) {
    console.error('查询失败', e)
  } finally {
    loading.close()
  }
}

// 提交
async function handleSubmit() {
  const userId = getUserId(currentUser.value)
  if (!userId) return

  if (!formData.value.anchorName) {
    ElMessage.error('请输入主播名称')
    return
  }
  if (!formData.value.gender) {
    ElMessage.error('请选择性别')
    return
  }
  if (!formData.value.country) {
    ElMessage.error('请选择国家')
    return
  }

  const data = {
    anchorId: formData.value.anchorName,
    headerIcon: formData.value.anchorIcon,
    gender: formData.value.gender,
    country: formData.value.country,
    createUserId: userId
  }

  try {
    if (isEditing.value) {
      await editAnchor({ ...data, id: editingId.value })
      ElMessage.success('修改成功')
    } else {
      await addAnchor(data)
      ElMessage.success('添加成功')
    }
    loadAnchorList()
    handleReset()
  } catch (e) {
    console.error('提交失败', e)
  }
}

// 重置
function handleReset() {
  formData.value = { anchorName: '', country: null, gender: null, anchorIcon: '' }
  isEditing.value = false
  editingId.value = null
}

// 取消
function handleCancel() {
  handleReset()
}

// 编辑
function handleEdit(item) {
  isEditing.value = true
  editingId.value = item.id
  formData.value = {
    anchorName: item.anchorId,
    country: item.country,
    gender: item.gender,
    anchorIcon: item.headerIcon?.split('/').pop() || ''
  }
}

// 删除
function handleDelete(item) {
  deleteItem.value = item
  showDeleteDialog.value = true
}

async function confirmDelete() {
  try {
    await delAnchor({ id: deleteItem.value.id })
    ElMessage.success('删除成功')
    showDeleteDialog.value = false
    loadAnchorList()
    handleReset()
  } catch (e) {
    console.error('删除失败', e)
  }
}

onMounted(() => {
  countryOptions.value = getCountryNamesArray()
  currentUser.value = getMainUserData() || {}
  const userId = getUserId(currentUser.value)
  if (userId) {
    loadAnchorList()
  }
})
</script>

<style scoped lang="less">
.anchor-library {
  width: 100%;
  height: 100%;
}

.demo-panel {
  width: 100%;
  height: 100%;
}

.anchor-list {
  width: 100%;
  height: 100%;
  overflow: auto;
  padding: 15px;
}

.anchor-card {
  margin-bottom: 15px;
}

.card-content {
  display: flex;
  align-items: center;
  padding: 20px;
  background: url('https://vv-1317974657.cos.ap-shanghai.myqcloud.com/util/PKbackground.png') no-repeat center/cover;
  border-radius: 12px;
  transition: all 0.3s;
}

.card-content:hover {
  box-shadow: 0 0 10px rgba(0,0,0,0.2);
  transform: scale(1.02);
}

.card-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 20px;
}

.card-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.personal-info {
  flex: 1;
}

.name {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.info-row {
  display: flex;
  gap: 15px;
}

.gender {
  padding: 2px 15px;
  border-radius: 20px;
  font-size: 14px;
  color: white;
}

.gender.male { background: #59d8db; }
.gender.female { background: #f3876f; }

.country {
  padding: 2px 15px;
  background: #fff;
  border-radius: 20px;
  font-size: 14px;
  color: #666;
}

.card-actions {
  display: flex;
  gap: 20px;
}

.action-btn {
  cursor: pointer;
  transition: all 0.3s;
}

.action-btn:hover { transform: scale(1.2); }

.action-btn img {
  width: 28px;
  height: 28px;
}

.empty-tip {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  color: #03aba8;
}

.form-panel {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  border-left: 1px solid #e0f0f0;
}

.form-title {
  display: flex;
  align-items: center;
  gap: 15px;
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 30px;
}

.title-icon {
  width: 40px;
  height: 28px;
}

.form-content {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.form-row {
  width: 80%;
  margin-bottom: 20px;
}

.confirm-btn {
  width: 80%;
  padding: 12px;
  background: linear-gradient(to top, #4fcacd, #5fdbde);
  color: white;
  border-radius: 25px;
  text-align: center;
  font-size: 18px;
  cursor: pointer;
  margin-top: 80px;
  transition: all 0.3s;
}

.confirm-btn:hover {
  box-shadow: 0 0 10px rgba(0,0,0,0.2);
  transform: scale(1.02);
}

.reset-btn {
  width: 80%;
  padding: 12px;
  background: linear-gradient(to top, #e4ffff, #ffffff);
  border: 1px solid #4fcacd;
  color: #03aba8;
  border-radius: 25px;
  text-align: center;
  font-size: 18px;
  cursor: pointer;
  margin-top: 20px;
  transition: all 0.3s;
}

.reset-btn:hover {
  box-shadow: 0 0 10px rgba(0,0,0,0.2);
  transform: scale(1.02);
}
</style>
