<template>
  <div class=" render-container user-manage ">
    <div class="filter-container">
      <div class="flex align-items-c justify-content-b">
        <el-form
          :model="queryParams"
          label-width="100px"
          label-position="top"
          ref="queryParams"
          inline
        >
          <el-form-item label="用户名称" prop="userName">
            <el-input
              v-model="queryParams.userName"
              size="medium"
              placeholder="请输入用户名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" size="medium">
              <el-option label="全部" value=""></el-option>
              <el-option
                v-for="item in statusList"
                :label="item.label"
                :value="item.value"
                :key="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!--            <el-form-item label="上传时间" prop="times">-->
          <!--              <el-date-picker-->
          <!--                size="medium"-->
          <!--                style="width:100%"-->
          <!--                v-model="queryParams.times"-->
          <!--                value-format="yyyy-MM-dd"-->
          <!--                start-placeholder="开始时间"-->
          <!--                end-placeholder="结束时间"-->
          <!--                type="daterange"-->
          <!--              ></el-date-picker>-->
          <!--            </el-form-item>-->
        </el-form>
        <div class="mt15 flex align-items-c justify-content-b">
          <el-button size="medium" type="primary" @click="handleQuery"
            >查询</el-button
          >
          <el-button size="medium" @click="resetQuery">重置</el-button>
          <el-button size="medium" type="primary" @click="handleAdd"
            >新增</el-button
          >
        </div>
      </div>
    </div>
    <r-table
      :columns="tableConfig.columns"
      :data="tableData"
      :deletion="false"
      :total="tableConfig.total"
      @currentChange="handleCurrentChange"
      @sizeChange="handleSizeChange"
      :currentPage="tableConfig.currentPage"
      :pageSize="tableConfig.pageSize"
    />

    <!-- 用户新增弹窗 -->
    <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,
  resetPassword
} 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: []
      },
      statusList: [{ label: '启用', value: 0 }, { label: '停用', value: 1 }],
      // 表格配置项
      tableConfig: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
        columns: [
          { 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: '操作',
            isRedraw: true,
            render: (h, params) => {
              return h('div', [
                h(
                  'el-button',
                  {
                    props: {
                      type: 'text',
                      size: 'mini',
                      icon: 'el-icon-edit-outline',
                      title: '编辑'
                    },
                    class: 'normal-button',
                    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',
                      icon: 'el-icon-remove-outline',
                      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',
                      icon: 'el-icon-refresh-right'
                    },
                    class: 'normal-button',
                    on: { click: () => this.handleResetPassword(params.row) }
                  },
                  '重置密码'
                ),
                h(
                  'el-button',
                  {
                    props: {
                      type: 'text',
                      size: 'mini',
                      style: 'color: #F56C6C',
                      icon: 'el-icon-delete'
                    },
                    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 => {
          this.tableData = response.content.content.list || []
          this.tableConfig.total = response.content.content.total || 0
        })
        .catch(() => {
          this.$message.error('获取用户列表出错')
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleQuery() {
      this.queryParams.page = 1
      this.getUserList()
    },
    resetQuery() {
      this.$refs.queryParams.resetFields()
      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 => {
          this.currentUserData = response.content.content || {}
          this.dialogVisible = true
        })
        .catch(() => {
          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 => {
          this.currentUserData = response.content.content || {}
          this.dialogVisible = true
        })
        .catch(() => {
          this.$message.error('获取用户详情出错')
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleSubmit() {
      this.getUserList() // 提交后刷新列表
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getUserList()
    },
    handleCurrentChange(val) {
      this.queryParams.page = val
      this.getUserList()
    },
    handleDelete(row) {
      this.$messageBox(
        () => {
          this.loading = true
          // 将id放入数组中传递
          deleteUser([row.id])
            .then(() => {
              this.$message.success('删除成功')
              this.getUserList()
            })
            .catch(() => {
              this.$message.error('删除用户出错')
            })
            .finally(() => {
              this.loading = false
            })
        },
        '确认删除该用户吗？',
        'warning',
        '警告'
      )
    },
    handleToggleStatus(row) {
      const statusText = row.status === 0 ? '停用' : '启用'

      this.$messageBox(
        () => {
          // 调用changeUserStatus接口
          const newStatus = row.status === 0 ? 1 : 0 // 切换状态
          changeUserStatus({
            userId: row.id,
            status: newStatus
          })
            .then(() => {
              this.$message.success(`${statusText}成功`)
              this.getUserList() // 刷新列表
            })
            .catch(() => {
              this.$message.error(`${statusText}用户出错`)
            })
        },
        `确认${statusText}该用户吗？`,
        'warning',
        '提示'
      )
    },
    handleResetPassword(row) {
      this.currentUserId = row.id
      this.$messageBox(
        () => {
          // 调用resetPassword接口
          resetPassword({
            userId: row.id
          }).then(() => {
            this.$message.success('重置密码成功')
            this.handleQuery() // 刷新列表
          })
        },
        '确认重置该用户的密码吗？',
        'warning',
        '提示'
      )
    }
  }
}
</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>
