<template>
  <div>
    <n-card>
      <HeadSearch :info="search" @search="handleSearch" @reset="handleSearch" />
      <DataTable
        ref="tableRef"
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        @fetch-success="getTableData"
        @update:checked-row-keys="handleCheck"
      >
        <template #tableTitle>
          <n-button type="primary" @click="handleOrder"> 生成工单 </n-button>
        </template>
      </DataTable>
    </n-card>
  </div>

  <MapDrawer v-model:visible="mapDrawer" :data="rowData" />

  <QuestionModal v-if="modalShow" v-model:visible="modalShow" :type="modalType" :data="rowData" />

  <PreviewModal v-if="previewModal" v-model:visible="previewModal" :data="pageData" :select-row="rowData" />

</template>

<script>
import table from './tools/table.js'
import search from './tools/search.js'
import HeadSearch from '@/components/Search/index.vue'
import DataTable from '@/components/DataTable/index.vue'
import MapDrawer from './components/MapDrawer.vue'
import PreviewModal from './components/PreviewModal.vue'
import QuestionModal from './components/QuestionModal.vue'
import { reactive, ref, unref, toRefs, onUnmounted } from 'vue'
import { getQuestionList } from '@/api/task/index.js'
import { generateOrder } from '@/api/order/index.js'

export default {
  name: 'QuestionList',
  components: { HeadSearch, DataTable, MapDrawer, PreviewModal, QuestionModal },
  setup() {
    const data = reactive({
      search,
      ...toRefs(table),
      pageData: []
    })
    /**
     * @description: 加载表格数据
     * @param {*} res
     * @return {*}
     */
    const loadDataTable = async(res) => {
      const _params = {
        ...unref(data.searchParams),
        status: 1,
        ...res
      }
      console.log(_params)
      return await getQuestionList(_params)
    }

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

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

    function getTableData(list) {
      data.pageData = list.items
    }

    // 选择表格数据
    const selectedIds = ref([])
    function handleCheck(rowKeys) {
      selectedIds.value = rowKeys
    }

    const handleOrder = async() => {
      if (selectedIds.value.length) {
        const ids = selectedIds.value.join(',')
        const res = await generateOrder(ids)
        if (res.code === 0) {
          selectedIds.value = []
          data.handleSearch()
        }
      } else {
        $message.warning('请至少选中一条数据')
      }
    }

    return {
      ...toRefs(data),
      loadDataTable,
      getTableData,
      handleModal,
      handleOrder,
      handleCheck,
      selectedIds
    }
  }
}

</script>
<style scoped lang='scss'>
</style>
