<template>
  <div class="m-user-table">
    <div class="header">
      <el-form :inline="true" :model="formInline" ref="ruleFormRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formInline.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" :icon="Search">查询</el-button>
          <el-button @click="reset(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="footer">
      <div class="util">
        <el-button type="primary" @click="addHandler">
          <el-icon>
            <Plus />
          </el-icon>
          新增用户
        </el-button>
      </div>
      <div class="table-inner">
        <el-table v-loading="loading" :data="tableData" style="width: 100%;height: 100%" border>
          <el-table-column prop="username" label="用户名" align="center" width="100" />
          <el-table-column prop="nickname" label="昵称" align="center" />
          <el-table-column prop="sex" label="性别" align="center">
            <template #default="scope">
              <span v-if="scope.row.sex === 0">女</span>
              <span v-else-if="scope.row.sex === 1">男</span>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="password" label="密码" align="center" width="120"/> -->
          <el-table-column prop="role" label="关联角色" align="center" width="120">
            <template #default="scope">
              <span v-if="scope.row.role === 1">超级管理员</span>
              <span v-else-if="scope.row.role === 2">管理员</span>
            </template>
          </el-table-column>
          <el-table-column prop="phone" label="手机号" align="center" width="120" />
          <el-table-column prop="status" label="用户状态" align="center">
            <template #default="scope">
              <el-switch inline-prompt :model-value="scope.row.status" :active-text="'启用'" :inactive-text="'禁用'"
                :active-value="1" :inactive-value="0" @change="changeStatus(scope.row)" />
            </template>
          </el-table-column>
          <el-table-column prop="describe" :show-overflow-tooltip="true" width="180" label="用户描述" align="center" />
          <el-table-column prop="createTime" label="创建时间" align="center" width="180">
            <template #default="{ row }">
              {{ dformatTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="operator" label="操作" width="200px" align="center" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" icon="Edit" @click="editHandler(scope.row)">
                编辑
              </el-button>
              <el-button @click="del(scope.row)" type="danger" size="small" icon="Delete">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination">
        <el-pagination v-model:currentPage="currentPage1" :page-size="10" background
          layout="total, sizes, prev, pager, next, jumper" :total="1000" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>

    <UserDialog ref="userDialog" :callback="addUser" :editCallback="editUser" />
  </div>
</template>
<script lang="ts" setup>
import { ElMessageBox, ElMessage, FormInstance } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { onBeforeMount, onMounted, reactive, ref } from 'vue'
import { useUserStore } from "@/store/modules/user"
import { userData } from '@/mock/system'
import UserDialog from './userDialog.vue'
import systemApi from '@/api/system'
import { formatTime } from '@/utils'

const tableData = ref([{}])
const dialogVisible = ref(false)
const userDialog = ref()
const ruleFormRef = ref<FormInstance>()
const formInline = reactive({})
const loading = ref(true)
const currentPage1 = ref(1)
const UserStore = useUserStore()

onBeforeMount(() => {
  systemApi.userList({ "userName": UserStore.username }).then((resp) => {
    tableData.value = resp.data.result;
  });
});

const onSubmit = () => {
  console.log('submit!', formInline)
  loading.value = true
  setTimeout(() => {
    loading.value = false
  }, 1000)
}

const reset = (formEl: FormInstance | undefined) => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
  }, 1000)
}

const dformatTime = (time) => {
  const date = new Date(time);
  const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
  return formattedDate;
}

const addHandler = () => {
  userDialog.value.show()
}
const editHandler = (row) => {
  userDialog.value.show(row)
}

const del = (row) => {
  ElMessageBox.confirm('你确定要删除当前项吗?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  })
    .then(async () => {
      systemApi.delUser({ "username": row.username }).then((resp) => {
        console.log(resp);
        if (resp.data.code == 200) {
          let index = tableData.value.indexOf(row);
          tableData.value.splice(index, 1);
          ElMessage({
            message: "删除成功",
            type: 'success',
            duration: 3000
          });
        } else {
          ElMessage({
            message: "删除失败",
            type: 'error',
            duration: 3000
          });
        }
      });
    })
    .catch(() => { })
}


const changeStatus = (row) => {
  if (row.username != undefined) {
    ElMessageBox.confirm(
      `确定要${!row.status ? '禁用' : '启用'} ${row.username} 账户吗？`,
      '温馨提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
      .then(async () => {
        systemApi.editUserStatus({ "username": row.username }).then((resp) => {
          if (resp.data.result) {
            row.status = row.status == 0 ? 1 : 0;
          }
        });
      })
  }
}

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
}

const handleCurrentChange = (val: number) => {
  currentPage1.value = val
}

const addUser = (user: any) => {
  tableData.value.push(user)
}

const editUser = (user: any) => {
  const index = tableData.value.findIndex(item => item.username == user.username);
  if (index != -1) {
    user.createTime=tableData.value[index].createTime;
    tableData.value[index] = user;
  }else{
    console.log("未找到对象");
  }
}

onMounted(() => {
  setTimeout(() => {
    loading.value = false
  }, 1000)
})

</script>
<style lang="scss" scoped>
@import "../index";
</style>
