<template xmlns="">
  <div class="main">
    <div class="header">
      <div class="input">
        <a-input class="first-input" v-model:value="value1" addonBefore="关键字" placeholder="请输入用户账号或姓名" />
        <a-input class="second-input" v-model:value="value2" addonBefore="手机号码" placeholder="请输入手机号码"/>
        <a-select
            placeholder="请选择状态"
            ref="select"
            style="width: 120px"
        >
          <a-select-option value="启用">启用</a-select-option>
          <a-select-option value="禁用">禁用</a-select-option>
        </a-select>
      </div>
      <div class="edit">
        <a-button class="query-button" @click="searchUser"><SearchOutlined />查询</a-button>
        <a-button class="add-button" type="primary" @click="showAddDiaLog"><PlusOutlined />新增用户</a-button>
      </div>
    </div>


    <!--新增用户对话框-->
    <a-modal v-model:open="AddDiaLog" cancel-text="取消" ok-text="确认" title="新增用户" @cancel="addCancel" @ok="addOk">
      <div>
        <div>用户名：<a-input v-model:value="addData.username" style="width: 250px; margin-bottom: 10px" /></div>
        <div style="margin-left: 15px">密码：<a-input v-model:value="addData.password" style="width: 250px; margin-bottom: 10px" type="password"/></div>
        <div style="margin-left: 15px">地址：<a-input v-model:value="addData.address" style="width: 250px; margin-bottom: 10px" /></div>
        <div style="margin-left: 15px">电话：<a-input v-model:value="addData.phone" style="width: 250px; margin-bottom: 10px" /></div>
        <div style="margin-left: 15px">邮箱：<a-input v-model:value="addData.email" style="width: 250px; margin-bottom: 10px" /></div>
        <div style="margin-left: 15px">性别：
          <a-radio-group v-model:value="addData.sex" style="margin-bottom: 10px">
            <a-radio :value="1">男</a-radio>
            <a-radio :value="0">女</a-radio>
          </a-radio-group></div>
        <div style="margin-left: 15px">年龄：<a-input v-model:value="addData.age" style="width: 250px" type="number" /></div>

      </div>
    </a-modal>

    <!--删除用户对话框-->
    <a-modal v-model:open="DeleteDiaLog" cancel-text="取消" ok-text="确认" title="删除用户" @cancel="deleteCancel" @ok="deleteOk">
      <p>是否要删除xxx数据？</p>
    </a-modal>

    <!--修改用户对话框-->
    <a-modal
        v-model:open="EditDiaLog"
        title="编辑"
        @on-ok="editOk"
        @on-cancel="editCancel">
      <div style="">
        <div style="margin-bottom: 10px">
            <span>
              用户名：<a-input v-model:value="updateData.username" style="width: 180px" />
            </span>
          <span style="margin-left: 20px">
              电话：<a-input v-model:value="updateData.phone" placeholder="Enter something..." style="width: 180px" />
            </span>
        </div>
        <div style="margin-bottom: 10px">
            <span>
              性别：
              <a-radio-group v-model="sex">
                <a-radio label="男"></a-radio>
                <a-radio label="女"></a-radio>
              </a-radio-group>
            </span>
          <span style="margin-left: 98px">
            角色：
            <a-select v-model="roleSingle" style="width:200px">
              <a-select-option v-for="item in roleList" :key="item.value" :value="item.value">{{ item.label }}</a-select-option>
            </a-select>
          </span>
        </div>
        <div style="margin-bottom: 10px">邮箱：<Input v-model="updateData.email" style="width: 435px" /></div>
        <div style="margin-bottom: 10px">地址：<Input v-model="updateData.address" style="width: 435px" /></div>
        <div style="margin-bottom: 10px">简介：<Input v-model="updateData.description" style="width: 435px" type="textarea" /></div>
      </div>
    </a-modal>


    <!--表格内容-->
    <div class="table">
      <a-table :columns="columns" :dataSource="data"/>
    </div>
  </div>
</template>

<script setup>
import {computed, onMounted, reactive, ref} from 'vue';
import {DeleteOutlined, EditOutlined, PlusOutlined, SearchOutlined} from '@ant-design/icons-vue';
import {message} from "ant-design-vue";
import requests from "@/public/request.js";

const value1 = ref('');
const value2 = ref('');
const AddDiaLog = ref(false);
const DeleteDiaLog = ref(false);
const EditDiaLog = ref(false);
const DeleteId = ref(0);
let dataSource = ref([]);
let data = ref([]);
const dataLoaded = ref(false);
const token = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxNiIsImV4cCI6MTcwNjc4OTgwNH0.Cx4NOfPh3QXH-pYRCSHxpUjdeUxBZABVb5Z82gK8sfI"
const requestBody = {
  "page": null,
  "limit": null,
  "search": null,
  "role": null
}
const AllUser = reactive({
  page:1,
  limit: 10,
  search: null,
  role: null
})

const loadingTable = ref(true)
const sex = ref('男')


const updateData = reactive({
  id: 0,
  username: '',
  address: '',
  phone: '',
  email: '',
  age: '',
  signature: '',
  sex: '',
  avatar: '',
  nickname: '',
  description: '',
  enabled: true,
  isExpired: false,
  passwordExpired: false,
  recommend: false,
  isLocked: false
})


const roleSingle = ref(1);

const roleList= reactive([
  {
    value: 1,
    label: '管理员'
  },
  {
    value: 2,
    label: '老师'
  },
  {
    value: 3,
    label: '学生'
  }
])


const userLock = reactive({
  id: -1,
  isLock: 1
})


const states = reactive({
  data:[],
  role:[],
})


/**
 * 配置代码
 */
message.config({
  background: true
})
function setRowClassName(record, index) {
  return 'custom-record';
}

onMounted(() => {
  getAll()
})


function getAll() {
  requests.userAllCurrent(AllUser,token).then((res)=>{
    console.log(res)
    // states.data = res.data.data
    // console.log(res.data.data)
    loadingTable.value = false
    for (let i = 0; i < res.data.data.length; i++) {
      states.data[i] = res.data.data[i].user
      states.role[i] = res.data.data[i].role.rid
    }
    console.log("getAll:",states.data.length)
  })
}




/*新增用户*/
const addData = reactive({
  username: '',
  password: '',
  address: '',
  phone: '',
  email: '',
  sex:1,
  age: ''
})

const showAddDiaLog = () => {
  AddDiaLog.value = true;
  addData.username = '';
  addData.password = '';
  addData.address = '';
  addData.phone = '';
  addData.email = '';
  addData.sex = 1;
  addData.age = '';
};

function addOk () {
  if (sex.value === '男') {
    addData.sex = 1
  }else {
    addData.sex = 0
  }
  requests.userAdd(addData, token).then((res)=>{
    console.log(res.data)
    if (res.data.code===200) {
      message.success('新增成功')
      getAll();
      AddDiaLog.value = false;
    }
    else {
      message.error('新增失败')
    }
  })
}



function addCancel () {
  message.info('取消新增')
}



/*删除用户*/
const showDeleteDiaLog = (record, index) => {
  DeleteDiaLog.value = true;
  DeleteId.value = record.id;
};

function deleteOk() {
  DeleteDiaLog.value = false;
  console.log(DeleteId.value)
  requests.userDelete(DeleteId.value, token).then((res) => {
    console.log("deleteResult:", res)
    if (res.data.code === 200) {
      message.success('删除成功')
    } else {
      message.error('删除失败')
    }
  })
}

function deleteCancel(){
  DeleteDiaLog.value = false;
  message.info('取消删除')
}



/*编辑用户*/
const showEditDiaLog = (record, index) => {
  EditDiaLog.value = true
  updateData.id = record.id
  updateData.username = record.username
  updateData.address = record.address
  updateData.phone = record.phone
  updateData.email = record.email
  updateData.age = record.age
  updateData.signature = record.signature
  updateData.sex = record.sex
  updateData.avatar = record.avatar
  updateData.nickname = record.nickname
  updateData.description = record.description
  roleSingle.value = states.role[index]
  if (record.sex === 1) {
    sex.value = '男'
  }else {
    sex.value = '女'
  }
}
function editOk(){
  loadingTable.value = true
  EditDiaLog.value = false
  requests.userEdit(updateData,token).then((res)=>{
    console.log("editResult:",res)
    console.log("updateData:",updateData)
    if (res.data.code === 200) {
      getAll()
      message.success('修改成功')
    }
    else {
      loadingTable.value = false
      message.error('修改失败')

    }
  })

}
function editCancel(){
    EditDiaLog.value = false;
}



/*查询用户*/
const searchData = reactive({
  username: '',
  phone: ''
})

function searchUser(){
  loadingTable.value = true
  if (searchData.username === '' && searchData.phone === '') {
    getAll()
  }
  else {
    requests.userCurrent(searchData,token).then((res)=>{
      loadingTable.value = false
      console.log("searchResult:",res)
      if (res.data.code === 200) {
        states.data = []
        states.data[0] = res.data.data.user
        message.success('查询成功')
        console.log(loadingTable.value)
      }
      else {
        message.error(res.data.message)
      }
    })
  }
}

const columns = [
  {
    title: '序号',
    dataIndex: 'id',
    key: 'id',
  },
  {
    title: '用户名',
    dataIndex: 'username',
    key: 'username',
  },
  {
    title: '账户昵称',
    dataIndex: 'nickname',
    key: 'nickname',
  },
  {
    title: '电话',
    key: 'phone',
    dataIndex: 'phone',
  },
  {
    title: '用户状态',
    dataIndex: 'enabled',
    key: 'enabled',
  },
  {
    title: '更新时间',
    key: 'updatedAt',
    dataIndex: 'updatedAt'
  }
];

const rowSelection = {
  onChange: (selectedRowKeys, selectedRows) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
  },
  getCheckboxProps: record => ({
    disabled: record.name === 'Disabled User',
    name: record.name,
  }),
};

async function fetchData() {
  try {
    const queryData = await requests.userAllCurrent(
        {
          page: null,
          limit: null,
          search: null,
          role: null
        },
        "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIiwiZXhwIjoxNzA2ODU0Nzk1fQ.A5kh3jSxbkvHmfEyp9MTp9--N0HdoiEREkKdPgcfXOk"
    );
    console.log(queryData.data); // 访问数据
    dataSource.value = queryData.data.data;
    dataLoaded.value = true;
    for (let i = 0; i <= dataSource.value.count; i++) {
      if (dataSource.value.users[i].user.updatedAt === null) {
        dataSource.value.users[i].user.updatedAt = "null"
      }
      data.value.push({
        username: dataSource.value.users[i].user.username,
        nickname: dataSource.value.users[i].user.nickname,
        phone: dataSource.value.users[i].user.phone,
        enabled: dataSource.value.users[i].user.enabled,
        updatedAt: dataSource.value.users[i].user.updatedAt,
      });
    }
    console.log(data.value);
  } catch (error) {
    console.error(error);
  }
}
console.log(dataSource)

// 组件挂载时调用 fetchData
onMounted(() => {
  fetchData();
});
</script>


<style scoped>
.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: auto;
}

.header {
  display: flex;
}

.input {
  width: 35vw;
  margin-top: 2vh;
  margin-bottom: 1vh;
  display: flex;
  flex-direction: row;
}

.first-input {
  margin-right: 1vw;
  margin-left: 1vw;
}

.second-input {
  margin-right: 1vw;
}

.edit {
  margin-top: 2vh;
  width: 20vw;
  display: flex;
}

.query-button {
  margin-left: 4vw;
  margin-right: 1vw;

}

.delete-button {
  background-color: #CD5C5C;
  color: white;
  margin-left: 1vw;
}

.table {
  width: 100%;
  height: auto;
  margin-top: 2vh;
}
</style>
