<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="primary" @click="refresh">查询</ElButton>
      </span>
      <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 #operate="{ row }">
          <ElButton
            :disabled="
              (!row.url && !row.tiffUrl) || row.enableArrange === false
            "
            link
            type="primary"
            size="small"
            @click="handleDownload(row)"
          >
            下载
          </ElButton>
          <ElButton
            type="primary"
            link
            size="small"
            @click="handlePrintPick(row)"
          >
            拣货单
          </ElButton>
          <ElButton
            type="primary"
            link
            size="small"
            @click="handlePrintProduction(row)"
          >
            生产单
          </ElButton>
          <ElButton
            type="warning"
            link
            size="small"
            @click="handleReArrange(row)"
          >
            重排
          </ElButton>
          <ElButton
            type="danger"
            link
            size="small"
            @click="handleBatchDelete(row)"
          >
            删除
          </ElButton>
        </template>
      </TableView>
    </div>

    <ArrangeDialog
      ref="arrangeDialogRef"
      :submit-api="submitBatchDownloadDesignImagesApi"
      @success="refresh"
    />

    <div class="table-pagination-bar">
      <div class="selected-count-text">
        已选择
        <strong style="color: red">{{ selectedRows.length }}</strong> 条数据
      </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: 0 auto"
        @size-change="onPageSizeChange"
        @current-change="onCurrentPageChange"
      />
    </div>
  </div>
</template>

<script setup lang="tsx">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getBatchManageListApi,
  batchDeleteApi,
  downloadBatchMaterialApi,
  printPickPdfByBatchNumberApi,
  printProductionPdfByBatchNumberApi,
} 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'
import { batchDownloadDesignImagesApi } from '@/api/factoryOrderNew'

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: 180,
    align: 'center',
  },
  {
    label: '下载状态',
    slot: 'downloadStatus',
    width: 90,
    align: 'center',
    render: (row: BatchManageData) => {
      return (
        <div>
          <el-tag type={row?.downloadStatus ? 'success' : 'danger'}>
            {row?.downloadStatus ? '已下载' : '未下载'}
          </el-tag>
        </div>
      )
    },
  },
  {
    label: '订单数量',
    prop: 'operationNum',
    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: BatchManageData) => {
      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: BatchManageData) => {
      return (
        <div>
          <span>
            {getStandardDesignImageText(row?.standardDesignImage ?? 0)}
          </span>
        </div>
      )
    },
  },
  {
    label: '失败原因',
    minWidth: 300,
    prop: 'failReason',
    align: 'left',
    render: (row: BatchManageData) => {
      return (
        <div style="white-space: pre-line">
          <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: BatchManageData) => {
      return (
        <div>
          <span>{row?.automaticComposing ? '是' : '否'}</span>
        </div>
      )
    },
  },
  {
    label: '排版参数',
    width: 140,
    prop: 'composingParam',
    align: 'left',
    render: (row: BatchManageData) => {
      return (
        <div style="white-space: pre-line">
          <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 (row?: BatchManageData) => {
  let ids
  if (!row) {
    if (!selectedRows.value.length) {
      ElMessage.warning('请先选择数据')
      return
    }
    ids = selectedRows.value.map((r) => r.id)
  } else {
    ids = [row.id]
  }
  try {
    await ElMessageBox.confirm('确定删除选中的数据吗？', '提示', {
      type: 'warning',
    })
  } catch {
    return
  }
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await batchDeleteApi(ids)
    if (res.code !== 200) return
    ElMessage.success(res.message)
    refresh()
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}

const handleDownload = async (row: BatchManageData) => {
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  const type = row.url && row.tiffUrl ? 'tiff' : row.url ? 'png' : 'tiff'
  try {
    const res = await downloadBatchMaterialApi(row.id, type)
    if (res.code !== 200) return
    window.open(filePath + res.message, '_blank')
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}

const submitBatchDownloadDesignImagesApi = (params: {
  productIdList?: number[]
  templateWidth?: number
  type?: string
}) => {
  return batchDownloadDesignImagesApi({
    id: params.productIdList?.[0] as number,
    templateWidth: params.templateWidth,
    type: params.type,
  })
}

const handlePrintPick = async (row: BatchManageData) => {
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })

  try {
    const res = await printPickPdfByBatchNumberApi({
      batchArrangeNumber: row.batchArrangeNum as string,
    })

    if (res?.code !== 200) return
    ElMessage.success('操作成功')
    window.open(filePath + res?.message)
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}

const handlePrintProduction = async (row: BatchManageData) => {
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })

  try {
    const res = await printProductionPdfByBatchNumberApi({
      batchArrangeNumber: row.batchArrangeNum as string,
    })

    if (res?.code !== 200) return
    ElMessage.success('操作成功')
    window.open(filePath + res?.message)
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}

const handleReArrange = (row: BatchManageData) => {
  arrangeDialogRef.value?.open({
    productIdList: [row.id],
    title: '重排',
    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;
}

.table-pagination-bar {
  margin-top: 10px;
  display: flex;
  align-items: center;
}

.selected-count-text {
  font-size: 14px;
  color: #606266;
  white-space: nowrap;
}

.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>
