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

defineOptions({
  name: 'DataReviewDetailRule'
})

const { push } = useRouter()

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

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

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 { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'modelId',
    label: '报表编码',
    search: {
      component: 'TreeSelect',
      componentProps: {
        nodeKey: 'nodeid',
        props: {
          label: 'text',
          children: 'children'
        }
      },
      optionApi: async () => {
        const res = await getReporTreeApi()
        return res
      }
    },
    form: {
      component: 'TreeSelect',
      componentProps: {
        nodeKey: 'nodeid',
        props: {
          label: 'text',
          children: 'children'
        }
      },
      optionApi: async () => {
        const res = await getReporTreeApi()
        return res
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'reportName',
    label: '报表名称',
    search: {
      component: 'Input'
    },
    form: {
      component: 'Input',
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'reportType',
    label: '报表类型',
    search: {
      component: 'TreeSelect',
      componentProps: {
        nodeKey: 'pkid',
        props: {
          label: 'typeName',
          children: 'children'
        }
      },
      optionApi: async () => {
        const res = await getReportTypeApi()
        return res
      }
    },
    detail: {
      span: 24
    },
    table: {
      slots: {
        default: (data: any) => {
          return <>{data.row.typeName}</>
        }
      }
    }
  },
  {
    field: 'tg',
    label: '系统标识',
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        style: {
          width: '100%'
        }
      }
    },
    detail: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'action',
    width: '260px',
    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, 'edit')}>
                {'编辑'}
              </ElLink>
              <ElLink type="primary" underline={false} onClick={() => goRuleConfig(data.row)}>
                {'规则配置'}
              </ElLink>
            </>
          )
        }
      }
    }
  }
])

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

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 disabled = ref(true)

const onSelectionChange = (selection: TableData[]) => {
  disabled.value = selection.length === 0
}

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

const currentRow = ref()
const actionType = ref('')
const writeRef = ref<ComponentRef<typeof Write>>()

const action = (row: any, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

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

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    // const res = await saveUserApi(formData)
    //   .catch(() => {})
    //   .finally(() => {
    //     saveLoading.value = false
    //   })
    // if (res) {
    //   dialogVisible.value = false
    //   currentPage.value = 1
    //   getList()
    // }
  }
}

/** 跳转至规则配置 */
const goRuleConfig = (row: any) => {
  push(`/data-review/data-review-detail-rule-config/${row.modelId}`)
}
</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" width="60%">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :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>
