<template>
  <div class="p-2">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="flex items-center">
            <div class="stats-icon bg-blue-100 text-blue-600">
              <el-icon><User /></el-icon>
            </div>
            <div class="ml-4">
              <div class="text-sm text-gray-400">总用户数</div>
              <div class="text-2xl font-bold">{{ total }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="flex items-center">
            <div class="stats-icon bg-green-100 text-green-600">
              <el-icon><Avatar /></el-icon>
            </div>
            <div class="ml-4">
              <div class="text-sm text-gray-400">付费用户</div>
              <div class="text-2xl font-bold">{{ paidUserCount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="flex items-center">
            <div class="stats-icon bg-orange-100 text-orange-600">
              <el-icon><Document /></el-icon>
            </div>
            <div class="ml-4">
              <div class="text-sm text-gray-400">测评用户</div>
              <div class="text-2xl font-bold">{{ assessmentUserCount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="flex items-center">
            <div class="stats-icon bg-red-100 text-red-600">
              <el-icon><CircleClose /></el-icon>
            </div>
            <div class="ml-4">
              <div class="text-sm text-gray-400">黑名单用户</div>
              <div class="text-2xl font-bold">{{ blacklistUserCount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索栏 -->
    <el-card shadow="hover" class="mb-4">
      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
        <el-form-item label="用户姓名" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入用户姓名"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="用户编号" prop="studentNo">
          <el-input
            v-model="queryParams.studentNo"
            placeholder="请输入用户编号"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="用户类型" prop="userType">
          <el-select v-model="queryParams.userType" placeholder="用户类型" clearable style="width: 200px">
            <el-option
              v-for="dict in main_student_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="黑名单" prop="isBlacklist">
          <el-select v-model="queryParams.isBlacklist" placeholder="是否在黑名单" clearable style="width: 200px">
            <el-option label="是" value="Y" />
            <el-option label="否" value="N" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 工具栏和表格 -->
    <el-card shadow="hover">
      <template #header>
        <div class="flex justify-between items-center">
          <div class="flex items-center">
            <el-icon class="mr-2"><UserFilled /></el-icon>
            <span>用户列表</span>
          </div>
          <div>
            <el-button type="primary" plain icon="Download" @click="handleExport">导出</el-button>
            <el-button type="success" plain icon="Promotion" :disabled="multiple" @click="handleBatchRecommend">批量内推</el-button>
            <el-button type="danger" plain icon="CircleClose" :disabled="multiple" @click="handleBatchBlacklist">批量加黑</el-button>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" :data="studentList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="用户信息" min-width="200">
          <template #default="scope">
            <div class="flex items-center">
              <el-avatar :src="scope.row.avatarUrl" :size="40" />
              <div class="ml-2">
                <div class="font-bold flex items-center">
                  {{ scope.row.name }}
                  <el-icon v-if="scope.row.gender === '0'" class="text-blue-500 ml-1"><Male /></el-icon>
                  <el-icon v-else-if="scope.row.gender === '1'" class="text-pink-500 ml-1"><Female /></el-icon>
                  <span v-if="scope.row.userType === '1'" class="ml-1 text-orange-400">💎</span>
                </div>
                <div class="text-xs text-gray-400">{{ scope.row.studentNo }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="联系方式" min-width="180">
          <template #default="scope">
            <div>{{ scope.row.mobile }}</div>
            <div class="text-xs text-gray-400">{{ scope.row.email }}</div>
          </template>
        </el-table-column>
        <el-table-column label="测评数" align="center" prop="evaluationCount" />
        <el-table-column label="类型" align="center">
          <template #default="scope">
            <el-tag>
              {{ scope.row.userTypeLabel || scope.row.userType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="累计消费" align="center" prop="totalAmount">
          <template #default="scope">
            <span class="text-blue-600 font-bold">￥{{ scope.row.totalAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="角色" align="center">
          <template #default>
            <el-tag type="info">学员</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="注册时间" align="center" prop="createTime" width="120" />
        <el-table-column label="最后登录" align="center" prop="loginDate" width="120" />
        <el-table-column label="操作" align="center" width="280" fixed="right">
          <template #default="scope">
            <div class="flex items-center justify-center gap-1">
              <el-button link type="primary" @click="handleDetail(scope.row)">详情</el-button>
              <el-button link type="primary" @click="handleUpdate(scope.row)">编辑</el-button>
              <el-button v-if="scope.row.userType !== '3'" link type="danger" @click="handleBlacklist(scope.row)">加入黑名单</el-button>
              <el-button v-else link type="success" @click="handleRemoveBlacklist(scope.row)">移除黑名单</el-button>
              <el-button link type="success" @click="handleRecommend(scope.row)">内推</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="flex justify-between items-center mt-4">
        <span class="text-sm text-gray-400">显示 1 到 {{ studentList.length }} 条，共 {{ total }} 条</span>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </el-card>

    <!-- 内推对话框 -->
    <el-dialog v-model="recommendOpen" title="内推" width="500px" append-to-body>
      <el-form :model="recommendForm" label-width="80px">
        <el-form-item label="内推名单">
          <el-select v-model="recommendForm.users" multiple placeholder="请选择" style="width: 100%">
            <el-option v-for="user in selectedUsers" :key="user.id" :label="user.name" :value="user.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="内推公司">
          <el-select v-model="recommendForm.company" placeholder="请选择公司" style="width: 100%">
            <el-option label="XXXXXX有限公司" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="内推岗位">
          <el-select v-model="recommendForm.post" placeholder="请选择岗位" style="width: 100%">
            <el-option label="审计岗位" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="说明">
          <el-input v-model="recommendForm.remark" type="textarea" rows="4" placeholder="请输入说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="recommendOpen = false">取消</el-button>
          <el-button type="primary" @click="submitRecommend">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Student" lang="ts">
import { ref, reactive, onMounted, getCurrentInstance, ComponentInternalInstance } from 'vue'
import { useRouter } from 'vue-router'
import { User, Avatar, Document, CircleClose, UserFilled, Download, Promotion, Male, Female, Search, Refresh } from '@element-plus/icons-vue'
import { listStudent, updateUserType, updateStatus } from "@/api/main/student";
import { StudentVO, StudentQuery } from "@/api/main/student/types";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { main_student_type, main_arrivail_time, main_position_type, main_experience, main_education, main_internship_duration } = proxy?.useDict("main_student_type", "main_arrivail_time", "main_position_type", "main_experience", "main_education", "main_internship_duration") as any;

const router = useRouter()

const loading = ref(true)
const total = ref(0)
const studentList = ref<StudentVO[]>([])
const paidUserCount = ref(0)
const assessmentUserCount = ref(0)
const blacklistUserCount = ref(0)

const queryParams = reactive<StudentQuery>({
  pageNum: 1,
  pageSize: 20,
  studentNo: undefined,
  name: undefined,
  userType: undefined,
  status: undefined,
  isBlacklist: undefined
})
const dateRange = ref([])
const multiple = ref(true)
const selectedUsers = ref([])

const recommendOpen = ref(false)
const recommendForm = reactive({
  users: [],
  company: undefined,
  post: undefined,
  remark: ''
})

const getList = () => {
  loading.value = true
  listStudent(proxy?.addDateRange(queryParams, dateRange.value)).then(response => {
    studentList.value = response.rows
    total.value = response.total
    calculateStats()
    loading.value = false
  })
}

const calculateStats = () => {
  paidUserCount.value = studentList.value.filter(item => item.userType === '1').length
  assessmentUserCount.value = studentList.value.filter(item => item.status === '0').length
  blacklistUserCount.value = studentList.value.filter(item => item.userType === '3').length
}

onMounted(() => {
  getList()
})

const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

const resetQuery = () => {
  dateRange.value = []
  proxy?.$refs['queryRef']?.resetFields()
  handleQuery()
}

const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
  multiple.value = !selection.length
}


const handleDetail = (row) => {
  router.push('/system/student/detail/' + row.id)
}

const handleUpdate = (row) => {
  router.push('/system/student/detail/' + row.id)
}

const handleStatusChange = (row) => {
  updateStatus(row.id, row.status).then(() => {
    proxy.$modal.msgSuccess('状态更新成功')
    calculateStats()
  }).catch(() => {
    row.status = row.status === '0' ? '1' : '0'
  })
}

const handleBlacklist = (row) => {
  proxy.$modal.confirm('确定要加入黑名单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    updateUserType(row.id, '3').then(() => {
      row.userType = '3'
      proxy.$modal.msgSuccess('已加入黑名单')
      calculateStats()
    })
  }).catch(() => {})
}

const handleRemoveBlacklist = (row) => {
  proxy.$modal.confirm('确定要移除黑名单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    updateUserType(row.id, '2').then(() => {
      row.userType = '2'
      proxy.$modal.msgSuccess('已移除黑名单')
      calculateStats()
    })
  }).catch(() => {})
}

const handleRecommend = (row: StudentVO) => {
  recommendForm.users = [row.id as string]
  selectedUsers.value = [row]
  recommendOpen.value = true
}

const handleBatchRecommend = () => {
  recommendForm.users = selectedUsers.value.map(item => item.id as string)
  recommendOpen.value = true
}

const handleBatchBlacklist = () => {
  if (selectedUsers.value.length === 0) {
    proxy.$modal.msgWarning('请先选择要加入黑名单的用户')
    return
  }
  proxy.$modal.confirm(`确定要将选中的 ${selectedUsers.value.length} 个用户加入黑名单吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    loading.value = true
    try {
      for (const item of selectedUsers.value) {
        await updateUserType(item.id, '3')
      }
      proxy.$modal.msgSuccess('批量加入黑名单成功')
      getList()
    } catch (error) {
      console.error(error)
    } finally {
      loading.value = false
    }
  }).catch(() => {})
}

const handleExport = () => {
  proxy.download('main/student/export', queryParams, `student_list_${new Date().getTime()}.xlsx`)
}

const submitRecommend = () => {
  if (!recommendForm.company || !recommendForm.post) {
    proxy.$modal.msgWarning('请选择公司和岗位')
    return
  }
  proxy.$modal.msgSuccess('内推成功')
  recommendOpen.value = false
}
</script>

<style scoped lang="scss">
.stats-card {
  .stats-icon {
    width: 48px;
    height: 48px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
  }
}
</style>
