<template xmlns="">
  <div class="flex flex-col w-full h-auto">
    <div class="flex">
      <div class="w-36 ml-4 mt-4 flex">
        <a-input v-model:value="searchData.id" class="h-8 border-gray-300 rounded-md"  placeholder="请输入用户id"/>
      </div>
      <div class="mt-4 flex">
        <a-button class="ml-4 mr-4 flex justify-center items-center" @click="searchUser">
          <SearchOutlined/>
          查询
        </a-button>
        <a-button class="text-blue-50 bg-blue-500 flex justify-center items-center" type="primary" @click="showAddDiaLog">
          <PlusOutlined/>
          新增用户
        </a-button>
      </div>
    </div>


    <!--新增用户对话框-->
    <a-modal v-model:open="AddDiaLog" cancel-text="取消" ok-text="确认" title="新增用户" @cancel="addCancel"
             @ok="addOk">
      <a-form>
        <a-form-item class="ml-6 mt-4">
          <span style="color:red; font-size: 20px">*</span>
          用户名
          <a-input v-model:value="addData.username" class="h-8 w-2/3 border-gray-300 rounded-md"/>
        </a-form-item>
        <a-form-item class="ml-6">
          <span style="color:red; font-size: 20px">*</span>
          密码：
          <a-input v-model:value="addData.password" class="h-8 w-2/3 border-gray-300 rounded-md" type="password"/>
        </a-form-item>
        <a-form-item class="ml-6">
          <span style="color:red; font-size: 20px">*</span>
          地址：
          <a-input v-model:value="addData.address" class="h-8 w-2/3 border-gray-300 rounded-md"/>
        </a-form-item>
        <a-form-item class="ml-6">
          <span style="color:red; font-size: 20px">*</span>
          电话：
          <a-input v-model:value="addData.phone" class="h-8 w-2/3 border-gray-300 rounded-md"/>
        </a-form-item>
        <a-form-item class="ml-6">
          <span style="color:red; font-size: 20px">*</span>
          邮箱：
          <a-input v-model:value="addData.email" class="h-8 w-2/3 border-gray-300 rounded-md"/>
        </a-form-item>
        <a-form-item class="ml-6">
          <span style="color:red; font-size: 20px">*</span>
          年龄：
          <a-input v-model:value="addData.age" class="h-8 w-2/3 border-gray-300 rounded-md" type="number"/>
        </a-form-item>
        <a-form-item class="ml-6">
          <span style="color:red; font-size: 20px">*</span>
          性别：
          <a-radio-group v-model:value="addData.sex">
            <a-radio :value="1">男</a-radio>
            <a-radio :value="0">女</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>

    <!--修改用户对话框-->
    <a-modal
        v-model:open="EditDiaLog"
        cancel-text="取消"
        ok-text="确定"
        style="width: 850px"
        title="修改用户"
        @cancel="editCancel"
        @ok="editOk"
    >
      <a-form>
        <div style="display: flex; margin-top: 1vw">
          <a-form-item label="用户名" style="margin-left: 1vw">
            <a-input v-model:value="updateData.username" style="width: 12vw; margin-left: 1.2vw"/>
          </a-form-item>
          <a-form-item label="手机号码" style="margin-left: 3vw">
            <a-input v-model:value="updateData.phone" style="width: 12vw; margin-left: 2vw"/>
          </a-form-item>
        </div>
        <div style="display: flex">
          <a-form-item label="地址" style="margin-left: 1vw">
            <a-input v-model:value="updateData.address" style="width: 12vw; margin-left: 2vw"/>
          </a-form-item>
          <a-form-item label="邮箱" style="margin-left: 3vw">
            <a-input v-model:value="updateData.email" style="width: 12vw; margin-left: 3.6vw"/>
          </a-form-item>
        </div>
        <div style="display: flex">
          <a-form-item label="年龄" style="margin-left: 1vw">
            <a-input v-model:value="updateData.age" style="width: 12vw; margin-left:2vw"/>
          </a-form-item>
          <a-form-item label="性别" style="margin-left: 3vw">
            <a-input v-model:value="updateData.sex" style="width: 12vw; margin-left: 3.6vw"/>
          </a-form-item>
        </div>
        <div style="display: flex">
          <a-form-item label="头像地址" style="margin-left: 1vw">
            <a-input v-model:value="updateData.avatar" style="width: 12vw; margin-left: 0.5vw"/>
          </a-form-item>
          <a-form-item label="用户是否可用" style="margin-left: 3vw">
            <a-switch v-model:checked="updateData.enabled" style="width: 3vw; margin-left: 0.5vw"/>
          </a-form-item>
        </div>
        <div style="display: flex">
          <a-form-item label="用户是否被推荐" style="margin-left: 1vw">
            <a-switch v-model:checked="updateData.recommend" style="width: 3vw; margin-left: 0.5vw"/>
          </a-form-item>
        </div>
      </a-form>
    </a-modal>


    <!--表格内容-->
    <div style=" width:100%; height:auto; margin-top:2vh;">
      <a-table :columns="columns" :dataSource="states.data" :loading="loadingTable" :row-selection="rowSelection" :rowKey="record => record.id">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key==='id'">
            {{ record.id }}
          </template>
          <template v-else-if="column.key === 'enabled'">
            <a-tag v-if="record.enabled === true" :bordered="false" color="success">启用</a-tag>
            <a-tag v-if="record.enabled === false" :bordered="false" color="error">禁用</a-tag>
          </template>
          <template v-else-if="column.key==='createdAt'">
            {{ record.createdAt }}
          </template>
          <template v-else-if="column.key==='updateAt'">
            {{ record.updatedAt }}
          </template>
          <template v-else-if="column.key === 'isDelete'">
            {{ record.isDelete }}
          </template>
          <template v-else-if="column.key==='action'">
            <span style="margin-left: 10px; display: flex">
              <a-button class="text-blue-500 flex justify-center items-center" size="small" type="text" @click="() => showEditDiaLog(record)"><EditOutlined/>修改</a-button>
              <a-button class="text-blue-500 flex justify-center items-center" size="small" type="text" @click="() => showDeleteConfirm(record)"><DeleteOutlined/>删除</a-button>
            </span>
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>

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

const AddDiaLog = ref(false);
const EditDiaLog = ref(false);
let dataSource = ref([]);
let data = ref([]);
const token = window.localStorage.getItem('token')
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: '',
  username: '',
  address: '',
  phone: '',
  email: '',
  age: '',
  signature: '',
  sex: '',
  avatar: '',
  //nickname: '',
  //description: '',
  enabled: true,
  isExpired: false,
  passwordExpired: false,
  recommend: false,
  isLocked: false,
  //createdAt:'',
  //updateAt:'',
  isDelete:false,
})


const roleSingle = ref(1);


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


function setRowClassName(record, index) {
  return 'custom-row';
}

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


/**
 * 配置代码
 */
message.config({
  background: true
})

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


function getAll() {
  requests.userCurrent(null, 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)
  })
}


/*
function getAll() {
  requests.userAllCurrent(AllUser, token).then((res) => {
    console.log(res);
    loadingTable.value = false;

    // 直接更新整个数组来确保响应性
    states.data = res.data.data.map(item => item.user);
    states.role = res.data.data.map(item => item.role.rid);

    console.log("getAll:", states.data.length);
  });
}

*/





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

function 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('新增成功')
      AddDiaLog.value = false;
      getAll();
      loadingTable.value = true
    } else {
      message.error('新增失败')
    }
  })
}


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


/*删除用户*/
const deleteId = reactive({
  id: -1
})

const showDeleteConfirm = (record) => {
  console.log("delete Dialog")
  Modal.confirm({
    title: '删除数据',
    icon: createVNode(ExclamationCircleOutlined),
    content: '确认删除这条数据吗',
    okText: '确认',
    cancelText: '取消',
    onOk: () => {

      deleteId.id = record.id
      requests.userDelete(deleteId.id, token)
          .then(response => {
            console.log('删除成功');
            message.success("删除成功")
            getAll()
          })
          .catch(error => {
            console.error('删除失败', error);
            message.error("删除失败")
            getAll()
          })

    }

  });

};


/*编辑用户*/
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
 // updateData.isDelete = record.isDelete
  updateData.recommend = record.recommend
  updateData.enabled = record.enabled
  // updateData.isExpired = record.isExpired
  roleSingle.value = states.role[index]
  if (record.sex === 1) {
    sex.value = '男'
  } else {
    sex.value = '女'
  }
}

function editOk() {
  loadingTable.value = true
  requests.userEdit(updateData, token).then((res) => {
    console.log("editResult:", res)
    console.log("updateData:", updateData)
    if (res.data.code === 200) {
      //getAll()
      EditDiaLog.value = false
      message.success('修改成功')
    } else {
      loadingTable.value = false
      message.error('修改失败')

    }
  })

}

function editCancel() {
  EditDiaLog.value = false;
  message.info('取消修改')
}


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

function searchUser() {
  loadingTable.value = true
  if (searchData.id === '') {
    getAll()
  } else {
    requests.userCurrent(searchData, token).then((res) => {
      loadingTable.value = false
      console.log("searchResult:", res)
      if (res.data.code === 200) {
        console.log("success")
        dataSource.value = res.data.data;
        //console.log("H1:", dataSource.value.role)
        const user = dataSource.value.user;
        const role = dataSource.value.role;
        if (user.updatedAt === null) {
          user.updatedAt = "null";
        }

        // 现在 'user' 已经定义，我们可以安全地访问它的属性
        states.data = []
        states.data.push({
          username: user.username,
          nickname: user.nickname,
          phone: user.phone,
          enabled: user.enabled,
          createdAt: user.createdAt,
          updatedAt: user.updatedAt,
          id: user.id,
          isDelete: user.isDelete,
          address: user.address,
          sex: user.sex,
          age: user.age,
          email: user.email,
          avatar: user.avatar,
          recommend: user.recommend
        });
        message.success('查询成功')
        console.log(loadingTable.value)
      } else {
        console.log("nil")
        message.error(res.data.message)
      }
    })
  }
}

const columns = [
  {
    title: '序号',
    dataIndex: 'id',
    key: 'id',
  },
  {
    title: '用户名',
    dataIndex: 'username',
    key: 'username',
  },
  {
    title: '电话',
    key: 'phone',
    dataIndex: 'phone',
  },
  {
    title: '用户状态',
    dataIndex: 'enabled',
    key: 'enabled',
  },
  {
    title: '创建时间',
    key: 'createdAt',
    dataIndex: 'createdAt',
  },
  {
    title: '更新时间',
    key: 'updatedAt',
    dataIndex: 'updatedAt'
  },
  {
    title: '是否已被删除',
    key: 'isDelete',
    dataIndex: 'isDelete'
  },
  {
    title: '操作',
    key: 'action',
    dataIndex: 'action'
  },
];

const rowSelection = {
  onChange: (selectedRowKeys, selectedRows) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
  },
  getCheckboxProps: (record) => ({
    // 设置每行选择框的属性
    checked: record.id
  }),
};


/*
async function fetchData() {
  try {
    const queryData = await requests.userAllCurrent(
        {
          page: null,
          limit: null,
          search: null,
          role: null
        },
    window.localStorage.getItem('token')
    );
    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,
        createdAt:dataSource.value.users[i].user.createdAt,
        updatedAt: dataSource.value.users[i].user.updatedAt,
        id:dataSource.value.users[i].user.id,
      });
    }
    console.log(data.value);
  } catch (error) {
    console.error(error);
  }
}
console.log(dataSource)

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


async function fetchData() {
  try {
    const queryData = await requests.userAllCurrent(
        {
          page: null,
          limit: null,
          search: null,
          role: null
        },
        window.localStorage.getItem('token')
    );
    console.log(queryData.data); // 访问数据
    dataSource.value = queryData.data.data;

    // 修正循环条件，确保我们不越界
    for (let i = 0; i < dataSource.value.count; i++) {
      const user = dataSource.value.users[i].user;
      const role = dataSource.value.users[i].role;
      if (user.updatedAt === null) {
        user.updatedAt = "null";
      }

      // 现在 'user' 已经定义，我们可以安全地访问它的属性
      states.data.push({
        username: user.username,
        nickname: user.nickname,
        phone: user.phone,
        enabled: user.enabled,
        createdAt: user.createdAt,
        updatedAt: user.updatedAt,
        id: user.id,
        isDelete: user.isDelete,
        address: user.address,
        sex: user.sex,
        age: user.age,
        email: user.email,
        avatar: user.avatar,
        recommend: user.recommend,
        signature:user.signature
      });
    }
    console.log(data.value);
  } catch (error) {
    console.error(error);
  }
}

console.log(dataSource)

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


</script>


<style scoped>
.main {

}



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


.edit {

}

.query-button {


}


.table {

}
</style>
