<template>
  <div class="Table">
    <!-- 表格 -->
    <Table :list="datas.tableData" @handleDelete="handleDelete" @handleEdit="handleEdit"></Table>
    <!-- 分页 -->
    <Paging :pagingConfig="datas.pagingConfig" @sizeChange="sizeChange" @currentChange="currentChange"></Paging>
    <!-- 其他模板 -->
  </div>
</template>
<script setup>
import Table from './component/Table.vue'
import Paging from '@/components/mycomponents/myPaging.vue'
import eventBus from '@/utils/eventBus'
import API from './api'

const datas = reactive({
  tableData: [], // 表格数据
  title: '新增数据',
  pagingConfig: {
    total: 0, // 总数
    pageSize: 10, // 每页数据数量
    pageNumber: 1, // 当前页码
  },
  DialogForm: { // 弹窗表单数据
    name: "",
    telephone: "",
    address: "",
    remark: ""
  },
  rules: {
    name: [
      { required: true, message: '请输入供应商名称', trigger: 'blur' },
      { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
  }
})
const myDialogRef = ref(null)
const ruleFormRef = ref(null)
onMounted(() => {
  getList()
  eventBus.on('search', (res) => {
    getList(res)
  })
})
onBeforeUnmount(() => {
  eventBus.off('search')
})

async function getList(data = {}) {
  const res = await API.getPage({ page: datas.pagingConfig.pageNumber, size: datas.pagingConfig.pageSize, ...data })
  datas.tableData = res.records
  datas.pagingConfig.total = res.totalRow
  datas.pagingConfig.pageSize = res.pageSize
  datas.pagingConfig.pageNumber = res.pageNumber
}
function add() {
  rest()
  datas.title = '新增数据'
  myDialogRef.value.open()
}
async function handleEdit(row) {
  datas.title = '编辑数据'
  const res = await API.getinfo(row.id)
  datas.DialogForm = res
  myDialogRef.value.open()
}
async function confirm() {
  ruleFormRef.value.validate(async valid => {
    if (valid) {
      let res = null
      if (datas.title == '新增数据') {
        res = await API.add(datas.DialogForm)
      } else {
        res = await API.update(datas.DialogForm)
      }
      if (res.code == 200) {
        ElMessage({
          message: '成功',
          type: 'success',
        })
        rest()
        getList()
        myDialogRef.value.close()
      }
    }
  })
}
// 重置
function rest() {
  datas.DialogForm = { sort: "1" }
}
async function handleDelete(id) {
  ElMessageBox.confirm("是否删除数据项?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    async () => {
      let res = await API.deleteByIds(id)
      if (res.code == 200) {
        ElMessage({
          message: '删除成功',
          type: 'success',
        })
        getList()
      }
    }
  );
}
// 分页
function sizeChange(val) {
  datas.pagingConfig.pageSize = val
  getList()
}
function currentChange(val) {
  datas.pagingConfig.pageNumber = val
  getList()
}

</script>
<style scoped lang="scss">
.Table {
  padding: 20px;
  background-color: #fff;
  border: 1px solid #e4e7ed;
  margin-top: 20px;
  border-radius: 4px;
}
</style>