<template>
  <div class="user-manage">
    <el-card>
      <div class="filter-container">
        <el-form :model="queryParams" label-width="100px" class="demo-form-inline">
          <el-row>
            <el-col :span="6">
              <el-form-item label="用户类型">
                <el-select v-model="queryParams.userRoles" placeholder="请选择用户类型" clearable size="small">
                  <el-option label="管理员" value="admin" />
                  <el-option label="普通用户" value="user" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="用户编码">
                <el-input v-model="queryParams.userCodeLike" placeholder="请输入用户编码" clearable size="small" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="用户名称">
                <el-input v-model="queryParams.userNameLike" placeholder="请输入用户名称" clearable size="small" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="创建时间">
                <el-date-picker
                  v-model="queryParams.dateRange"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd"
                  size="small"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item>
                <el-button type="primary" size="medium" @click="handleQuery">查询</el-button>
                <el-button type="primary" plain size="medium" @click="resetQuery">重置</el-button>
                <el-button type="primary" size="medium" @click="handleAdd">新增</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <r-table
        :columns="tableConfig.columns"
        :data="tableData"
        :deletion="false"
        :total="tableConfig.total"
        @currentChange="handleCurrentChange"
        @sizeChange="handleSizeChange"
        :currentPage="tableConfig.currentPage"
        :pageSize="tableConfig.pageSize"
      />
    </el-card>

    <!-- 用户新增弹窗 -->
    <user-dialog :visible.sync="dialogVisible" :title="dialogTitle" :is-edit="isEdit" :is-view="isView" :user-data="currentUserData" @submit="handleSubmit" />

    <!-- 重置密码弹窗 -->
    <reset-password-dialog :visible.sync="resetPasswordVisible" :user-id="currentUserId" @success="getUserList" />
  </div>
</template>

<script>
import UserDialog from './components/UserDialog.vue'
import ResetPasswordDialog from './components/ResetPasswordDialog.vue'
import { getUserPage, queryUserDetail, deleteUser, changeUserStatus, updatePassword } from '@/api/generatedApi/system'

export default {
  name: 'UserManage',
  components: {
    UserDialog,
    ResetPasswordDialog
  },
  data() {
    return {
      loading: false,
      dialogVisible: false,
      resetPasswordVisible: false,
      dialogTitle: '添加用户',
      isEdit: false,
      isView: false,
      currentUserData: {},
      currentUserId: '',
      queryParams: {
        page: 1,
        pageSize: 10,
        userRoles: '',
        userCodeLike: '',
        userNameLike: '',
        status: '',
        dateRange: []
      },
      // 表格配置项
      tableConfig: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
        columns: [
          { prop: 'userCode', key: '用户编码' },
          { prop: 'userName', key: '用户名称' },
          { prop: 'realName', key: '真实姓名' },
          { prop: 'mobile', key: '手机号' },
          { prop: 'email', key: '邮箱' },
          { prop: 'userRoles', key: '用户角色' },
          {
            prop: 'status',
            key: '状态',
            render: (h, params) => {
              return h(
                'el-tag',
                {
                  props: {
                    type: params.row.status === 0 ? 'success' : 'danger',
                    size: 'small'
                  }
                },
                params.row.status === 0 ? '启用' : '停用'
              )
            }
          },
          {
            key: '操作',
            render: (h, params) => {
              return h('div', [
                h(
                  'el-button',
                  {
                    props: { type: 'text', size: 'mini' },
                    on: { click: () => this.handleEdit(params.row) }
                  },
                  '编辑'
                ),
                // h(
                //   'el-button',
                //   {
                //     props: { type: 'text', size: 'mini' },
                //     on: { click: () => this.handleInfoVisible(params.row) }
                //   },
                //   '查看详情'
                // ),
                h(
                  'el-button',
                  {
                    props: {
                      type: 'text',
                      size: 'mini',
                      style: params.row.status === 0 ? 'color: #F56C6C' : 'color: #67C23A'
                    },
                    on: { click: () => this.handleToggleStatus(params.row) }
                  },
                  params.row.status === 0 ? '停用' : '启用'
                ),
                h(
                  'el-button',
                  {
                    props: { type: 'text', size: 'mini', style: 'color: #409EFF' },
                    on: { click: () => this.handleResetPassword(params.row) }
                  },
                  '重置密码'
                ),
                h(
                  'el-button',
                  {
                    props: { type: 'text', size: 'mini', style: 'color: #F56C6C' },
                    on: { click: () => this.handleDelete(params.row) }
                  },
                  '删除'
                )
              ])
            }
          }
        ]
      },
      tableData: []
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 获取用户列表
    getUserList() {
      this.loading = true
      const params = { ...this.queryParams }

      // 处理日期范围
      if (params.dateRange && params.dateRange.length === 2) {
        params.startDate = params.dateRange[0]
        params.endDate = params.dateRange[1]
      }
      delete params.dateRange

      getUserPage(params)
        .then(response => {
          console.log(response)
          if (response.code === '0') {
            this.tableData = response.content.content.list || []
            this.tableConfig.total = response.content.content.total || 0
          } else {
            this.$message.error(response.msg || '获取用户列表失败')
          }
        })
        .catch(error => {
          console.error('获取用户列表出错：', error)
          this.$message.error('获取用户列表出错')
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleQuery() {
      this.queryParams.page = 1
      this.getUserList()
    },
    resetQuery() {
      this.queryParams.userRoles = ''
      this.queryParams.userCodeLike = ''
      this.queryParams.userNameLike = ''
      this.queryParams.dateRange = []
      this.handleQuery()
    },
    handleAdd() {
      this.isEdit = false
      this.isView = false
      this.currentUserData = {}
      this.dialogVisible = true
      this.dialogTitle = '添加用户'
    },
    handleEdit(row) {
      this.isEdit = true
      this.isView = false
      this.dialogTitle = '编辑用户'
      this.loading = true

      // 获取用户详情
      queryUserDetail({ id: row.id })
        .then(response => {
          if (response.code === '0') {
            this.currentUserData = response.content.content || {}
            this.dialogVisible = true
          } else {
            this.$message.error(response.msg || '获取用户详情失败')
          }
        })
        .catch(error => {
          console.error('获取用户详情出错：', error)
          this.$message.error('获取用户详情出错')
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleInfoVisible(row) {
      // 查看详情逻辑
      this.isView = true
      this.isEdit = false
      this.dialogTitle = '查看用户详情'
      this.loading = true

      // 获取用户详情
      queryUserDetail({ id: row.id })
        .then(response => {
          if (response.code === '0') {
            this.currentUserData = response.content.content || {}
            this.dialogVisible = true
          } else {
            this.$message.error(response.msg || '获取用户详情失败')
          }
        })
        .catch(error => {
          console.error('获取用户详情出错：', error)
          this.$message.error('获取用户详情出错')
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleSubmit(formData) {
      this.getUserList() // 提交后刷新列表
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getUserList()
    },
    handleCurrentChange(val) {
      this.queryParams.page = val
      this.getUserList()
    },
    handleDelete(row) {
      this.$confirm('确认删除该用户吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loading = true
          // 将id放入数组中传递
          deleteUser([row.id])
            .then(response => {
              if (response.code === '0') {
                this.$message.success('删除成功')
                this.getUserList()
              } else {
                this.$message.error(response.msg || '删除失败')
              }
            })
            .catch(error => {
              console.error('删除用户出错：', error)
              this.$message.error('删除用户出错')
            })
            .finally(() => {
              this.loading = false
            })
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    handleToggleStatus(row) {
      const statusText = row.status === 0 ? '停用' : '启用'
      this.$confirm(`确认${statusText}该用户吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用changeUserStatus接口
        const newStatus = row.status === 0 ? 1 : 0 // 切换状态
        changeUserStatus({
          userId: row.id,
          status: newStatus
        })
          .then(response => {
            if (response.code === '0') {
              this.$message.success(`${statusText}成功`)
              this.getUserList() // 刷新列表
            } else {
              this.$message.error(response.msg || `${statusText}失败`)
            }
          })
          .catch(error => {
            console.error(`${statusText}用户出错：`, error)
            this.$message.error(`${statusText}用户出错`)
          })
      })
    },
    handleResetPassword(row) {
      this.currentUserId = row.id
      this.resetPasswordVisible = true
    }
  }
}
</script>

<style lang="scss" scoped>
.user-manage {
  padding: 20px;

  .filter-container {
    margin-bottom: 20px;

    .el-form-item {
      margin-bottom: 10px;
      margin-right: 10px;

      .el-form-item__label {
        padding-right: 8px;
      }
    }
  }
}
</style>
