<script lang="ts" setup>
import { IotRyImproveDailyReportApi } from '@/api/pms/iotryimprovedailyreport'
import { useTableComponents } from '@/components/ZmTable/useTableComponents'
import dayjs from 'dayjs'
import EquipmentForm from './components/equipment-form.vue'
import { useUserStore } from '../../../store/modules/user.js'

defineOptions({ name: 'IotRyEquipmentDailyReport' })

interface ReportRow {
  id: number
  title: string
  createTime: number
  workLocation: string
  workPurpose: string
  relocationDays: number
  productionStatus: string
  nextPlan: string
  personnel: string
  auditStatus: 0 | 10 | 20 | 30 | 40
}

interface Query {
  deptId?: number
  pageNo: number
  pageSize: number
  createTime?: string[]
}

const deptId = useUserStore().getUser.deptId
const loading = ref(false)
const { ZmTable, ZmTableColumn } = useTableComponents<ReportRow>()
const formRef = ref()
const formVisible = ref(false)
const total = ref(0)

const query = ref<Query>({
  deptId: undefined,
  pageNo: 1,
  pageSize: 10,
  createTime: undefined
})

const reportRows = ref<ReportRow[]>([])

async function loadList() {
  loading.value = true
  try {
    const data = await IotRyImproveDailyReportApi.getIotRyImproveDailyReportPage(query.value)
    reportRows.value = data.list || []
    total.value = data.total || 0
  } finally {
    loading.value = false
  }
}

function handleQuery() {
  query.value.pageNo = 1
  loadList()
}

function resetQuery() {
  query.value = {
    pageNo: 1,
    pageSize: 10,
    createTime: undefined
  }
  loadList()
}

function handleSizeChange(val: number) {
  query.value.pageSize = val
  handleQuery()
}

function handleCurrentChange(val: number) {
  query.value.pageNo = val
  loadList()
}

const auditStatusMap = {
  0: { label: '未提交', type: 'info' },
  10: { label: '审批中', type: 'warning' },
  20: { label: '审核通过', type: 'success' },
  30: { label: '审核不通过', type: 'danger' },
  40: { label: '已取消', type: 'info' }
} as const

function getAuditStatus(status?: number) {
  return auditStatusMap[status as keyof typeof auditStatusMap] || auditStatusMap[0]
}

function handleOpenForm(
  type: 'create' | 'edit' | 'detail' | 'approval' | 'modify',
  row?: ReportRow
) {
  formRef.value?.handleOpenForm(type, row)
}

function reloadAfterCreate() {
  query.value.pageNo = 1
  return loadList()
}

watch(() => query.value.deptId, handleQuery)

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

<template>
  <div
    class="grid grid-cols-[auto_1fr] grid-rows-[48px_1fr] gap-x-4 gap-y-3 h-[calc(100vh-20px-var(--top-tool-height)-var(--tags-view-height)-var(--app-footer-height))]">
    <DeptTreeSelect
      :top-id="158"
      :deptId="deptId"
      v-model="query.deptId"
      :show-title="false"
      class="row-span-2" />

    <el-form
      size="default"
      class="bg-white dark:bg-[#1d1e1f] rounded-lg shadow px-6 gap-8 flex items-center justify-between">
      <div class="flex items-center gap-8">
        <el-form-item label="汇报时间">
          <el-date-picker
            v-model="query.createTime"
            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="!w-260px" />
        </el-form-item>
      </div>
      <el-form-item>
        <!-- <el-button
          type="primary"
          @click="handleOpenForm('create')"
          v-hasPermi="['pms:iot-ry-improve-daily-report:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button> -->
        <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-form-item>
    </el-form>

    <div class="bg-white dark:bg-[#1d1e1f] shadow rounded-lg flex flex-col p-4 min-h-0">
      <div class="flex-1 relative">
        <el-auto-resizer class="absolute">
          <template #default="{ width, height }">
            <zm-table
              :data="reportRows"
              :loading="loading"
              :width="width"
              :max-height="height"
              :height="height"
              empty-text="暂无设备搬迁整改项目汇报"
              show-border>
              <zm-table-column type="index" label="序号" width="70" fixed="left" />
              <zm-table-column label="标题" prop="title" fixed="left" />
              <zm-table-column label="施工队伍" prop="deptName" />
              <zm-table-column label="汇报时间" prop="createTime">
                <template #default="{ row }">
                  {{ dayjs(row.createTime).format('YYYY.MM.DD') }}
                </template>
              </zm-table-column>
              <zm-table-column label="工作地点" prop="workLocation" />
              <zm-table-column label="施工目的" prop="workPurpose" />
              <zm-table-column
                label="安全作业天数"
                prop="relocationDays"
                :real-value="(row) => row.relocationDays + '天'"
                cover-formatter />
              <zm-table-column label="施工动态" prop="productionStatus" />
              <zm-table-column label="下步计划" prop="nextPlan" />
              <zm-table-column label="人员情况" prop="personnel" />
              <zm-table-column label="审批状态" prop="auditStatus" width="120">
                <template #default="{ row }">
                  <el-tag :type="getAuditStatus(row.auditStatus).type">
                    {{ getAuditStatus(row.auditStatus).label }}
                  </el-tag>
                </template>
              </zm-table-column>
              <zm-table-column label="操作" width="200" fixed="right" action>
                <template #default="{ row }">
                  <el-button link type="primary" @click="handleOpenForm('detail', row)">
                    查看
                  </el-button>
                  <el-button
                    link
                    type="primary"
                    @click="handleOpenForm('modify', row)"
                    v-hasPermi="['pms:iot-ry-improve-daily-report:modify']">
                    修改
                  </el-button>
                  <el-button
                    v-if="row.status === 0"
                    link
                    type="primary"
                    @click="handleOpenForm('edit', row)"
                    v-hasPermi="['pms:iot-ry-improve-daily-report:update']">
                    编辑
                  </el-button>
                  <el-button
                    v-if="row.auditStatus === 10"
                    link
                    type="primary"
                    @click="handleOpenForm('approval', row)"
                    v-hasPermi="['pms:iot-ry-improve-daily-report:approval']">
                    审批
                  </el-button>
                </template>
              </zm-table-column>
            </zm-table>
          </template>
        </el-auto-resizer>
      </div>
      <div class="mt-3 flex justify-end">
        <el-pagination
          v-model:current-page="query.pageNo"
          v-model:page-size="query.pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>

  <EquipmentForm
    ref="formRef"
    v-model:visible="formVisible"
    :load-list="loadList"
    :reload-after-create="reloadAfterCreate" />
</template>

<style scoped>
:deep(.el-form-item) {
  margin-bottom: 0;
}
</style>
