<template>
  <div class="user-page flex-column card h-100 overflow-hidden">
    <div class="header-filter-form">
      <SearchForm
        v-model="searchForm"
        :config="searchConfig"
        @search="search"
        :isAddBtn="false"
        @delete="deleteFn"
      ></SearchForm>
    </div>
    <div class="user-content flex-1 flex-column overflow-hidden">
      <div v-loading="loading" class="user-list flex-1 overflow-hidden">
        <CustomizeTable
          border
          align="center"
          v-model="tableData"
          :config="tableConfig"
          @get-checkbox-records="handleCheckboxRecords"
        ></CustomizeTable>
      </div>
      <ElPagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[100, 200, 300, 400, 500]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin: 10px auto 0; text-align: right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></ElPagination>
    </div>
  </div>
</template>

<script setup lang="tsx">
defineOptions({
  name: 'MyDownloads',
})
import {
  getExportRecordApi,
  deleteExportRecordByIdsApi,
} from '@/api/myDownload'

import { ISeachFormConfig } from '@/types/searchType'
import { TableColumn } from '@/components/VxeTable'
import SearchForm from '@/components/SearchForm.tsx'
import CustomizeTable from '@/components/VxeTable.tsx'
import usePageList from '@/utils/hooks/usePageList'
import { useValue } from '@/utils/hooks/useValue'
import { filePath } from '@/api/axios'

import { Delete, Download } from '@element-plus/icons-vue'

const [searchForm] = useValue({ periodTime: [] })

interface ParamsType {
  startTime?: string
  endTime?: string
  periodTime?: string[]
  pageSize: number
  currentPage: number
}

const {
  loading,
  currentPage,
  pageSize,
  total,
  data: tableData,
  refresh: search,
  onCurrentPageChange: handleCurrentChange,
  onPageSizeChange: handleSizeChange,
} = usePageList({
  query: (page, pageSize) => {
    const params: ParamsType = {
      ...searchForm.value,
      pageSize: pageSize,
      currentPage: page,
    }
    if (searchForm.value?.periodTime.length) {
      params.startTime = searchForm.value?.periodTime[0]
      params.endTime = searchForm.value?.periodTime[1]
    }
    params.periodTime && delete params.periodTime

    return getExportRecordApi(params).then(({ data }) => {
      return data
    })
  },
})

const selection = ref([])

const searchConfig = ref<ISeachFormConfig[]>([
  {
    prop: 'periodTime',
    type: 'dateRangePicker',
    label: '创建时间',
    attrs: {
      style: { width: '380px' },
      clearable: true,
      type: 'datetimerange',
      'default-time': [
        new Date(0, 0, 0, 0, 0, 0),
        new Date(0, 0, 0, 23, 59, 59),
      ],
      'start-placeholder': '开始时间',
      'end-placeholder': '结束时间',
      format: 'YYYY-MM-DD HH:mm:ss',
      'value-format': 'YYYY-MM-DD HH:mm:ss',
    },
  },
  {
    prop: 'status',
    type: 'select',
    label: '状态',
    attrs: {
      clearable: true,
      placeholder: '请选择启用状态',
      options: [
        { label: '正在生成', value: 1 },
        { label: '生成成功', value: 2 },
        { label: '生成失败', value: 3 },
      ],
    },
  },
  {
    prop: 'fileDescription',
    type: 'input',
    label: '下载描述',
    attrs: {
      clearable: true,
      placeholder: '请输入下载描述',
    },
  },
])

const tableConfig = ref<TableColumn[]>([
  {
    prop: 'fileDescription',
    label: '下载文件描述',
    attrs: {
      'min-width': 200,
    },
  },
  {
    prop: 'status',
    label: '下载状态',
    render: {
      default: ({ row }) => (
        <div>
          {row.status === 1
            ? '正在生成'
            : row.status === 2
            ? '生成成功'
            : '生成失败'}
        </div>
      ),
    },
  },

  {
    prop: 'createTime',
    label: '创建时间',
  },
  {
    prop: 'finishTime',
    label: '完成时间',
  },
  {
    prop: 'errorMsg',
    label: '错误信息',
    attrs: {
      'min-width': 400,
    },
  },
  {
    prop: 'operating',
    label: '操作',
    attrs: {
      align: 'center',
    },
    render: {
      default: ({ row }) => (
        <div>
          <el-icon
            size="24"
            title="下载"
            color={row.status === 2 ? '#8cc34b' : '#ccc'}
            style={{
              cursor: row.status === 2 ? 'pointer' : 'not-allowed',
              verticalAlign: 'middle',
              opacity: row.status === 2 ? 1 : 0.6,
            }}
            onClick={
              row.status === 2
                ? () => downloadFn(row as { fileUrl: string })
                : undefined
            }
          >
            <Download />
          </el-icon>

          <el-icon
            size="24"
            title="删除"
            color="#f56c6c"
            style="cursor: pointer; vertical-align: middle"
            onclick={() => deleteFn(row.id as string | number)}
          >
            <Delete />
          </el-icon>
        </div>
      ),
    },
  },
])

/**
 * @description: 获取选中数据
 */
function handleCheckboxRecords(value: never[]) {
  console.log(351, value)
  selection.value = value
}

function downloadFn(data: { fileUrl: string }) {
  window.open(filePath + data.fileUrl, '_blank')
  console.log(248, data)
}
async function deleteFn(id?: string | number) {
  try {
    await ElMessageBox.confirm('确定删除该下载文件记录?', '提示', {
      cancelButtonText: '取消',
      confirmButtonText: '确认',
      type: 'warning',
    })
    let ids
    if (id) {
      ids = [id].join(',')
    } else {
      ids = selection.value.map((el: { id: string }) => el.id).join(',')
    }
    console.log(214, ids)

    await deleteExportRecordByIdsApi(ids)
    ElMessage.success('操作成功')
    search()
  } catch (error) {
    console.log(error)
  }
}
</script>

<style lang="scss" scoped>
.header-filter-form {
  margin-bottom: 20px;

  :deep(.el-form-item) {
    margin-right: 14px;
    margin-bottom: 10px;
  }
}
.user-operate-btn {
  margin-bottom: 10px;
}
.dialog-footer {
  text-align: center;
}
</style>
