<template>
  <div>
    <n-card>
      <headSearch :info="search" @search="handleSearch" @reset="handleSearch" />
      <data-table
        ref="tableRef"
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        size="large"
        @update:checked-row-keys="handleCheck"
      >
        <template #tableTitle>
          <n-button v-if="permissionList.includes('equipment:box:create')" type="primary" @click="handleModal"> {{ getPermissionLabel('equipment:box:create') }} </n-button>
          <n-popconfirm
            negative-text="取消"
            positive-text="确认"
            @positive-click="handleDelete"
          >
            <template #trigger>
              <n-button type="primary"> 删除 </n-button>
            </template>
            确认要删除选中数据吗?
          </n-popconfirm>
        </template>
      </data-table>
    </n-card>
  </div>
  <!-- 新增、编辑弹窗 -->
  <BoxModal v-if="modalShow" v-model:visible="modalShow" :data="rowData" :type="modalType" @reload="handleSearch" />
</template>

<script>
import search from './tools/search.js'
import table from './tools/table.js'
import headSearch from '@/components/Search/index.vue'
import dataTable from '@/components/DataTable/index.vue'
import BoxModal from './components/BoxModal.vue'
import { ref, unref, toRefs, reactive, onUnmounted } from 'vue'
import { boxPage } from '@/api/equipment/box.js'
import { usePermissionStore } from '@/store/modules/permission'

export default {
  name: 'BoxManage',
  components: { dataTable, BoxModal, headSearch },
  setup() {
    const permissionStore = usePermissionStore()

    const data = reactive({
      ...toRefs(table),
      search,
      permissionList: permissionStore.accessPermissionCodes

    })

    const getPermissionLabel = (code) => {
      return permissionStore.accessPermissions.find((item) => {
        return item.code === code
      })?.name || ''
    }

    const loadDataTable = async(res) => {
      const _params = {
        ...unref(data.searchParams),
        ...res
      }
      return await boxPage(_params)
    }

    // 新增
    function handleModal() {
      data.rowData = null
      data.modalType = 'create'
      data.modalShow = true
    }

    const selectedIds = ref([])
    function handleCheck(rowKeys) {
      selectedIds.value = rowKeys
    }

    function handleDelete() {
      if (selectedIds.value.length) {
        data.deleteData(selectedIds.value)
      } else {
        $message.warning('请至少选中一条数据')
      }
    }

    onUnmounted(() => {
      data.searchParams = null
    })

    return {
      ...toRefs(data),
      loadDataTable,
      handleModal,
      handleDelete,
      handleCheck,
      getPermissionLabel
    }
  }
}
</script>
<style scoped lang='scss'>
.n-button + .n-button {
  margin-left: 10px;
}
</style>
