<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.employeeId"
            placeholder="请选择"
            clearable
            filterable
            style="width: 120px"
          >
            <ElOption
              v-for="item in employeeList"
              :key="item.id"
              :label="item.account"
              :value="item.id"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="工艺类型">
          <ElSelect
            v-model="filterForm.craftType"
            placeholder="请选择"
            clearable
            style="width: 120px"
          >
            <ElOption
              v-for="(item, index) in processType"
              :key="index"
              :value="item.value"
              :label="item.label"
            ></ElOption>
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="下载状态">
          <ElSelect
            v-model="filterForm.downloadStatus"
            placeholder="请选择"
            clearable
            style="width: 120px"
          >
            <ElOption label="未下载" :value="0" />
            <ElOption label="已下载" :value="1" />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="排版状态">
          <ElSelect
            v-model="filterForm.syntheticStatus"
            placeholder="请选择"
            clearable
            style="width: 120px"
          >
            <ElOption label="否" :value="0" />
            <ElOption label="是" :value="1" />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="自动排版">
          <ElSelect
            v-model="filterForm.automaticComposing"
            placeholder="请选择"
            clearable
            style="width: 120px"
          >
            <ElOption label="是" :value="1" />
            <ElOption label="否" :value="0" />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="批次号">
          <ElInput
            v-model="filterForm.batchArrangeNumber"
            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
        v-loading="loading"
        :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(row)"
          >
            下载
          </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="refresh" />

    <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="onPageSizeChange"
      @current-change="onCurrentPageChange"
    />
  </div>
</template>

<script setup lang="tsx">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getBatchManageListApi,
  batchDeleteApi,
  downloadBatchMaterialApi,
} from '@/api/factoryOrderNew'
import type { BatchManageData } from '@/types/api/factoryOrderNew'
import type { PaginationData } from '@/types/api'
import TableView from '@/components/TableView.vue'
import ArrangeDialog from './ArrangeDialog.vue'
import { getEmployeeListApi } from '@/api/common'
import type { userData } from '@/types/api/user'
import usePageList from '@/utils/hooks/usePageList'
import { filePath } from '@/api/axios'

const selectedRows = ref<BatchManageData[]>([])
const employeeList = ref<userData[]>([])
const arrangeDialogRef = ref<InstanceType<typeof ArrangeDialog>>()
interface ProcessTypeData {
  label: string
  value: string
}
const processType = ref<ProcessTypeData[]>([
  {
    label: '烫画',
    value: 'TH',
  },
  {
    label: '直喷',
    value: 'ZP',
  },
  {
    label: '刺绣',
    value: 'CX',
  },
  {
    label: '雕刻',
    value: 'DK',
  },
  {
    label: '白胚',
    value: 'BP',
  },
  {
    label: '其他',
    value: 'QT',
  },
])
const getStandardDesignImageText = (value: number): string => {
  const map: Record<number, string> = { 0: '否', 1: '是', 2: '混合' }
  return map[value] ?? '-'
}
const columns = [
  {
    label: '批次号',
    prop: 'batchArrangeNum',
    width: 120,
    align: 'center',
  },
  {
    label: '下载状态',
    slot: 'downloadStatus',
    width: 90,
    align: 'center',
    render: ({ row }: { row: BatchManageData; index: number }) => {
      return (
        <div>
          <el-tag type={row?.downloadStatus ? 'success' : 'danger'}>
            {row?.downloadStatus ? '已下载' : '未下载'}
          </el-tag>
        </div>
      )
    },
  },
  {
    label: '订单数量',
    prop: 'productNum',
    width: 85,
    align: 'center',
  },
  {
    label: '素材数量',
    width: 85,
    prop: 'materialNum',
    align: 'center',
  },
  {
    label: '创建人',
    width: 85,
    prop: 'employeeAccount',
    align: 'center',
  },
  {
    label: '工艺类型',
    width: 150,
    prop: 'craftType',
    align: 'center',
    render: ({ row }: { row: BatchManageData; index: number }) => {
      if (row && !row.craftType) {
        return (
          <div>
            <span>-</span>
          </div>
        )
      }
      const labels: string[] =
        row?.craftType?.split(',') ??
        []
          .map((type: string) => type.trim())
          .map(
            (type: string) =>
              processType.value.find((e: ProcessTypeData) => e.value === type)
                ?.label || type,
          )
          .filter((type: string | undefined) => type !== undefined)

      return (
        <div>
          <span>{labels.join(',')}</span>
        </div>
      )
    },
  },
  {
    label: '规范素材',
    minWidth: 180,
    prop: 'standardDesignImage',
    align: 'center',
    render: ({ row }: { row: BatchManageData }) => {
      return (
        <div>
          <span>
            {getStandardDesignImageText(row?.standardDesignImage ?? 0)}
          </span>
        </div>
      )
    },
  },
  {
    label: '失败原因',
    minWidth: 250,
    prop: 'failReason',
    align: 'left',
    render: ({ row }: { row: BatchManageData; index: number }) => {
      return (
        <div>
          <span v-html={row?.failReason}></span>
        </div>
      )
    },
  },
  {
    label: '创建时间',
    width: 180,
    prop: 'createTime',
    align: 'center',
  },
  {
    label: '完成时间',
    width: 180,
    prop: 'finishTime',
    align: 'center',
  },
  {
    label: '自动排版',
    width: 85,
    prop: 'automaticComposing',
    align: 'center',
    render: ({ row }: { row: BatchManageData; index: number }) => {
      return (
        <div>
          <span>{row?.automaticComposing ? '是' : '否'}</span>
        </div>
      )
    },
  },
  {
    label: '排版参数',
    width: 140,
    prop: 'composingParam',
    align: 'center',
    render: ({ row }: { row: BatchManageData; index: number }) => {
      return (
        <div>
          <span>{row?.composingParam?.split(';').join('\n')}</span>
        </div>
      )
    },
  },
  {
    label: '操作',
    slot: 'operate',
    width: 260,
    align: 'center',
    fixed: 'right',
    prop: 'operate',
  },
]

const filterForm = reactive({
  createTimeRange: [] as string[],
  employeeId: '' as string | number,
  craftType: '',
  downloadStatus: '' as string | number,
  syntheticStatus: '' as string | number,
  automaticComposing: '' as string | number,
  batchArrangeNumber: '',
})

const {
  loading,
  currentPage,
  pageSize,
  total,
  data: tableData,
  onCurrentPageChange,
  onPageSizeChange,
  refresh,
} = usePageList<BatchManageData>({
  initPageSize: 50,
  query: async (current, size) => {
    const { createTimeRange, ...rest } = filterForm
    const params: Record<string, unknown> = { ...rest }
    if (createTimeRange?.length === 2) {
      params.startTime = createTimeRange[0]
      params.endTime = createTimeRange[1]
    }
    const res = await getBatchManageListApi(params, current, size)
    return (res.data || {
      total: 0,
      size,
      current,
      records: [],
    }) as PaginationData<BatchManageData>
  },
})

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('删除成功')
    refresh()
  } catch (e) {
    const err = e as Error & { message?: string }
    ElMessage.error(err?.message || '删除失败')
  }
}

const handleDownload = async (row: BatchManageData) => {
  try {
    await ElMessageBox.confirm('确定下载选中的批次吗？', '提示', {
      type: 'warning',
    })
  } catch {
    return
  }
  try {
    const res = await downloadBatchMaterialApi(row.id)
    if (res.code !== 200) return
    window.open(filePath + res.message)
  } catch (e) {
    console.error(e)
  }
}

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

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

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

const handleReArrange = (row: BatchManageData) => {
  arrangeDialogRef.value?.open({
    productIdList: [row.id],
    title: '重排',
    requestUrl: 'factory/podOrderBatchDownload/reComposingDesignImages',
    showAutoSwitch: false,
  })
}

onMounted(() => {
  loadEmployeeList()
})

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>
