<template xmlns="">
  <div class="main">
    <div class="header">
      <div class="input">
        <a-input v-model:value="searchData.id" addonBefore="角色id" class="first-input" placeholder="请输入角色id" />
      </div>
      <div class="edit">
        <a-button class="query-button" @click="searchRole"><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.name" style="width: 250px; margin-bottom: 10px"/></div>
        <div>角色备注：<a-input v-model:value="addData.displayName" style="width: 250px; margin-bottom: 10px;"/></div>
      </div>
    </a-modal>

    <!--删除角色对话框-->
    <a-modal v-model:open="DeleteDiaLog" cancel-text="取消"  content="确认删除这条数据吗?" ok-text="确认" title="删除角色" @cancel="deleteCancel" @ok="deleteOk">
      <p>确定删除改数据吗？</p>
    </a-modal>

    <!--修改角色对话框-->
    <a-modal
        v-model:open="editDiaLog"
        cancel-text="取消"
        @cancel="editCancel"
        ok-text="确定"
        title="修改角色"
        @ok="editOk"
    >
      <div style="">
        <div style="margin-bottom: 10px;">
          <div style="margin-left: 15px; margin-bottom: 15px">角色id(原始id)： <a-input v-model:value="updateData.id" style="width:10vw" type="number"  /></div>
          <div style="margin-left: 15px; margin-bottom: 15px">角色名称：<a-input v-model:value="updateData.name" style="width: 10vw; margin-left: 2vw" /></div>
          <div style="margin-left: 15px; margin-bottom: 15px">角色备注：<a-input v-model:value="updateData.displayName" style="width: 10vw; margin-left: 2vw" /></div>
        </div>
      </div>
    </a-modal>

    <div class="table">
      <a-table :columns="columns" :data-source="states.data" :row-selection="rowSelection"  :rowKey="record => record.id"
        :loading="loading"
        @change="handleTableChange">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'roleName'">
              {{ record.roleName }}
          </template>
          <template v-else-if="column.key === 'displayName'">
              {{record.displayName}}
          </template>
          <template v-else-if="column.key === 'id'">
              {{record.id}}
          </template>
          <template v-else-if="column.key === 'createdAt'">
            {{record.createdAt}}
          </template>
          <template v-else-if="column.key === 'updatedAt'">
            {{record.updatedAt}}
          </template>
          <template v-else-if="column.key === 'role_action'">
            <span style="margin-left: 10px">
              <a-button class="button2" size="small" type="text" @click="() => showEditDiaLog(record)"><EditOutlined />修改</a-button>
              <a-button class="button1" size="small" type="text" @click="() => showDeleteConfirm(record)"><DeleteOutlined />删除</a-button>
            </span>
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>


<script setup>
import {computed, 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 {usePagination} from 'vue-request';
import requests from '@/js/request.js';
import axios from 'axios';

const roleid = ref('');
const AddDiaLog = ref(false);
const DeleteDiaLog = ref(false);
const editDiaLog = ref(false);
const token = window.localStorage.getItem('token')
const states = reactive({
  data:[]
});
const updateData = reactive({
  id: '',
  name: '',
  displayName: '',

});
const loadingTable = ref(true);

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

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


function getAll() {
  requests.roleGet(null,token).then((res)=>{
    console.log(res)
    states.data = res.data.data
    // 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
     }*/
    console.log("getAll:",states.data)
  })
}



/*新增角色*/
const addData = reactive({
  // id:'',
  // roleName:'',
  name:'',
  displayName:'',
  // createdAt:'',
  // updatedAt:'',

})

function showAddDiaLog(){
  AddDiaLog.value = true;
  addData.name = '';
  addData.displayName = '';
}

function addOk () {
  requests.roleAdd(addData, token).then((res)=>{
    console.log(res.data)
    if (res.data.code===200) {
      message.success('新增成功')
      AddDiaLog.value = false;
      getAll()
    }
    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.roleDelete(deleteId, token)
          .then(response => {
            console.log('删除成功');
            message.success("删除成功")
            getAll()
          })
          .catch(error => {
            console.error('删除失败', error);
            message.error("删除失败")
            getAll()
          })

    }

  });

};


/*修改角色*/
/*function showEditDiaLog(record){
  editDiaLog.value = true
  updateData.id = record.id
  updateData.name = record.role_name
  updateData.displayName = record.displayName

}*/

const showEditDiaLog = (record) => {
    console.log("record:",record)
    editDiaLog.value = true
    updateData.id = record.id
    updateData.name = record.roleName
    updateData.displayName = record.displayName
};


function editOk(){
  loadingTable.value = true
  editDiaLog.value = false;
  requests.roleEdit(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;
  message.info('取消修改')
}


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

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




const columns = [
  {
    title: '角色名称',
    dataIndex: 'roleName',
    key: 'roleName',
  },
  {
    title: '角色备注',
    dataIndex: 'displayName',
    key:'displayName',
  },
  {
    title: '排序id',
    dataIndex: 'id',
    key: 'id',
  },
  {
    title: '创建时间',
    key: 'createdAt',
    dataIndex: 'createdAt',
  },
  {
    title: '更新时间',
    key: 'updatedAt',
    dataIndex: 'updatedAt'
  },
  {
    title: '操作',
    key: 'role_action',
    dataIndex: 'role_action'
  },
];



const rowSelection = {
  onChange: (selectedRowKeys, selectedRows) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
  },
  getCheckboxProps: record => ({
    checked:record.id,
  }),
};

const queryData = params => {
  return axios.get('https://randomuser.me/api?noinfo', {
    params,
  });
};
const {
  data: dataSource,
  run,
  loading,
  current,
  pageSize,
} = usePagination(queryData, {
  formatResult: res => res.data.results,
  pagination: {
    currentKey: 'page',
    pageSizeKey: 'results',
  },
});
const pagination = computed(() => ({
  total: 200,
  current: current.value,
  pageSize: pageSize.value,
}));
const handleTableChange = (pag, filters, sorter) => {
  run({
    results: pag.pageSize,
    page: pag?.current,
    sortField: sorter.field,
    sortOrder: sorter.order,
    ...filters,
  });
};
</script>


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

.header {
  display: flex;
}

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

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

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

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

.button1 {
  color: dodgerblue;
}

.button2 {
  color:dodgerblue;
}
</style>
