<script setup lang="tsx">
import { ContentWrap } from '@common/src/components/ContentWrap'
import { Search } from '@common/src/components/Search'
import { Dialog } from '@common/src/components/Dialog'
import { Table } from '@common/src/components/Table'
import { BaseButton } from '@common/src/components/Button'
import { useTable } from '@common/src/hooks/web/useTable'
import { CrudSchema, useCrudSchemas } from '@common/src/hooks/web/useCrudSchemas'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'

import { ref, unref, reactive } from 'vue'

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await Api({
      current: unref(currentPage),
      size: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.list,
      total: res.data.totalCount
    }
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList } = tableMethods

const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: '序号',
    type: 'index',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'no',
    label: '编号',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'serviceName',
    label: '业务表名称',
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return <>{data.row.serviceName}</>
        }
      }
    },
    form: {
      component: 'Input'
    }
  },
  {
    field: 'serviceNo',
    label: '业务编码',
    search: {
      hidden: true
    },
    table: {
      hidden: true
    },
    form: {
      component: 'Input'
    }
  },
  {
    field: 'action',
    width: '220px',
    label: '操作',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <BaseButton size="small" type="primary" onClick={() => action(data.row, 'detail')}>
                查看详情
              </BaseButton>
              <BaseButton size="small" type="primary" onClick={() => action(data.row, 'edit')}>
                编辑
              </BaseButton>
              <BaseButton size="small" type="danger" onClick={() => delData(data.row)}>
                删除
              </BaseButton>
            </>
          )
        }
      }
    }
  }
])

// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref()
const actionType = ref('')

const AddAction = () => {
  dialogTitle.value = '新增'
  currentRow.value = null
  dialogVisible.value = true
  actionType.value = 'add'
}

const delData = async (row) => {
  ElMessageBox.confirm('确认删除？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await del(row?.id)
    getList()
  })
}

const action = (row, type: string) => {
  currentRow.value = row
  actionType.value = type
  dialogTitle.value = type === 'edit' ? '编辑' : '详情'
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    const res = await (actionType.value === 'add'
      ? createBusinessTable(formData)
      : updateBusinessTable(formData))
    saveLoading.value = false
    if (res.success) {
      dialogVisible.value = false
      getList()
    }
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">新增</BaseButton>
    </div>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
    <Detail
      v-if="actionType === 'detail'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="currentRow"
    />
    <Write
      v-else
      :action-type="actionType"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="currentRow"
    />
    <template #footer>
      <BaseButton v-if="actionType !== 'detail'" type="primary" :loading="saveLoading" @click="save"
        >保存</BaseButton
      >
      <BaseButton @click="dialogVisible = false">关闭</BaseButton>
    </template>
  </Dialog>
</template>
