<template>
  <div class="discount-users-container">
    <!-- 主容器 -->
    <el-card class="main-container" shadow="never">
      <!-- 搜索和操作栏 -->
      <div class="filter-section">
        <div class="filter-content">
          <el-form :inline="true" :model="queryParams" class="search-form" v-if="!codeId">
            <el-form-item label="代金卷" v-if="!codeId">
              <el-select 
                v-model="queryParams.code_id" 
                placeholder="请选择代金券"
                filterable
                clearable
                style="width: 280px"
              >
                <el-option
                  v-for="item in voucherListOptions"
                  :key="item.id"
                  :label="`${item.name} (¥${(item.amount / 100).toFixed(2)})`"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery" :disabled="!queryParams.code_id">
                <el-icon><Search /></el-icon>查询
              </el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <div class="action-bar">
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>新增用户关联
            </el-button>
            <el-button type="success" @click="fetchUsersList">
              <el-icon><Refresh /></el-icon>刷新
            </el-button>
            <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">
              <el-icon><Delete /></el-icon>批量删除
            </el-button>
          </div>
        </div>
      </div>

      <!-- 用户关联列表 -->
      <div class="table-section">
        <!-- 骨架屏 -->
        <div v-if="loading" class="skeleton-container">
          <div v-for="i in 5" :key="i" class="skeleton-row">
            <div class="skeleton-cell skeleton-checkbox"></div>
            <div class="skeleton-cell skeleton-id"></div>
            <div class="skeleton-cell skeleton-discount-id"></div>
            <div class="skeleton-cell skeleton-related-id"></div>
            <div class="skeleton-cell skeleton-type"></div>
            <div class="skeleton-cell skeleton-time"></div>
            <div class="skeleton-cell skeleton-action"></div>
          </div>
        </div>

        <el-table
          v-else
          v-loading="loading"
          :data="usersList"
          @selection-change="handleSelectionChange"
          style="width: 100%"
          :header-cell-style="{ background: '#fafafa', color: '#333', fontWeight: 600 }"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="discountId" label="代金券ID" width="120" v-if="!codeId" />
          <el-table-column label="用户名" min-width="150">
            <template #default="{ row }">
              <el-link v-if="row.userId && row?.user?.user_name" type="primary" :underline="false" @click="router.push({ path: '/user/detail', query: { user_id: row.userId } })">{{ row.user.user_name }}</el-link>
              <span v-else>{{ row?.user?.user_name || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="手机号" min-width="150">
            <template #default="{ row }">
              {{ row?.user?.phone || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="邮箱" min-width="150">
            <template #default="{ row }">
              {{ row?.user?.email || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getUserTypeTagByRow(row)">
                {{ getUserTypeNameByRow(row) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
                <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.count"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          class="pagination"
        />
      </div>
    </el-card>

    <!-- 添加/编辑用户关联对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增用户关联' : '编辑用户关联'"
      width="600px"
      append-to-body
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="代金券" prop="code_id">
          <el-select 
            v-model="form.code_id" 
            placeholder="请选择代金券"
            filterable
            clearable
            :disabled="dialogType === 'edit'"
            style="width: 100%"
          >
            <el-option
              v-for="item in voucherListOptions"
              :key="item.id"
              :label="`${item.name} (¥${(item.amount / 100).toFixed(2)})`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="选择类型" prop="select_type" v-if="dialogType === 'add'">
          <el-radio-group v-model="form.select_type" @change="handleSelectTypeChange">
            <el-radio value="user">用户</el-radio>
            <el-radio value="user_group">用户组</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="选择用户" prop="selected_user" v-if="dialogType === 'add' && form.select_type === 'user'">
          <div class="user-selector-wrapper">
            <div class="selected-user-display" v-if="form.selected_user">
              <el-tag type="primary" closable @close="clearSelectedUser">
                {{ getSelectedUserName() }}
              </el-tag>
            </div>
            <el-button 
              type="primary" 
              plain 
              @click="openUserSelector"
              style="width: 100%"
            >
              <el-icon><User /></el-icon>
              {{ form.selected_user ? '重新选择用户' : '选择用户' }}
            </el-button>
          </div>
        </el-form-item>
        
        <el-form-item label="选择用户组" prop="selected_group" v-if="dialogType === 'add' && form.select_type === 'user_group'">
          <el-select 
            v-model="form.selected_group" 
            placeholder="请选择用户组"
            filterable
            clearable
            style="width: 100%"
            @change="handleUserGroupChange"
          >
            <el-option
              v-for="item in userGroupOptions"
              :key="item.Id"
              :label="`${item.Name} (ID: ${item.Id})`"
              :value="item.Id"
            />
          </el-select>
        </el-form-item>
        
        <!-- 编辑模式显示字段 -->
        <template v-if="dialogType === 'edit'">
          <el-form-item label="关联类型">
            <el-tag :type="form.select_type === 'user' ? 'primary' : 'warning'">
              {{ form.select_type === 'user' ? '用户' : '用户组' }}
            </el-tag>
          </el-form-item>
          <el-form-item v-if="form.select_type === 'user'" label="用户ID" prop="user_id">
            <div class="user-selector-wrapper">
                <div class="selected-user-display" v-if="form.user_id">
                  <el-tag type="primary" closable @close="clearSelectedUser">
                    {{ getSelectedUserName() }}
                  </el-tag>
                </div>
                <el-button type="primary" plain @click="openUserSelector" style="width: 100%;">
                  <el-icon><User /></el-icon>
                  {{ form.user_id ? '重新选择用户' : '选择用户' }}
                </el-button>
            </div>
          </el-form-item>
          <el-form-item v-if="form.select_type === 'user_group'" label="用户组ID">
            <el-select v-model="form.user_group_id" placeholder="">
                <el-option v-for="item in userGroupOptions" :key="item.Id" :label="`${item.Name} (ID: ${item.Id})`" :value="item.Id">
                </el-option>
            </el-select>
          </el-form-item>
        
        </template>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户选择弹窗 -->
    <UserSelector
      v-model:visible="userSelectorVisible"
      @select="confirmUserSelection"
    />
  </div>
</template>


<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Search, Plus, Refresh, User } from '@element-plus/icons-vue'
import { 
  getDiscountUsersList, 
  addDiscountUsers,
  updateDiscountUsers,
  deleteDiscountUsers,
  getDiscountCodeList
} from '@/api/admin/discount'
import {
  getUserList,
  getUserGroupList
} from '@/api/admin/user'
import UserSelector from '@/components/UserSelector/index.vue'

const props = defineProps({
  codeId: {
    type: [String, Number],
    default: ''
  }
})

const router = useRouter()

// 查询参数
const queryParams = reactive({
  code_id: props.codeId || '',
  page: 1,
  count: 10
})

watch(() => props.codeId, (newVal) => {
  if (newVal) {
    queryParams.code_id = newVal
    fetchUsersList()
  }
})

// 表单数据
const form = reactive({
  id: undefined,
  code_id: undefined,
  user_id: undefined,
  username: '',
  email: '',
  status: 1,
  select_type: 'user',  // 选择类型：user 或 user_group
  selected_user: undefined,  // 选中的用户ID
  selected_group: undefined,  // 选中的用户组ID
  user_group_id: undefined  // 用户组ID（用于提交）
})

const formRules = {
  code_id: [
    { required: true, message: '请选择代金券', trigger: 'change' }
  ],
  select_type: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ],
  selected_user: [
    { required: true, message: '请选择用户', trigger: 'change' }
  ],
  selected_group: [
    { required: true, message: '请选择用户组', trigger: 'change' }
  ]
}

// 状态数据
const loading = ref(false)
const usersList = ref([])
const total = ref(0)
const selectedRows = ref([])
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const voucherListOptions = ref([])  // 代金券列表选项
const userOptions = ref([])  // 用户列表选项
const userGroupOptions = ref([])  // 用户组列表选项

// 用户选择弹窗相关
const userSelectorVisible = ref(false)

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 获取用户类型名称（根据行数据）
const getUserTypeNameByRow = (row) => {

//通过看是否有user对象参数判断是否为用户还是用户组类型
  if(row.user){
    return '用户'
  }else{
    return '用户组'
  }

  return '-'
}

// 获取用户类型标签（根据行数据）
const getUserTypeTagByRow = (row) => {
  

  if(row.user){
    return 'primary'
  }else{
    return 'warning'
  }
  return 'info'
}

// 获取代金券列表选项
const fetchVoucherListOptions = async () => {
  try {
    const res = await getDiscountCodeList({
      page: 1,
      count: 10,
      discount_type: 'coupon'
    })
    console.log('获取代金券列表:', res.data)
    if (res.data.code === 200) {
      voucherListOptions.value = res.data.data?.data || []
    }
  } catch (error) {
    console.error('获取代金券列表失败:', error)
    ElMessage.error('获取代金券列表失败')
  }
}

// 获取用户列表
const fetchUserList = async () => {
  try {
    const res = await getUserList({
      page: 1,
      count: 10,
      key: ''
    })
    console.log('获取用户列表:', res.data)
    if (res.data.code === 200) {
      userOptions.value = res.data.data?.data || []
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  }
}

// 获取用户组列表
const fetchUserGroupList = async () => {
  try {
    const res = await getUserGroupList({
      page: 1,
      count: 10,
      key: ''
    })
    console.log('获取用户组列表:', res.data)
    if (res.data.code === 200) {
      userGroupOptions.value = res.data.data?.data || []
    }
  } catch (error) {
    console.error('获取用户组列表失败:', error)
    ElMessage.error('获取用户组列表失败')
  }
}

// 打开用户选择器
const openUserSelector = () => {
  userSelectorVisible.value = true
}

// 确认用户选择
const confirmUserSelection = (user) => {
  if (!user) {
    ElMessage.warning('请选择一个用户')
    return
  }
  form.selected_user = user.UserId
  form.user_id = user.UserId
  // 将选中的用户添加到 userOptions 中（如果不存在）
  if (!userOptions.value.find(u => u.UserId === user.UserId)) {
    userOptions.value.push(user)
  }
  userSelectorVisible.value = false
  ElMessage.success('用户选择成功')
}

// 清除选中的用户
const clearSelectedUser = () => {
  form.selected_user = undefined
  form.user_id = undefined
}


// 获取选中用户的显示名称
const getSelectedUserName = () => {
  
  let user;
   user = userOptions.value.find(u => u.UserId === form.selected_user)
   console.log("是否有用户的user_id信息",form.user_id)
//需要进行判断是否是编辑的用户通过user_id进行刷选到所需要的用户对象信息
if(form.user_id){
  console.log("用户表信息：",userOptions.value)
   user = userOptions.value.find(u => u.UserId === form.user_id)
}

console.log("获取用户的名称",user)
  return user ? `${user.UserName} (ID: ${user.UserId})` : '未知用户'
}

// 选择类型变化
const handleSelectTypeChange = (type) => {
  form.selected_user = undefined
  form.selected_group = undefined
  form.user_id = undefined
  form.user_group_id = undefined
}

// 选择用户变化
const handleUserChange = (userId) => {
  const user = userOptions.value.find(item => item.UserId === userId)
  if (user) {
    form.user_id = user.UserId
  }
}

// 选择用户组变化
const handleUserGroupChange = (groupId) => {
  const group = userGroupOptions.value.find(item => item.Id === groupId)
  if (group) {
    form.user_group_id = group.Id
  }
}

// 获取用户关联列表
const fetchUsersList = async () => {
  if (!queryParams.code_id) {
    ElMessage.warning('请选择代金券进行查询')
    return
  }
  
  loading.value = true
  try {
    const res = await getDiscountUsersList(queryParams)
    console.log('用户关联列表数据:', res.data)
    if (res.data.code === 200) {
      usersList.value = res.data.data || []
      total.value = res.data.data?.length || 0
    }
  } catch (error) {
    console.error('获取用户关联列表失败:', error)
    ElMessage.error('获取用户关联列表失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  queryParams.page = 1
  fetchUsersList()
}

// 重置查询
const resetQuery = () => {
  queryParams.code_id = ''
  queryParams.page = 1
  usersList.value = []
  total.value = 0
}

// 选择项变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页
const handleSizeChange = (size) => {
  queryParams.count = size
  fetchUsersList()
}

const handleCurrentChange = (page) => {
  queryParams.page = page
  fetchUsersList()
}

// 新增用户关联
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  Object.assign(form, {
    id: undefined,
    code_id: queryParams.code_id ? Number(queryParams.code_id) : undefined,
    user_id: undefined,
    username: '',
    email: '',
    status: 1,
    select_type: 'user',
    selected_user: undefined,
    selected_group: undefined,
    user_group_id: undefined
  })
  formRef.value?.resetFields()
  
  fetchUserGroupList()
}

// 编辑用户关联
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  
  // 判断是用户还是用户组
  let userId, userGroupId, selectType
  console.log("获取编辑的当前信息：",row)
  if (row.userId && row.userId !== 0) {
    // 用户
    userId = row.userId
    userGroupId = undefined
    selectType = 'user'
  } else if (row.userGroupId && row.userGroupId !== 0) {
    // 用户组
    userId = undefined
    userGroupId = row.userGroupId
    selectType = 'user_group'
  }
  
  Object.assign(form, {
    id: row.id,
    code_id: row.discountId,
    user_id: userId,
    user_group_id: userGroupId,
    select_type: selectType,
    username: '',
    email: '',
    status: 1
  })
  //点击编辑需要初始化加载用户列表
    fetchUserList()
    fetchUserGroupList()
}

// 删除用户关联
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除该用户关联吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteDiscountUsers({ 
        discount_user_id: String(row.id),
        code_id: String(row.discountId)
      })
      console.log('删除响应:', res.data)
      if (res.data.code === 200) {
        ElMessage.success('删除成功')
        fetchUsersList()
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error(error.response?.data?.message || '删除失败')
    }
  }).catch(() => {})
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  ElMessageBox.confirm(`确认删除选中的 ${selectedRows.value.length} 条记录吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    loading.value = true
    try {
      const deletePromises = selectedRows.value.map(row => 
        deleteDiscountUsers({ 
          discount_user_id: String(row.id),
          code_id: String(row.discountId)
        })
      )
      
      const results = await Promise.allSettled(deletePromises)
      
      const successCount = results.filter(r => r.status === 'fulfilled' && r.value?.data?.code === 200).length
      const failCount = results.length - successCount
      
      if (failCount === 0) {
        ElMessage.success(`批量删除成功，共删除 ${successCount} 条记录`)
      } else if (successCount === 0) {
        ElMessage.error(`批量删除失败，所有 ${failCount} 条记录删除失败`)
      } else {
        ElMessage.warning(`批量删除完成，成功 ${successCount} 条，失败 ${failCount} 条`)
      }
      
      fetchUsersList()
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除操作异常')
    } finally {
      loading.value = false
    }
  }).catch(() => {})
}

// 提交表单
const submitForm = () => {
  // 新增模式下的额外验证
  if (dialogType.value === 'add') {
    if (!form.code_id) {
      ElMessage.warning('请选择代金券')
      return
    }
    if (form.select_type === 'user' && !form.selected_user) {
      ElMessage.warning('请选择用户')
      return
    }
    if (form.select_type === 'user_group' && !form.selected_group) {
      ElMessage.warning('请选择用户组')
      return
    }
    if (!form.user_id && !form.user_group_id) {
      ElMessage.warning('请先选择用户或用户组')
      return
    }
  }
  
  formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = {
          code_id: String(form.code_id)
        }
        
        // 根据选择类型决定传 user_id 还是 user_group_id
        if (dialogType.value === 'add') {
          if (form.select_type === 'user') {
            // 选择的是用户，传 user_id
            submitData.user_id = String(form.user_id)
          } else if (form.select_type === 'user_group') {
            // 选择的是用户组，传 user_group_id
            submitData.user_group_id = String(form.user_group_id)
          }
        } else {
          // 编辑模式：根据类型传递对应的ID
          if (form.select_type === 'user') {
            submitData.user_id = String(form.user_id)
          } else if (form.select_type === 'user_group') {
            submitData.user_group_id = String(form.user_group_id)
          }
          // 编辑需要传 discount_user_id
          submitData.discount_user_id = String(form.id)
        }
        
        console.log('提交用户关联数据:', submitData)
        
        let res
        if (dialogType.value === 'add') {
          res = await addDiscountUsers(submitData)
        } else {
          res = await updateDiscountUsers(submitData)
        }
        
        console.log('提交响应:', res.data)
        if (res.data.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '新增成功' : '修改成功')
          dialogVisible.value = false
          fetchUsersList()
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error(error.response?.data?.message || '操作失败')
      }
    }
  })
}

// 初始化
onMounted(() => {
  fetchVoucherListOptions()
  if (queryParams.code_id) {
    fetchUsersList()
  }
})
</script>

<style scoped>
.discount-users-container {
  padding: 0;
}

.main-container {
  border: 1px solid #e1e8ed;
  background: #ffffff;
}

.filter-section {
  padding: 0;
  border-bottom: 1px solid #e1e8ed;
  background: #fafbfc;
}

.filter-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  gap: 20px;
  flex-wrap: wrap;
}

.search-form {
  margin: 0;
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12px;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 0;
}

.action-bar {
  display: flex;
  gap: 12px;
  flex-shrink: 0;
}

.table-section {
  padding: 0;
}

.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  padding: 16px 20px;
  border-top: 1px solid #e1e8ed;
  background: #fafbfc;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 0;
}

:deep(.el-card__body) {
  padding: 0;
}

/* 用户选择器样式 */
.user-selector-wrapper {
  width: 100%;
}

.selected-user-display {
  margin-bottom: 12px;
  padding: 8px 12px;
  background: #f5f7fa;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-selector-dialog .selector-search {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #ebeef5;
}

.selector-pagination {
  margin-top: 16px;
  justify-content: flex-end;
}

:deep(.el-table__row) {
  cursor: pointer;
}

:deep(.el-table__row):hover {
  background-color: #f5f7fa;
}

:deep(.current-row) {
  background-color: #ecf5ff !important;
}

/* 骨架屏样式 */
.skeleton-container {
  padding: 20px;
}

.skeleton-row {
  display: flex;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
  gap: 16px;
}

.skeleton-row:last-child {
  border-bottom: none;
}

.skeleton-cell {
  height: 20px;
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: skeleton-loading 1.5s ease-in-out infinite;
  border-radius: 4px;
}

.skeleton-checkbox { width: 55px; }
.skeleton-id { width: 80px; }
.skeleton-discount-id { width: 120px; }
.skeleton-related-id { width: 130px; }
.skeleton-type { width: 120px; }
.skeleton-time { width: 180px; }
.skeleton-action { width: 200px; height: 32px; }

@keyframes skeleton-loading {
  0% { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}
</style>
