<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import {
  getSrdbRectifyTaskListApi,
  saveSrdbRectifyTaskApi,
  delSrdbRectifyTaskListApi,
  delSrdbRectifyTaskApi,
  querySrdbRectifyTaskApi,
} from '@/api/srdb/SrdbRectifyTask/SrdbRectifyTask'
import { REPORT_STATUS_LIST,APPLE_STATUS_LIST } from './constants'
import { TableData } from '@/api/srdb/SrdbRectifyTask/SrdbRectifyTask/types'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { ElButton, ElLink, ElLoading, ElPopconfirm, ElMessage } from 'element-plus'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import Write from './components/Write.vue'
import { Dialog } from '@/components/Dialog'
import { getWidth } from '@/utils';
import Detail from './components/Detail.vue'

const { t } = useI18n()

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

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getSrdbRectifyTaskListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.body.list,
      total: res.body.total
    }
  },
  fetchDelApi: async () => {
    const res = await delSrdbRectifyTaskListApi(unref(ids));
    return !!res;
  },
})

const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList, refresh } = tableMethods

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'selection',
    type: 'selection',
    fixed: true
  },
  {
    field: 'orgNo',
    label: '机构金融许可证号'
  },
  {
    field: 'subOrgNo',
    label: '子机构编号'
  },
  {
    field: 'regulationId',
    label: '制度表编号'
  },
  {
    field: 'regulationName',
    label: '制度名称'
  },
  {
    field: 'regulationVersion',
    label: '制度版本'
  },
  {
    field: 'orgApplicantNo',
    label: '整改编码'
  },
  {
    field: 'dataDate',
    label: '数据日期'
  },
  {
    field: 'workflowId',
    label: '任务编码'
  },
  {
    field: 'rectifyType',
    label: '整改类型'
  },
  {
    field: 'corrEndDate',
    label: '整改截止日期'
  },
  {
    field: 'tabName',
    label: '表中文'
  },
  {
    field: 'tabNameEn',
    label: '表英文'
  },
  {
    field: 'tabGuid',
    label: '表唯一编号'
  },
  // {
  //   field: 'metricsCode',
  //   label: '退回指标数量'
  // },
  {
    field: 'reportStatus',
    label: '报送状态',
    slots: {
      default: (data: any) => {
        return REPORT_STATUS_LIST[data.row.reportStatus]?.label
      }
    }
  },
  {
    field: 'applyStatus',
    label: '申请状态',
    slots: {
      default: (data: any) => {
        return APPLE_STATUS_LIST[data.row.applyStatus]?.label
      }
    }
  },
  {
    field: 'centerPullStatus',
    label: '中心拉取通知状态'
  },
  {
    field: 'centerPullTime',
    label: '拉取时间'
  },
  {
    field: 'filePath',
    label: '整改要求文件存放全路径'
  },
  {
    field: 'corrAdvice',
    label: '整改说明'
  },
  {
    field: 'applicantTelphone',
    label: '申请人联系方式'
  },
  {
    field: 'applicant',
    label: '申请人名称'
  },
  {
    field: 'applyTime',
    label: '申请时间'
  },
  {
    field: 'backTime',
    label: '监管退回或审批时间'
  },
  {
    field: 'restateReportTime',
    label: '重报时间'
  },
  // {
  //   field: 'createTime',
  //   label: '生成时间'
  // },
  // {
  //   field: 'collectingCode',
  //   label: '采集编码'
  // },
  // {
  //   field: 'metricsName',
  //   label: '采集编码'
  // },
  {
    field: 'action',
    label: t('tableDemo.action'),
    width: 160,
    fixed: 'right',
    slots: {
      default: (data: any) => {
        return (
          <>
            <ElLink type="primary" underline={false} onClick={() => action(data.row, 'edit')}>
              {t('tableDemo.edit')}
            </ElLink>
            <ElPopconfirm
              title={t('common.delTableMsg')}
              width={200}
              v-slots={{
                reference: () => {
                  return (
                    <>
                      <ElLink type="primary" underline={false}>
                        {t('tableDemo.del')}
                      </ElLink>
                    </>
                  )
                }
              }}
              onConfirm={() => delData(data.row)}
            ></ElPopconfirm>
            <ElLink type="primary" underline={false} onClick={() => action(data.row, 'detail')}>
              {t('tableDemo.detail')}
            </ElLink>
          </>
        )
      }
    }
  }
].map(item => ({ minWidth: item.label ? getWidth(item.label) : 120, ...item }) as TableColumn))

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'regulationId',
    label: '制度表编号',
    componentProps: {},
    component: 'Input'
  },
  {
    field: 'regulationName',
    label: '制度名称',
    componentProps: {},
    component: 'Input'
  },
  {
    field: 'dataDate',
    label: '数据日期',
    componentProps: {},
    component: 'DatePicker'
  },
  {
    field: 'reportStatus',
    label: '报送状态',
    componentProps: {
      options:REPORT_STATUS_LIST
    },
    component: 'Select'
  },
  {
    field: 'applyStatus',
    label: '申请状态',
    componentProps: {
      options:APPLE_STATUS_LIST
    },
    component: 'Select'
  },
  // {
  //   field: 'centerPullStatus',
  //   label: '中心拉取通知状态',
  //   componentProps: {},
  //   component: 'Select'
  // },
  // {
  //   field: 'applicant',
  //   label: '申请人名称',
  //   componentProps: {},
  //   component: 'Input'
  // }
])

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

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

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

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

/**单行查询**/
const action = async (row: TableData, type: string) => {
  let detailLoading = ElLoading.service({
    background: 'rgba(0, 0, 0, 0.7)'
  })
  const res = await querySrdbRectifyTaskApi(row.id)
    .catch(() => {})
    .finally(() => {
      detailLoading.close()
    })
  detailLoading.close()
  if (res) {
    const data = res.body.result
    dialogTitle.value = t(type === 'edit' ? 'tableDemo.edit' : 'tableDemo.detail')
    actionType.value = type
    currentRow.value = data
    dialogVisible.value = true
  }
}

const AddAction = () => {
  dialogTitle.value = t('tableDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = 'add'
}
const saveLoading = ref(false)

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

const delLoading = ref(false)

/** 批量删除  **/
const delDataBatch = async () => {
  const elTableExpose = await getElTableExpose()
  ids.value = elTableExpose?.getSelectionRows().map((v: TableData) => { v.id }) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

/** 单行删除 */
const delData = async (row: TableData) => {
  const res = await delSrdbRectifyTaskApi(row.id)
  if (res) {
    const { code, errMsg } = res.head
    if (code === '0') {
      ElMessage.success('删除成功!')
      getList()
    } else {
      ElMessage.error(errMsg || '删除失败!')
    }
  }
}

const disabled = ref(true)

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

</script>

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

    <Table
      :columns="tableColumns"
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      default-expand-all
      node-key="id"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total
      }"
      @selection-change="onSelectionChange"
      @register="tableRegister"
      @refresh="refresh"
    >
      <template #buttons>
        <!-- <ElButton type="primary" @click="AddAction">{{ t('tableDemo.add') }}</ElButton> -->
        <ElButton :loading="delLoading" type="primary" :disabled="disabled" @click="delDataBatch()">
          {{ t('tableDemo.del') }}
        </ElButton>
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :current-row="currentRow"
      :action-type="actionType"
    />
    <Detail v-if="actionType === 'detail'" :current-row="currentRow" />
    <template #footer>
      <ElButton v-if="actionType !== 'detail'" type="primary" :loading="saveLoading" @click="save">
        {{ t('dialogDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>