<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="创建人">
          <ElSelect
            v-model="filterForm.creator"
            placeholder="请选择"
            clearable
            filterable
            style="width: 120px"
          >
            <ElOption
              v-for="item in employeeList"
              :key="item.id"
              :label="item.account"
              :value="item.account"
            />
          </ElSelect>
        </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" />
            <ElOption label="雕刻" value="DK" />
            <ElOption label="白胚" value="BP" />
            <ElOption label="其他" value="QT" />
          </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="handleDownload()"
          >
            下载
          </ElButton>
          <ElButton type="primary" link size="small" @click="handlePrintPick()">
            拣货单
          </ElButton>
          <ElButton
            type="primary"
            link
            size="small"
            @click="handlePrintProduction()"
          >
            生产单
          </ElButton>
          <ElButton type="warning" link size="small" @click="handleReArrange(row)">
            重排
          </ElButton>
          <ElButton type="danger" link size="small" @click="handleDelete()">
            删除
          </ElButton>
        </template>
      </TableView>
    </div>

    <ArrangeDialog ref="arrangeDialogRef" @success="loadData" />

    <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'
import ArrangeDialog from './ArrangeDialog.vue'
import { getEmployeeListApi } from '@/api/common'
import type { userData } from '@/types/api/user'

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 employeeList = ref<userData[]>([])
const arrangeDialogRef = ref<InstanceType<typeof ArrangeDialog>>()

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 loadEmployeeList = async () => {
  try {
    const res = await getEmployeeListApi()
    if (res.code !== 200) return
    employeeList.value = res.data || []
  } catch (e) {
    console.error(e)
  }
}

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 handleDownload = () => {
  ElMessage.info('接口待提供')
}

const handlePrintPick = () => {
  ElMessage.info('接口待提供')
}

const handlePrintProduction = () => {
  ElMessage.info('接口待提供')
}

const handleDelete = () => {
  ElMessage.info('接口待提供')
}

const handleReArrange = (row: BatchManageData) => {
  // 后端未提供“批次 -> 商品ID列表”映射时，暂用行 id 作为占位
  arrangeDialogRef.value?.open({
    productIdList: [row.id],
    title: '重排',
    showAutoSwitch: false,
  })
}

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(() => {
  loadEmployeeList()
  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>
