<template>
  <div class="batch-manage">
    <div class="batch-manage-filter">
      <ElForm class="search-form" :inline="true" :model="filterForm">
        <ElFormItem label="创建时间">
          <el-date-picker
            v-model="filterForm.createTimeRange"
            type="datetimerange"
            value-format="YYYY-MM-DD HH:mm:ss"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            style="width: 320px"
          />
        </ElFormItem>
        <ElFormItem label="创建人">
          <ElInput
            v-model="filterForm.creator"
            placeholder="创建人"
            clearable
            style="width: 120px"
          />
        </ElFormItem>
        <ElFormItem label="工艺类型">
          <ElSelect
            v-model="filterForm.craftType"
            placeholder="请选择"
            clearable
            style="width: 120px"
          >
            <ElOption label="烫画" value="TH" />
            <ElOption label="直喷" value="ZP" />
            <ElOption label="刺绣" value="CX" />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="下载状态">
          <ElSelect
            v-model="filterForm.downloadStatus"
            placeholder="请选择"
            clearable
            style="width: 120px"
          >
            <ElOption label="未下载" value="NOT_DOWNLOADED" />
            <ElOption label="已下载" value="DOWNLOADED" />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="排版状态">
          <ElSelect
            v-model="filterForm.layoutStatus"
            placeholder="请选择"
            clearable
            style="width: 120px"
          >
            <ElOption label="未排版" value="NOT_LAYOUT" />
            <ElOption label="已排版" value="LAYOUT" />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="自动排版">
          <ElSelect
            v-model="filterForm.autoLayout"
            placeholder="请选择"
            clearable
            style="width: 120px"
          >
            <ElOption label="是" :value="true" />
            <ElOption label="否" :value="false" />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="批次号">
          <ElInput
            v-model="filterForm.batchNo"
            placeholder="批次号"
            clearable
            style="width: 140px"
          />
        </ElFormItem>
      </ElForm>
    </div>

    <div class="batch-manage-actions">
      <span class="item">
        <ElButton type="danger" @click="handleBatchDelete">批量删除</ElButton>
      </span>
    </div>

    <div class="batch-manage-table">
      <TableView
        :paginated-data="tableData"
        :columns="columns"
        selectionable
        @selection-change="handleSelectionChange"
      >
        <template #downloadStatus="{ row }">
          <el-tag
            :type="row.downloadStatus === '已下载' ? 'success' : 'info'"
            size="small"
          >
            {{ row.downloadStatus || '未下载' }}
          </el-tag>
        </template>
        <template #operation="{ row }">
          <ElButton type="primary" link size="small" @click="handleView(row)">
            查看
          </ElButton>
          <ElButton
            type="primary"
            link
            size="small"
            @click="handleDownload(row)"
          >
            下载
          </ElButton>
        </template>
      </TableView>
    </div>

    <ElPagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[50, 100, 200, 300]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin: 10px auto 0"
      @size-change="handlePageSizeChange"
      @current-change="handleCurrentPageChange"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getBatchManageListApi, batchDeleteApi } from '@/api/factoryOrderNew'
import type { BatchManageData } from '@/types/api/factoryOrderNew'
import type { CustomColumn } from '@/types/table'
import TableView from '@/components/TableView.vue'

const loading = ref(false)
const tableData = ref<BatchManageData[]>([])
const selectedRows = ref<BatchManageData[]>([])
const currentPage = ref(1)
const pageSize = ref(50)
const total = ref(0)

const columns: CustomColumn<BatchManageData>[] = [
  { key: 'batchNo', prop: 'batchNo', label: '批次号', minWidth: 120 },
  {
    key: 'downloadStatus',
    prop: 'downloadStatus',
    label: '下载状态',
    minWidth: 90,
    align: 'center',
    slot: 'downloadStatus',
  },
  {
    key: 'orderCount',
    prop: 'orderCount',
    label: '订单数量',
    minWidth: 90,
    align: 'center',
  },
  {
    key: 'totalCount',
    prop: 'totalCount',
    label: '全部数量',
    minWidth: 90,
    align: 'center',
  },
  { key: 'creator', prop: 'creator', label: '创建人', minWidth: 80 },
  { key: 'craftType', prop: 'craftType', label: '工艺类型', minWidth: 90 },
  { key: 'timesRange', prop: 'timesRange', label: '次数范围', minWidth: 90 },
  {
    key: 'createTime',
    prop: 'createTime',
    label: '创建时间',
    minWidth: 160,
    sortable: true,
  },
  {
    key: 'createTimeSort',
    prop: 'createTime',
    label: '创建时间排序',
    minWidth: 110,
    sortable: true,
  },
  {
    key: 'extractTimes',
    prop: 'extractTimes',
    label: '提取次数排序',
    minWidth: 110,
    sortable: true,
  },
  {
    key: 'operation',
    label: '操作',
    minWidth: 120,
    fixed: 'right',
    slot: 'operation',
  },
]

const filterForm = reactive({
  createTimeRange: [] as string[],
  startTimeRange: [] as string[],
  finishTimeRange: [] as string[],
  creator: '',
  arrangeGroup: '',
  craftType: '',
  downloadStatus: '',
  layoutStatus: '',
  autoLayout: '' as string | boolean,
  batchNo: '',
})

const loadData = async () => {
  loading.value = true
  try {
    const res = await getBatchManageListApi(
      { ...filterForm },
      currentPage.value,
      pageSize.value,
    )
    const page = res.data
    tableData.value = page?.records || []
    total.value = page?.total || 0
  } catch (_e) {
    tableData.value = []
  } finally {
    loading.value = false
  }
}

const handleSelectionChange = (rows: BatchManageData[]) => {
  selectedRows.value = rows
}

const handleBatchDelete = async () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请先选择数据')
    return
  }
  await ElMessageBox.confirm('确定批量删除选中的批次吗？', '提示', {
    type: 'warning',
  })
  try {
    await batchDeleteApi(selectedRows.value.map((r) => r.id))
    ElMessage.success('删除成功')
    loadData()
  } catch (e) {
    const err = e as Error & { message?: string }
    ElMessage.error(err?.message || '删除失败')
  }
}

const handleView = (row: BatchManageData) => {
  ElMessage.info(`查看批次 ${row.batchNo}`)
}

const handleDownload = (row: BatchManageData) => {
  ElMessage.info(`下载批次 ${row.batchNo}`)
}

const handlePageSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  loadData()
}

const handleCurrentPageChange = (page: number) => {
  currentPage.value = page
  loadData()
}

const refresh = () => {
  currentPage.value = 1
  loadData()
}

onMounted(() => {
  loadData()
})

defineExpose({ refresh })
</script>

<style scoped lang="scss">
.batch-manage {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.batch-manage-filter {
  flex-shrink: 0;
  width: 100%;
  min-width: 0;
}

.batch-manage-actions {
  flex-shrink: 0;
  margin-bottom: 10px;
}

.batch-manage-table {
  flex: 1;
  overflow: auto;
}
.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 0;
  min-width: 0;

  :deep(.el-form-item) {
    margin-right: 10px;
    margin-bottom: 10px;
  }

  :deep(.el-form-item__content) {
    min-width: 0;
  }
}
</style>
