<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElLink } from 'element-plus'
import { Table } from '@/components/Table'
import {
  getTableListApi,
  saveTableApi,
  delTableListApi
} from '@/api/trustedZoneManage/fieldInfoQuery'
import { useTable } from '@/hooks/web/useTable'
import { TableData } from '@/api/table/types'
import { ref, unref, reactive } from 'vue'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'

defineOptions({
  name: 'FieldInfoQuery'
})

const ids = ref<string[]>([])

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getTableListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.list,
      total: res.data.total
    }
  },
  fetchDelApi: async () => {
    const res = await delTableListApi(unref(ids))
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList, refresh } = tableMethods

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

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'financialLicense',
    label: '金融许可证号',
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    detail: {
      hidden: false
    }
  },
  {
    field: 'organName',
    label: '机构名称',
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    detail: {
      hidden: false
    }
  },
  {
    field: 'typeCode',
    label: '采集编号',
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    detail: {
      hidden: false
    }
  },
  {
    field: 'systemCode',
    label: '制度编号',
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    detail: {
      hidden: false
    }
  },
  {
    field: 'systemName',
    label: '制度名称',
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    detail: {
      hidden: false
    }
  },
  {
    field: 'systemVersion',
    label: '制度版本号',
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    detail: {
      hidden: false
    }
  },
  {
    field: 'tableEnName',
    label: '表英文名',
    search: {
      component: 'Input'
    },
    form: {
      component: 'Input'
    },
    detail: {
      hidden: false
    }
  },
  {
    field: 'tableName',
    label: '表中文名',
    search: {
      component: 'Input'
    },
    form: {
      component: 'Input'
    },
    detail: {
      hidden: false
    }
  },
  {
    field: 'dataItemCode',
    label: '数据项代码',
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    detail: {
      hidden: false
    }
  },
  {
    field: 'dataItemName',
    label: '数据项名称',
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    detail: {
      hidden: false
    }
  },
  {
    field: 'dataDate',
    label: '数据日期',
    search: {
      component: 'DatePicker',
      componentProps: {
        type: 'daterange'
      }
    },
    form: {
      component: 'Input'
    },
    detail: {
      hidden: false
    }
  },
  {
    field: 'submitDate',
    label: '报送日期',
    search: {
      component: 'DatePicker',
      componentProps: {
        type: 'daterange'
      }
    },
    form: {
      component: 'Input'
    },
    detail: {
      hidden: false
    }
  },
  {
    field: 'submitState',
    label: '报送状态',
    search: {
      hidden: false,
      component: 'Select',
      componentProps: {
        options: [
          {
            label: '全部',
            value: 1
          },
          {
            label: '未上报',
            value: 2
          },
          {
            label: '已上报',
            value: 3
          }
        ]
      },
      value: 1
    },
    form: {
      component: 'Select',
      componentProps: {
        style: {
          width: '100%'
        },
        options: [
          {
            label: '全部',
            value: 1
          },
          {
            label: '未上报',
            value: 1
          },
          {
            label: '已上报',
            value: 2
          }
        ]
      }
    },
    detail: {
      hidden: false
    }
  },
  {
    field: 'action',
    width: '60px',
    label: t('tableDemo.action'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <ElLink type="primary" underline={false} onClick={() => action(data.row, 'detail')}>
                {t('exampleDemo.detail')}
              </ElLink>
            </>
          )
        }
      }
    }
  }
])

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

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

const currentRow = ref<TableData | null>(null)
const actionType = ref('')

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

const delLoading = ref(false)

const delData = async (row: TableData | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: TableData) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const action = (row: TableData, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = row
  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 saveTableApi(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false
      })
    if (res) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}

const disabled = ref(true)

const onSelectionChange = (selection: any[]) => {
  disabled.value = selection.length === 0
}
</script>

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

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
      @refresh="refresh"
      @selection-change="onSelectionChange"
    >
      <template #buttons>
        <ElButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</ElButton>
        <ElButton :loading="delLoading" type="primary" :disabled="disabled" @click="delData(null)">
          {{ t('exampleDemo.del') }}
        </ElButton>
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="currentRow"
    />

    <Detail
      v-if="actionType === 'detail'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="currentRow"
    />

    <template #footer>
      <ElButton v-if="actionType !== 'detail'" type="primary" :loading="saveLoading" @click="save">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
