<script lang="ts" setup>
import {ref} from 'vue'
import {onMounted} from "vue";
import myAxios from "../../API/myAxios.ts";
import {Action, ElMessage, ElMessageBox} from "element-plus";
import { HomeOutlined, UserOutlined } from '@ant-design/icons-vue';


const tableData = ref([]);

onMounted(() => {
  getUserList();
})



const onSearch = () => {
  getUserList();
}
const onReset = () => {
  searchParams.value.username = '';
  searchParams.value.phone='';
  getUserList();
}

const searchParams = ref({
  current: 1,
  pageSize: 10,
  username: '',
  phone: '',
  userStatus:0
});

const createTime = (row: any)=> {
  let data = row.createTime;
  return data.slice(0,16).replace('T',`~`)
}


const total= ref(0);
const getUserList = async () => {
  const res:any = await myAxios.get("/user/search",{
    params: {
      current: searchParams.value.current,
      pageSize: searchParams.value.pageSize,
      username: searchParams.value.username,
      phone: searchParams.value.phone,
      userStatus: searchParams.value.userStatus
    }})
  if(res.code === 0 && res.data) {
    tableData.value = res.data;
    total.value = parseInt(res.data.total)
  } else {
    ElMessage({
      type:"error",
      message: `加载数据失败：${res.message}`
    })
  }
}




const doDelete =async (id:string) => {
  const res:any = await myAxios.post("/user/delete",{id:id})
  ElMessage({
    showClose:true,
    type:res.code === 0 ? 'success' : "error",
    message:res.code === 0 ? '删除成功' : `删除失败:${res.message}`
  })
  if(res.code === 0 && res.data) {
    await getUserList();
  }
}



const doBan =async (id:string, isBan: boolean) => {
  const res:any = await myAxios.post("/user/update",{id:id, userRole: isBan ? 2 :0})
  ElMessage({
    showClose:true,
    type:res.code === 0 ? 'success' : "error",
    message:res.code === 0 ? '操作成功' : `操作失败:${res.message}`
  })
  if(res.code === 0 && res.data) {
    await getUserList();
  }
}

//分页
const handleCurrentChange = (current: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: current
  }
}
const handleSizeChange = (size: number) => {
  searchParams.value = {
    ...searchParams.value,
    pageSize: size
  }
  getUserList();
}



if(searchParams.value.userStatus===1){

}
/**
 * 新增
 * */
const dialogVisible = ref(false)
const editorDialogVisible = ref(false)
const addForm = ref({
  avatarUrl: '',
  userAccount: '',
  userPassword: '',
  username: '',
})
const editorForm:any = ref({
  avatarUrl: '',
  email: '',
  gender: 0,
  id: 0,
  isDelete: 0,
  phone: '',
  updateTime: '',
  userAccount: '',
  userPassword: '',
  userRole: 0,
  userStates: 0,
  username: ''
})

const onAdd = async () => {
  try {
    const obj = {
      id: Math.floor(Math.random() * 1000),
      ...addForm.value
    }
    console.log('Adding user:', obj); // 添加调试输出
    const response = await myAxios.post('/user/add', obj)
    console.log('Response:', response); // 添加调试输出
    if (response.status === 200) {
      tableData.value.push(obj)
      dialogVisible.value = false
      ElMessage.success('添加成功')
    }
  } catch (error) {
    console.error('Error adding user:', error)
    ElMessage.error('添加失败，请稍后再试')
  }
}

/**
 * 编辑
 *
 * */

const editorRow = (e: any) => {
  editorDialogVisible.value = true;
  editorForm.value = { ...e }; // Clone the object to avoid mutating the original data
};

const onEditor = async () => {
  try {
    const findIndex = tableData.value.findIndex((item) => item.id === editorForm.value.id);
    tableData.value[findIndex] = { ...editorForm.value }; // Update the local state

    // Make the API call to update the user on the server
    await myAxios.post('/user/update', editorForm.value);

    editorDialogVisible.value = false;
    ElMessage.success('更改成功');
  } catch (error) {
    console.error('Failed to update user:', error);
    ElMessage.error('更新失败，请检查您的网络连接或稍后再试。');
  }
};

</script>

<template>
  <!--面包屑-->
  <a-breadcrumb class="header">
    <a-breadcrumb-item href="">
      <home-outlined />
    </a-breadcrumb-item>
    <a-breadcrumb-item href="">
      <user-outlined />
      <span>{{ $route.path }}</span>
    </a-breadcrumb-item>
    <a-breadcrumb-item>{{ $route.name }}</a-breadcrumb-item>
  </a-breadcrumb>
  <!--搜索部分-->
  <div class="search-box">
    <el-form
        :inline="true"
        :model="searchParams"
    >
      <el-form-item label="跑腿姓名" class="search">
        <el-input v-model="searchParams.username" />
      </el-form-item>
      <el-form-item label="手机号" class="search">
        <el-input v-model="searchParams.phone" />
      </el-form-item>
      <el-button type="primary" @click="onSearch" style="margin-top: 10px" color="#4e58fd">搜索</el-button>
      <el-button type="primary" @click="onReset" style="margin-top: 10px" color="#4e58fd">重置</el-button>
      <!--新增-->
      <el-button type="primary" @click="dialogVisible = true" style="margin-top: 10px" color="#4e58fd">新增</el-button>
      <el-dialog
          v-model="dialogVisible"
          title="添加"
          width="500"
      >
        <el-form>
          <el-form-item label="ID" label-width="100">
            <el-input v-model="addForm.avatarUrl"></el-input>
          </el-form-item>
          <el-form-item label="用户名" label-width="100">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="账户" label-width="100">
            <el-input v-model="addForm.userAccount"></el-input>
          </el-form-item>
          <el-form-item label="密码" label-width="100">
            <el-input v-model="addForm.userPassword"></el-input>
          </el-form-item>
          <el-form-item label="状态" label-width="100">
            <el-select v-model="addForm.avatarUrl">
              <el-option value="0" label="管理员">管理员</el-option>
              <el-option value="1" label="普通用户">普通用户</el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="onAdd">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>
      <!--修改操作-->
      <el-dialog
          v-model="editorDialogVisible"
          title="编辑"
          width="500"
      >
        <el-form>
          <el-form-item label="ID" label-width="100">
            <el-input v-model="editorForm.avatarUrl"></el-input>
          </el-form-item>
          <el-form-item label="用户名" label-width="100">
            <el-input v-model="editorForm.username"></el-input>
          </el-form-item>
          <el-form-item label="日期" label-width="100">
            <el-input v-model="editorForm.userAccount"></el-input>
          </el-form-item>
          <el-form-item label="地址" label-width="100">
            <el-input v-model="editorForm.userPassword"></el-input>
          </el-form-item>
          <el-form-item label="状态" label-width="100">
            <el-select v-model="editorForm.avatarUrl">
              <el-option value="1" label="普通用户">普通用户</el-option>
              <el-option value="0" label="管理员">管理员</el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="editorDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="onEditor">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>
    </el-form>
  </div>

  <div class="table">
    <el-table :data="tableData" style="width: 100%;height: 80%" border stripe>
      <el-table-column label="骑手ID" prop="id"/>
      <el-table-column label="骑手姓名" prop="username"/>
      <el-table-column label="手机号" prop="phone"/>
      <el-table-column label="状态" prop="userStatus" >
        <template #default="scope">
          <div v-if="scope.row.userRole === 1">
            <el-tag type="success">跑腿中</el-tag>
          </div>
          <div v-else-if="scope.row.userRole === 0">
            <el-tag type="success">跑腿中</el-tag>
          </div>
          <div v-else-if="scope.row.userRole === 2">
            <el-tag type="warning">被封禁</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="订单总量" prop="createtime" :formatter="createTime"/>
      <el-table-column align="center" label="操作">

        <template #default="scope">
          <el-button link size="small" type="warning" :disabled="scope.row.userRole === 1"
                     @click="doBan(scope.row.id, scope.row.userRole !== 2)">
            {{scope.row.userRole === 2? '解封' : '封禁'}}
          </el-button>
          <el-button link size="small" type="info" @click="editorRow(scope.row)">编辑</el-button>
          <el-button link size="small" type="danger" :disabled="scope.row.userRole === 'admin'"
                     @click="doDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
          background
          :page-size="searchParams.pageSize"
          :current-page="searchParams.current"
          layout="total,sizes, prev, pager, next,jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="pagination"
          :page-sizes="[10.20]"
      />
    </div>
  </div>
</template>

<style scoped>
.header {
  width: 100%;
  height: 30px;
  background-color: white;
}
h4 {
  display: inline-block;
  margin-left: 10px;
}
.search {
  margin-top: 10px;
  float: left;
  width: 20%;
  height: 7%;
}
.table {
  width: 100%;
  height: 80%;
}

</style>