<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import {
  getLocalCheckTaskListApi,
  saveLocalCheckTaskApi,
  delLocalCheckTaskListApi,
  delLocalCheckTaskApi,
  queryLocalCheckTaskApi,
  importExcelApiUrl,
  exportExcelApi
} from '@/api/amld/LocalCheckTask/LocalCheckTask'
import { TableData } from '@/api/amld/LocalCheckTask/LocalCheckTask/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, formatter } 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'
import { Upload } from '@/components/Upload'
import { LocalCheckTask_APPLYSTATUS_LIST,LOCALCHECKTASK_APPLYPRODUCT_TABLE} from "./constants.ts"
import { findListLabel } from '@/utils'
const { t } = useI18n()

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

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getLocalCheckTaskListApi({
      pageIndex: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.body.list,
      total: res.body.total
    }
  },
  fetchDelApi: async () => {
    const res = await delLocalCheckTaskListApi(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: 'organName',
    label: '机构名称'
  },
  {
    field: 'startDate',
    label: '申请查询的数据开始日期'
  },
  {
    field: 'endDate',
    label: '申请查询的数据结束日期'
  },
  {
    field: 'proposer',
    label: '申请人'
  },
  
  {
    field: 'taskStartTime',
    label: '任务开始时间 '
  },
  {
    field: 'taskEndTime',
    label: '任务结束时间'
  },
  {
    field: 'status',
    label: '申请状态',
    formatter: (row: Recordable, __: TableColumn) => {
      const label = findListLabel(LocalCheckTask_APPLYSTATUS_LIST, row.status)
      if (label) {
        return label
      }
    }
  },
  {
    field: 'tableName',
    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: 'applydate',
    label: '申请起止时间',
    componentProps: {type: 'daterange'},
    component: 'DatePicker'
  },
  {
    field: 'proposer',
    label: '申请人',
    componentProps: {},
    component: 'Input'
  },
  {
    field: 'tableName',
    label: '申请生产的表',
    componentProps: {
      options:LOCALCHECKTASK_APPLYPRODUCT_TABLE
    },
    component: 'Select'
  },
  {
    field: 'organcode',
    label: '归属机构',
    componentProps: {},
    component: 'Select'
  },
  {
    field: 'status',
    label: '申请状态',
    componentProps: {
      options:LocalCheckTask_APPLYSTATUS_LIST,
    },
    component: 'Select'
  },
])

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 queryLocalCheckTaskApi(row.pkid)
    .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 saveLocalCheckTaskApi(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false
      })
    if (res) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}


/** 单行删除 */
const delData = async (row: TableData) => {
  const res = await delLocalCheckTaskApi(row.pkid)
  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
}
/* 提出申请 */
const submitApplication = ()=>{
  //点击提出申请，查看当前选中的任务信息
}
</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="pkid"
      :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 type="primary" @click="submitApplication">提出申请</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>