<script setup lang="ts">
import { useTableComponents } from '@/components/ZmTable/useTableComponents'
import {
  IotMaterialRequisitionApi,
  IotMaterialRequisitionVO
} from '@/api/pms/iotmaterialrequisition'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { erpPriceTableColumnFormatter } from '@/utils'

defineOptions({ name: 'IotMaterialRequisition' })

type MaterialRequisitionRow = IotMaterialRequisitionVO & {
  requisitionTime?: string
}

interface QueryParams extends PageParam {
  deptId?: number
  requisitionNumber?: string
  name?: string
  type?: number
  responsiblePerson?: string
  cost?: number
  result?: number
  otherCost?: number
  laborCost?: number
  requisitionTime?: string[]
  reason?: string
  remark?: string
  status?: number
  processInstanceId?: string
  auditStatus?: number
  createTime?: string[]
}

const { t } = useI18n()
const message = useMessage()
const { push } = useRouter()
const { ZmTable, ZmTableColumn } = useTableComponents<MaterialRequisitionRow>()

const initQuery: QueryParams = {
  pageNo: 1,
  pageSize: 10,
  deptId: undefined,
  requisitionNumber: undefined,
  name: undefined,
  type: undefined,
  responsiblePerson: undefined,
  cost: undefined,
  result: undefined,
  otherCost: undefined,
  laborCost: undefined,
  requisitionTime: [],
  reason: undefined,
  remark: undefined,
  status: undefined,
  processInstanceId: undefined,
  auditStatus: undefined,
  createTime: []
}

const queryParams = reactive<QueryParams>({ ...initQuery })
const queryFormRef = ref()
const loading = ref(false)
const exportLoading = ref(false)
const list = ref<MaterialRequisitionRow[]>([])
const total = ref(0)

const getList = async () => {
  loading.value = true
  try {
    const data = await IotMaterialRequisitionApi.getIotMaterialRequisitionPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const resetQuery = () => {
  Object.assign(queryParams, { ...initQuery })
  queryFormRef.value?.resetFields()
  handleQuery()
}

const handleSizeChange = (val: number) => {
  queryParams.pageSize = val
  handleQuery()
}

const handleCurrentChange = (val: number) => {
  queryParams.pageNo = val
  getList()
}

const openForm = (type: 'create' | 'update', id?: number) => {
  if (type === 'update' && typeof id === 'number') {
    push({ name: 'IotMaterialRequisitionEdit', params: { id } })
    return
  }

  push({ name: 'IotMaterialRequisitionAdd', params: {} })
}

const detail = (id?: number) => {
  push({ name: 'IotMaterialReqDetail', params: { id } })
}

const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await IotMaterialRequisitionApi.deleteIotMaterialRequisition(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await IotMaterialRequisitionApi.exportIotMaterialRequisition(queryParams)
    download.excel(data, '物料领用.xls')
  } finally {
    exportLoading.value = false
  }
}

const formatNumber = (value: unknown) => erpPriceTableColumnFormatter(null, null, value, null)

onMounted(() => {
  getList()
})
</script>

<template>
  <div
    class="iot-material-requisition-page grid grid-rows-[auto_1fr] gap-4 h-[calc(100vh-20px-var(--top-tool-height)-var(--tags-view-height)-var(--app-footer-height))]"
  >
    <el-form
      ref="queryFormRef"
      :model="queryParams"
      size="default"
      label-width="90px"
      class="iot-material-requisition-query bg-white dark:bg-[#1d1e1f] rounded-lg shadow px-6 py-3 min-w-0"
    >
      <div class="query-row">
        <el-form-item label="领用单编号" prop="requisitionNumber">
          <el-input
            v-model="queryParams.requisitionNumber"
            placeholder="请输入物料领用单编号"
            clearable
            class="query-control"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="领用日期" prop="requisitionTime">
          <el-date-picker
            v-model="queryParams.requisitionTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            class="query-control query-control--date"
          />
        </el-form-item>
      </div>

      <el-form-item class="query-actions">
        <el-button type="primary" @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />搜索
        </el-button>
        <el-button @click="resetQuery"> <Icon icon="ep:refresh" class="mr-5px" />重置 </el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['pms:iot-material-requisition:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" />新增
        </el-button>
        <el-button
          type="success"
          plain
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['pms:iot-material-requisition:export']"
        >
          <Icon icon="ep:download" class="mr-5px" />导出
        </el-button>
      </el-form-item>
    </el-form>

    <div class="bg-white dark:bg-[#1d1e1f] shadow rounded-lg flex flex-col p-4 min-w-0 min-h-0">
      <div class="flex-1 relative min-h-0">
        <el-auto-resizer class="absolute">
          <template #default="{ width, height }">
            <ZmTable
              :data="list"
              :loading="loading"
              :width="width"
              :height="height"
              :max-height="height"
              show-border
            >
              <ZmTableColumn
                type="index"
                :label="t('monitor.serial')"
                :width="70"
                fixed="left"
                hide-in-column-settings
              />
              <ZmTableColumn
                prop="requisitionNumber"
                label="领用单编号"
                min-width="170"
                fixed="left"
              />
              <ZmTableColumn prop="name" label="领用单名称" min-width="180" />
              <ZmTableColumn prop="responsiblePerson" label="领用人姓名" min-width="130" />
              <ZmTableColumn prop="cost" label="总费用" min-width="110">
                <template #default="{ row }">
                  {{ formatNumber(row.cost) }}
                </template>
              </ZmTableColumn>
              <ZmTableColumn prop="requisitionTime" label="领用日期" min-width="180">
                <template #default="{ row }">
                  {{ dateFormatter(row, null, row.requisitionTime) }}
                </template>
              </ZmTableColumn>
              <ZmTableColumn label="操作" width="150" fixed="right" action>
                <template #default="{ row }">
                  <el-button
                    link
                    type="primary"
                    @click="detail(row.id)"
                    v-hasPermi="['pms:iot-material-requisition:query']"
                  >
                    {{ t('operationFill.view') }}
                  </el-button>
                  <el-button
                    link
                    type="primary"
                    @click="openForm('update', row.id)"
                    v-hasPermi="['pms:iot-material-requisition:update']"
                  >
                    编辑
                  </el-button>
                  <el-button
                    link
                    type="danger"
                    @click="handleDelete(row.id)"
                    v-hasPermi="['pms:iot-material-requisition:delete']"
                  >
                    删除
                  </el-button>
                </template>
              </ZmTableColumn>
            </ZmTable>
          </template>
        </el-auto-resizer>
      </div>

      <div class="h-8 mt-2 flex items-center justify-end">
        <el-pagination
          v-show="total > 0"
          size="default"
          :current-page="queryParams.pageNo"
          :page-size="queryParams.pageSize"
          :background="true"
          :page-sizes="[10, 20, 30, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
.iot-material-requisition-query {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  gap: 12px 24px;
}

.query-row {
  display: flex;
  flex: 1 1 auto;
  flex-wrap: wrap;
  align-items: center;
  gap: 12px 22px;
  min-width: 0;
}

.query-actions {
  flex: 0 0 auto;
}

.query-actions :deep(.el-form-item__content) {
  display: flex;
  flex-wrap: wrap;
  gap: 8px 10px;
}

.query-actions :deep(.el-button) {
  margin-left: 0;
}

.query-control {
  width: 220px;
}

.query-control--date {
  width: 240px;
}

:deep(.el-form-item) {
  margin-bottom: 0;
}

@media (width >= 1800px) {
  .iot-material-requisition-query,
  .query-row {
    flex-wrap: nowrap;
  }
}

@media (width <= 1500px) {
  .iot-material-requisition-query,
  .query-row {
    gap: 12px 18px;
  }

  .query-control {
    width: 200px;
  }

  .query-control--date {
    width: 220px;
  }
}

@media (width <= 1200px) {
  .iot-material-requisition-page {
    grid-template-rows: auto minmax(480px, 1fr);
    height: auto;
    min-height: calc(
      100vh - 20px - var(--top-tool-height) - var(--tags-view-height) - var(--app-footer-height)
    );
  }

  .query-actions {
    width: 100%;
  }
}

@media (width <= 768px) {
  .iot-material-requisition-query {
    padding: 12px;
  }

  .query-row,
  .query-row :deep(.el-form-item),
  .query-actions {
    width: 100%;
  }

  .query-control,
  .query-control--date {
    width: 100%;
  }

  .query-actions :deep(.el-form-item__content) {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 8px;
    width: 100%;
  }

  .query-actions :deep(.el-button) {
    width: 100%;
    margin-left: 0;
  }
}
</style>
