<template>
  <div>
    <!-- 搜索区域 -->
    <div class="gva-search-box">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="讲师昵称">
          <el-input v-model="searchForm.name" placeholder="请输入讲师昵称" clearable />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchData">查询</el-button>
          <el-button @click="resetData">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 统计信息 -->
    <div class="stats-box">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-value">{{ stats.total }}</div>
            <div class="stat-label">总讲师数</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item active">
            <div class="stat-value">{{ stats.active }}</div>
            <div class="stat-label">启用讲师</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item vip">
            <div class="stat-value">{{ stats.vip }}</div>
            <div class="stat-label">VIP讲师</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item disabled">
            <div class="stat-value">{{ stats.disabled }}</div>
            <div class="stat-label">禁用讲师</div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 表格区域 -->
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" @click="handleAdd">新增讲师</el-button>
      </div>
      
      <el-table
        :data="tableData"
        v-loading="tableLoading"
        style="width: 100%"
        class="gva-table"
        stripe
      >
        <el-table-column prop="ID" label="ID" width="80" />
        <el-table-column prop="avatar" label="头像" width="100">
          <template #default="{ row }">
            <el-avatar
              :size="50"
              :src="row.avatar"
              fit="cover"
            >
              <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="nick_name" label="讲师昵称" min-width="120" />
        <el-table-column prop="phone" label="手机号" width="130">
          <template #default="{ row }">
            {{ row.phone || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="balance" label="账户余额" width="120">
          <template #default="{ row }">
            <span style="color: #67c23a; font-weight: bold;">¥{{ row.balance }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="weight" label="权重" width="80">
          <template #default="{ row }">
            <el-tag :type="getWeightTagType(row.weight)">
              {{ row.weight }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="expect_rate" label="分成比例" width="100">
          <template #default="{ row }">
            <span style="color: #409eff; font-weight: bold;">{{ row.expect_rate }}%</span>
          </template>
        </el-table-column>
        <el-table-column prop="is_vip" label="VIP状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.is_vip ? 'warning' : 'info'">
              {{ row.is_vip ? 'VIP讲师' : '普通讲师' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch 
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              :loading="row.loading"
              :before-change="() => statusChangeBefore(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="CreatedAt" label="注册时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.CreatedAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="text" @click="handleDetail(row)">详情</el-button>
            <el-button type="text" @click="handleEditWeight(row)">设置权重</el-button>
            <el-button type="text" @click="handleEditRate(row)">设置分成</el-button>
            <el-button type="text" @click="handleBalance(row)">修改余额</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="gva-pagination"
      />
    </div>

    <!-- 讲师详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="讲师详情"
      width="600px"
      :before-close="handleDetailClose"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="讲师头像">
          <el-avatar
            :size="80"
            :src="currentTeacher.avatar"
            fit="cover"
          />
        </el-descriptions-item>
        <el-descriptions-item label="讲师ID">{{ currentTeacher.ID }}</el-descriptions-item>
        <el-descriptions-item label="讲师昵称">{{ currentTeacher.nick_name }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ currentTeacher.phone || '-' }}</el-descriptions-item>
        <el-descriptions-item label="账户余额">
          <span style="color: #67c23a; font-weight: bold;">¥{{ currentTeacher.balance }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="权重">{{ currentTeacher.weight }}</el-descriptions-item>
        <el-descriptions-item label="分成比例">{{ currentTeacher.expect_rate }}%</el-descriptions-item>
        <el-descriptions-item label="VIP状态">
          <el-tag :type="currentTeacher.is_vip ? 'warning' : 'info'">
            {{ currentTeacher.is_vip ? 'VIP讲师' : '普通讲师' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentTeacher.status ? 'success' : 'danger'">
            {{ currentTeacher.status ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="注册时间">{{ formatDate(currentTeacher.CreatedAt) }}</el-descriptions-item>
        <el-descriptions-item label="个人简介" :span="2">
          {{ currentTeacher.des || '暂无简介' }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 设置权重弹窗 -->
    <el-dialog
      v-model="weightDialogVisible"
      title="设置讲师权重"
      width="400px"
      :before-close="handleWeightClose"
    >
      <el-form
        ref="weightFormRef"
        :model="weightForm"
        :rules="weightRules"
        label-width="100px"
      >
        <el-form-item label="讲师昵称">
          <span>{{ currentTeacher.nick_name }}</span>
        </el-form-item>
        <el-form-item label="当前权重">
          <span>{{ currentTeacher.weight }}</span>
        </el-form-item>
        <el-form-item label="新权重" prop="weight">
          <el-input-number 
            v-model="weightForm.weight" 
            :min="0"
            :max="100"
            placeholder="请输入权重值"
            style="width: 100%"
          />
          <div style="font-size: 12px; color: #999; margin-top: 5px;">
            权重越高，推荐优先级越高（0-100）
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleWeightClose">取消</el-button>
          <el-button type="primary" @click="submitWeight">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 设置分成比例弹窗 -->
    <el-dialog
      v-model="rateDialogVisible"
      title="设置分成比例"
      width="400px"
      :before-close="handleRateClose"
    >
      <el-form
        ref="rateFormRef"
        :model="rateForm"
        :rules="rateRules"
        label-width="100px"
      >
        <el-form-item label="讲师昵称">
          <span>{{ currentTeacher.nick_name }}</span>
        </el-form-item>
        <el-form-item label="当前分成">
          <span>{{ currentTeacher.expect_rate }}%</span>
        </el-form-item>
        <el-form-item label="新分成比例" prop="expect_rate">
          <el-input-number 
            v-model="rateForm.expect_rate" 
            :min="0"
            :max="100"
            :precision="2"
            placeholder="请输入分成比例"
            style="width: 100%"
          />
          <div style="font-size: 12px; color: #999; margin-top: 5px;">
            讲师从课程销售中获得的分成比例（0-100%）
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleRateClose">取消</el-button>
          <el-button type="primary" @click="submitRate">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改余额弹窗 -->
    <el-dialog
      v-model="balanceDialogVisible"
      title="修改余额"
      width="450px"
      :before-close="handleBalanceClose"
    >
      <el-form
        ref="balanceFormRef"
        :model="balanceForm"
        :rules="balanceRules"
        label-width="100px"
      >
        <el-form-item label="当前余额">
          <span style="font-weight: bold; color: #409eff;">¥{{ currentTeacher.balance }}</span>
        </el-form-item>
        <el-form-item label="操作类型" prop="change_type">
          <el-select v-model="balanceForm.change_type" placeholder="请选择操作类型" style="width: 100%">
            <el-option label="增加余额" :value="1" />
            <el-option label="减少余额" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item :label="balanceForm.change_type === 1 ? '增加金额' : '减少金额'" prop="balance">
          <el-input-number 
            v-model="balanceForm.balance" 
            :precision="2"
            :step="0.01"
            :min="0.01"
            :max="balanceForm.change_type === 2 ? currentTeacher.balance : 999999"
            :placeholder="balanceForm.change_type === 1 ? '请输入要增加的金额' : '请输入要减少的金额'"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="操作后余额">
          <span style="font-weight: bold; color: #67c23a;">
            ¥{{ getNewBalance() }}
          </span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleBalanceClose">取消</el-button>
          <el-button type="primary" @click="submitBalance">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增讲师弹窗 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增讲师"
      width="500px"
      :before-close="handleAddClose"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addRules"
        label-width="100px"
      >
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="讲师昵称" prop="nick_name">
          <el-input v-model="addForm.nick_name" placeholder="请输入讲师昵称" />
        </el-form-item>
        <el-form-item label="权重" prop="weight">
          <el-input-number 
            v-model="addForm.weight" 
            :min="0"
            :max="100"
            placeholder="请输入权重"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="分成比例" prop="expect_rate">
          <el-input-number 
            v-model="addForm.expect_rate" 
            :min="0"
            :max="100"
            :precision="2"
            placeholder="请输入分成比例"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleAddClose">取消</el-button>
          <el-button type="primary" @click="submitAdd">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { list, status, register, setBalance, setTeacherWeight, setTeacherRate } from '@/api/user/index.js'
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

defineOptions({
  name: 'TeacherManagement'
})

// 表格相关数据
const tableLoading = ref(false)
const tableData = ref([])
const queryParams = ref({
  page: 1,
  pageSize: 10,
  type: 2 // 固定为讲师类型
})
const total = ref(0)

// 搜索表单
const searchForm = ref({
  name: '',
  phone: '',
  status: '',
  is_vip: ''
})

// 统计数据
const stats = computed(() => {
  const active = tableData.value.filter(item => item.status === 1).length
  const disabled = tableData.value.filter(item => item.status === 0).length
  const vip = tableData.value.filter(item => item.is_vip === 1).length
  
  return {
    total: total.value,
    active,
    disabled,
    vip
  }
})

// 当前选中的讲师
const currentTeacher = ref({})

// 详情弹窗
const detailDialogVisible = ref(false)

// 权重设置弹窗
const weightDialogVisible = ref(false)
const weightFormRef = ref(null)
const weightForm = ref({
  id: '',
  weight: 0
})

// 分成比例设置弹窗
const rateDialogVisible = ref(false)
const rateFormRef = ref(null)
const rateForm = ref({
  id: '',
  expect_rate: 0
})

// 余额修改弹窗
const balanceDialogVisible = ref(false)
const balanceFormRef = ref(null)
const balanceForm = ref({
  id: '',
  balance: 0,
  change_type: 1
})

// 新增讲师弹窗
const addDialogVisible = ref(false)
const addFormRef = ref(null)
const addForm = ref({
  phone: '',
  password: '',
  nick_name: '',
  user_type: 2,
  user_label: 1,
  weight: 0,
  expect_rate: 0
})

// 表单验证规则
const weightRules = {
  weight: [
    { required: true, message: '请输入权重值', trigger: 'blur' },
    { type: 'number', min: 0, max: 100, message: '权重值必须在0-100之间', trigger: 'blur' }
  ]
}

const rateRules = {
  expect_rate: [
    { required: true, message: '请输入分成比例', trigger: 'blur' },
    { type: 'number', min: 0, max: 100, message: '分成比例必须在0-100之间', trigger: 'blur' }
  ]
}

const balanceRules = {
  change_type: [
    { required: true, message: '请选择操作类型', trigger: 'change' }
  ],
  balance: [
    { required: true, message: '请输入金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '金额必须大于0', trigger: 'blur' }
  ]
}

const addRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  nick_name: [
    { required: true, message: '请输入讲师昵称', trigger: 'blur' }
  ],
  weight: [
    { required: true, message: '请输入权重', trigger: 'blur' }
  ],
  expect_rate: [
    { required: true, message: '请输入分成比例', trigger: 'blur' }
  ]
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString('zh-CN')
}

// 获取权重标签类型
const getWeightTagType = (weight) => {
  if (weight >= 80) return 'danger'
  if (weight >= 50) return 'warning'
  if (weight >= 20) return 'primary'
  return 'info'
}

// 计算操作后的新余额
const getNewBalance = () => {
  if (!balanceForm.value.balance || !currentTeacher.value.balance) {
    return currentTeacher.value.balance || 0
  }
  
  const currentBalance = parseFloat(currentTeacher.value.balance)
  const changeAmount = parseFloat(balanceForm.value.balance)
  
  if (balanceForm.value.change_type === 1) {
    return (currentBalance + changeAmount).toFixed(2)
  } else {
    return Math.max(0, currentBalance - changeAmount).toFixed(2)
  }
}

// 搜索数据
const searchData = () => {
  queryParams.value.page = 1
  getList()
}

// 重置搜索
const resetData = () => {
  searchForm.value = {
    name: '',
    phone: '',
    status: '',
    is_vip: ''
  }
  queryParams.value.page = 1
  getList()
}

// 分页处理
const handleSizeChange = (size) => {
  queryParams.value.pageSize = size
  getList()
}

const handleCurrentChange = (page) => {
  queryParams.value.page = page
  getList()
}

// 获取讲师列表
async function getList() {
  tableLoading.value = true
  try {
    const params = {
      ...queryParams.value,
      ...searchForm.value
    }
    const res = await list(params)
    if (res.code === 0) {
      tableData.value = res.data.list || []
      // 为每个讲师添加loading状态
      tableData.value.forEach(item => {
        item.loading = false
      })
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.msg || '获取数据失败')
    }
  } catch (error) {
    console.error('获取讲师列表失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    tableLoading.value = false
  }
}

// 状态切换
async function statusChangeBefore(row) {
  row.loading = true
  try {
    const params = { ID: row.ID, status: row.status === 1 ? 0 : 1 }
    const res = await status(params)
    if (res.code === 0) {
      row.status = row.status === 1 ? 0 : 1
      ElMessage.success('状态修改成功')
    } else {
      ElMessage.error(res.msg || '状态修改失败')
    }
  } catch (error) {
    ElMessage.error('状态修改失败')
  } finally {
    row.loading = false
  }
}

// 查看详情
const handleDetail = (row) => {
  currentTeacher.value = row
  detailDialogVisible.value = true
}

// 设置权重
const handleEditWeight = (row) => {
  currentTeacher.value = row
  weightForm.value = {
    id: row.ID,
    weight: row.weight
  }
  weightDialogVisible.value = true
}

// 设置分成比例
const handleEditRate = (row) => {
  currentTeacher.value = row
  rateForm.value = {
    id: row.ID,
    expect_rate: row.expect_rate
  }
  rateDialogVisible.value = true
}

// 修改余额
const handleBalance = (row) => {
  currentTeacher.value = row
  balanceForm.value = {
    id: row.ID,
    balance: 0,
    change_type: 1
  }
  balanceDialogVisible.value = true
}

// 新增讲师
const handleAdd = () => {
  addForm.value = {
    phone: '',
    password: '',
    nick_name: '',
    user_type: 2,
    user_label: 1,
    weight: 0,
    expect_rate: 0
  }
  addDialogVisible.value = true
}

// 关闭弹窗方法
const handleDetailClose = () => {
  detailDialogVisible.value = false
}

const handleWeightClose = () => {
  weightDialogVisible.value = false
  weightFormRef.value?.resetFields()
}

const handleRateClose = () => {
  rateDialogVisible.value = false
  rateFormRef.value?.resetFields()
}

const handleBalanceClose = () => {
  balanceDialogVisible.value = false
  balanceFormRef.value?.resetFields()
}

const handleAddClose = () => {
  addDialogVisible.value = false
  addFormRef.value?.resetFields()
}

// 提交权重设置
const submitWeight = async () => {
  if (!weightFormRef.value) return
  await weightFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await setTeacherWeight(weightForm.value)
        if (res.code === 0) {
          ElMessage.success('权重设置成功')
          handleWeightClose()
          getList()
        } else {
          ElMessage.error(res.msg || '权重设置失败')
        }
      } catch (error) {
        console.error('权重设置失败:', error)
        ElMessage.error('权重设置失败')
      }
    }
  })
}

// 提交分成比例设置
const submitRate = async () => {
  if (!rateFormRef.value) return
  await rateFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await setTeacherRate(rateForm.value)
        if (res.code === 0) {
          ElMessage.success('分成比例设置成功')
          handleRateClose()
          getList()
        } else {
          ElMessage.error(res.msg || '分成比例设置失败')
        }
      } catch (error) {
        console.error('分成比例设置失败:', error)
        ElMessage.error('分成比例设置失败')
      }
    }
  })
}

// 提交余额修改
const submitBalance = async () => {
  if (!balanceFormRef.value) return
  
  // 额外验证：减少余额时不能超过当前余额
  if (balanceForm.value.change_type === 2) {
    const currentBalance = parseFloat(currentTeacher.value.balance)
    const reduceAmount = parseFloat(balanceForm.value.balance)
    
    if (reduceAmount > currentBalance) {
      ElMessage.error('减少金额不能超过当前余额')
      return
    }
  }
  
  await balanceFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await setBalance(balanceForm.value)
        if (res.code === 0) {
          ElMessage.success('余额修改成功')
          handleBalanceClose()
          getList()
        } else {
          ElMessage.error(res.msg || '余额修改失败')
        }
      } catch (error) {
        ElMessage.error('余额修改失败')
      }
    }
  })
}

// 提交新增讲师
const submitAdd = async () => {
  if (!addFormRef.value) return
  await addFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await register(addForm.value)
        if (res.code === 0) {
          ElMessage.success('新增讲师成功')
          handleAddClose()
          getList()
        } else {
          ElMessage.error(res.msg || '新增讲师失败')
        }
      } catch (error) {
        ElMessage.error('新增讲师失败')
      }
    }
  })
}

// 页面初始化
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.gva-search-box {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stats-box {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  .stat-item {
    text-align: center;
    padding: 20px;
    border-radius: 8px;
    background: #f8f9fa;
    
    &.active {
      background: #f0f9ff;
      color: #67c23a;
    }
    
    &.vip {
      background: #fef9e7;
      color: #e6a23c;
    }
    
    &.disabled {
      background: #fef2f2;
      color: #f56c6c;
    }

    .stat-value {
      font-size: 28px;
      font-weight: bold;
      margin-bottom: 5px;
    }

    .stat-label {
      font-size: 14px;
      opacity: 0.8;
    }
  }
}

.gva-table-box {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  
  .gva-btn-list {
    margin-bottom: 20px;
  }
}

.gva-table {
  :deep(.el-table__header) {
    background-color: #f5f7fa;
  }
  
  :deep(.el-table__row:hover > td) {
    background-color: #f5f7fa !important;
  }
}

.gva-pagination {
  margin-top: 20px;
  text-align: right;
}

.demo-form-inline {
  .el-form-item {
    margin-right: 20px;
  }
}
</style>