<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, ElPopconfirm, ElMessage } from 'element-plus'
import { Table } from '@/components/Table'
import { saveTableApi, delTableListApi, TempSubmitManage } from '@/api/template'
import { useTable } from '@/hooks/web/useTable'
import { Template } from '@/api/template/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'

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

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await TempSubmitManage({
      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: 'index',
    label: t('manage.index'),
    type: 'index',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'pkid',
    label: t('manage.pkid'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'formatId',
    label: t('manage.formatId'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      colProps: {
        span: 24
      }
    }
  },
  {
    field: 'reportName',
    label: '报表名称',
    search: {
      component: 'Input'
    },
    table: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    form: {
      component: 'Input',
      colProps: {
        span: 24
      }
    }
  },
  {
    field: 'formatName',
    label: t('manage.formatName'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      colProps: {
        span: 24
      }
    }
  },

  {
    field: 'systemCode',
    label: t('manage.systemCode'),
    search: {
      component: 'Select',
      componentProps: {
        options: [
          {
            value: 0,
            label: 'portal'
          },
          {
            value: 1,
            label: 'srdb'
          }
        ]
      }
    }
  },
  // {
  //   field: 'importance',
  //   label: t('manage.importance'),
  //   search: {
  //     hidden: true
  //   },
  //   form: {
  //     component: 'Select',
  //     componentProps: {
  //       style: {
  //         width: '100%'
  //       },
  //       options: [
  //         {
  //           label: '重要',
  //           value: 3
  //         },
  //         {
  //           label: '良好',
  //           value: 2
  //         },
  //         {
  //           label: '一般',
  //           value: 1
  //         }
  //       ]
  //     }
  //   },
  //   detail: {
  //     slots: {
  //       default: (data: any) => {
  //         return (
  //           <ElTag
  //             type={
  //               data.importance === 1 ? 'success' : data.importance === 2 ? 'warning' : 'danger'
  //             }
  //           >
  //             {data.importance === 1
  //               ? t('manage.important')
  //               : data.importance === 2
  //               ? t('manage.good')
  //               : t('manage.commonly')}
  //           </ElTag>
  //         )
  //       }
  //     }
  //   }
  // },
  // {
  //   field: 'pageviews',
  //   label: t('manage.pageviews'),
  //   search: {
  //     hidden: true
  //   },
  //   form: {
  //     component: 'InputNumber',
  //     value: 0
  //   }
  // },
  // {
  //   field: 'content',
  //   label: t('exampleDemo.content'),
  //   search: {
  //     hidden: true
  //   },
  //   table: {
  //     show: false
  //   },
  //   form: {
  //     component: 'Editor',
  //     colProps: {
  //       span: 24
  //     }
  //   },
  //   detail: {
  //     span: 24,
  //     slots: {
  //       default: (data: any) => {
  //         return <div innerHTML={data.content}></div>
  //       }
  //     }
  //   }
  // },
  {
    field: 'format',
    label: t('manage.format'),
    table: {
      hidden: true
    },
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      componentProps: {
        type: 'textarea',
        rows: 5
      },
      colProps: {
        span: 24
      }
    },
    detail: {
      hidden: false
    }
  },
  {
    field: 'action',
    width: '260px',
    label: t('manage.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')}>
                {t('exampleDemo.edit')}
              </ElLink>
              <ElLink type="primary" underline={false} onClick={() => action(data.row, 'detail')}>
                {'报文模版'}
              </ElLink>
              <ElPopconfirm
                title={t('common.delTableMsg')}
                width={200}
                v-slots={{
                  reference: () => {
                    return (
                      <>
                        <ElLink type="primary" underline={false}>
                          {t('exampleDemo.del')}
                        </ElLink>
                      </>
                    )
                  }
                }}
                onConfirm={() => delAloneData(data.row)}
              ></ElPopconfirm>
            </>
          )
        }
      }
    }
  }
])

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

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

const currentRow = ref<Template | 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: Template | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? row.pkid : elTableExpose?.getSelectionRows().map((v: Template) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const delAloneData = async (row: Template) => {
  delLoading.value = true
  const res = await delTableListApi([row.id])
    .catch(() => {})
    .finally(() => {
      delLoading.value = false
    })
  delLoading.value = false
  if (res) {
    const { code } = res.data
    if (code === 1) {
      ElMessage.success('操作成功!')
      getList()
    } else {
      ElMessage.error('操作失败!')
    }
  }
}

const action = (row: Template, type: string) => {
  console.log(row)
  dialogTitle.value = type === 'edit' ? '编辑' : '报文模版'
  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('manage.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>
