<script lang="ts" setup>
import { IotRdDailyReportApi } from '@/api/pms/iotrddailyreport'
import { useTableComponents } from '@/components/ZmTable/useTableComponents'
import { useUserStore } from '@/store/modules/user'
import { DICT_TYPE, getDictOptions } from '@/utils/dict'
import { rangeShortcuts } from '@/utils/formatTime'
import { useDebounceFn } from '@vueuse/core'
import dayjs from 'dayjs'
import createRdForm from './create-rd-form.vue'

defineOptions({ name: 'FillDailyReport' })

const router = useRouter()

const id = useUserStore().getUser.deptId

const deptId = id

interface Query {
  deptId?: number
  contractName?: string
  taskName?: string
  createTime?: string[]
  wellName?: string
  taskId?: number
  pageNo: number
  pageSize: number
}

const initQuery: Query = {
  pageNo: 1,
  pageSize: 10,
  deptId: id
}

const query = ref<Query>({ ...initQuery })

interface ListItem {
  createTime: string
  status: string
  auditStatus: number
  deptName: string
  contractName: string
  taskName: string
  nonProductionRate: number
  accidentTime: number
  repairTime: number
  selfStopTime: number
  complexityTime: number
  relocationTime: number
  rectificationTime: number
  waitingStopTime: number
  winterBreakTime: number
  partyaDesign: number
  partyaPrepare: number
  partyaResource: number
  otherNptTime: number
  otherNptReason: string
  responsiblePersonNames: string
  submitterNames: string
  nonProductFlag: boolean
  projectId?: number
  taskId?: number
}

const list = ref<ListItem[]>([])
const total = ref(0)

const loading = ref(false)

const loadList = useDebounceFn(async function () {
  loading.value = true
  try {
    const data = await IotRdDailyReportApi.getIotRdDailyReportPage(query.value)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
})

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

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

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

function resetQuery() {
  query.value = { ...initQuery }

  handleQuery()
}

watch(
  [
    () => query.value.deptId,
    () => query.value.contractName,
    () => query.value.taskName,
    () => query.value.createTime
  ],
  () => {
    handleQuery()
  },
  { immediate: true }
)

// const openForm = (_type: string, id?: number, istime: string = 'false') => {
//   router.push({
//     name: 'FillDailyReportForm',
//     params: { id: id, mode: 'fill' },
//     query: { istime: istime }
//   })
// }

const visible = ref(false)

const formRef = ref()

const isview = ref<'create' | 'detail' | 'time'>('create')
const viewId = ref<number>()

function handleOpenCreateForm(id?: number, type?: any) {
  if (formRef.value) {
    if (id) {
      viewId.value = id
      isview.value = type
    }
    formRef.value.handleOpenForm()
  }
}

function handleOpenForm(id: number, type: 'edit' | 'detail' | 'approval' | 'time', row?: ListItem) {
  if (row && row.projectId === null && row.taskId === null) {
    handleOpenCreateForm(id, type)
    return
  }
  router.push({
    name: 'FillDailyReportForm',
    query: { id: id, mode: type, backpath: route.path }
  })
}

const route = useRoute()

onMounted(() => {
  if (route.query.mode) {
    handleOpenForm(
      Number(route.query.id),
      route.query.mode as 'edit' | 'detail' | 'approval' | 'time'
    )
  }
})

const { ZmTable, ZmTableColumn } = useTableComponents<ListItem>()

function formCreateTime(row: ListItem) {
  return dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss')
}

function realValue(type: any, value: string) {
  const option = getDictOptions(type).find((item) => item.value === value)
  return option?.label || value
}

// function handleDetail(id: number) {
//   try {
//     router.push({
//       name: 'FillDailyReportForm',
//       params: {
//         id: id.toString(),
//         mode: 'detail'
//       }
//     })
//   } catch (error) {
//     console.error('跳转详情页面失败:', error)
//   }
// }
</script>

<template>
  <div
    class="grid grid-cols-[auto_minmax(0,1fr)] grid-rows-[auto_minmax(0,1fr)] gap-4 h-[calc(100vh-20px-var(--top-tool-height)-var(--tags-view-height)-var(--app-footer-height))]">
    <DeptTreeSelect
      :top-id="163"
      :deptId="deptId"
      v-model="query.deptId"
      :show-title="false"
      class="row-span-2" />

    <!-- <div class="p-4 bg-white dark:bg-[#1d1e1f] shadow rounded-lg row-span-2"> </div> -->
    <el-form
      size="default"
      :model="query"
      class="bg-white dark:bg-[#1d1e1f] rounded-lg shadow px-8 py-3 gap-6 flex items-center justify-between flex-wrap min-w-0">
      <div class="flex items-center gap-6 flex-wrap">
        <el-form-item label="项目">
          <el-input
            v-model="query.contractName"
            placeholder="请输入项目"
            clearable
            @keyup.enter="handleQuery()"
            class="!w-240px" />
        </el-form-item>
        <el-form-item label="任务">
          <el-input
            v-model="query.taskName"
            placeholder="请输入任务"
            clearable
            @keyup.enter="handleQuery()"
            class="!w-240px" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <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-300px max-w-full"
            :shortcuts="rangeShortcuts" />
        </el-form-item>
      </div>
      <el-form-item class="daily-report-actions shrink-0">
        <div class="flex flex-wrap items-center justify-end gap-3">
          <el-button
            type="primary"
            @click="handleOpenCreateForm()"
            v-hasPermi="['pms:iot-rd-daily-report:update']">
            新增日报
          </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>
        </div>
        <!-- <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['pms:iot-rd-daily-report:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button> -->
        <!-- <el-button type="success" plain @click="handleExport" :loading="exportLoading">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button> -->
      </el-form-item>
    </el-form>
    <div class="min-h-0 bg-white dark:bg-[#1d1e1f] shadow rounded-lg flex flex-col p-4">
      <div class="flex-1 relative">
        <el-auto-resizer class="absolute">
          <template #default="{ width, height }">
            <zm-table
              :data="list"
              :loading="loading"
              :width="width"
              :max-height="height"
              :height="height"
              show-border>
              <zm-table-column label="操作" width="140" fixed="left" action>
                <template #default="scope">
                  <el-button
                    link
                    type="primary"
                    @click="handleOpenForm(scope.row.id, 'edit')"
                    v-hasPermi="['pms:iot-rd-daily-report:update']"
                    v-if="scope.row.status === 0">
                    填报
                  </el-button>
                  <el-button
                    link
                    type="success"
                    @click="handleOpenForm(scope.row.id, 'detail', scope.row)"
                    v-hasPermi="['pms:iot-rd-daily-report:query']">
                    查看
                  </el-button>
                  <el-button
                    link
                    :type="
                      scope.row.nonProductFlag || scope.row.processInstanceId === '2'
                        ? 'success'
                        : 'warning'
                    "
                    @click="handleOpenForm(scope.row.id, 'time', scope.row)"
                    v-hasPermi="['pms:iot-rd-daily-report:non-productive']"
                    v-if="scope.row.auditStatus === 20">
                    时效
                  </el-button>
                </template>
              </zm-table-column>
              <zm-table-column
                prop="createTime"
                label="创建时间"
                cover-formatter
                :real-value="formCreateTime" />
              <zm-table-column
                prop="status"
                label="日报状态"
                cover-formatter
                :real-value="
                  (row: ListItem) =>
                    realValue(DICT_TYPE.OPERATION_FILL_ORDER_STATUS, row.status ?? '')
                ">
                <template #default="scope">
                  <dict-tag
                    :type="DICT_TYPE.OPERATION_FILL_ORDER_STATUS"
                    :value="scope.row.status" />
                </template>
              </zm-table-column>
              <zm-table-column prop="auditStatus" label="审批状态">
                <template #default="scope">
                  <el-tag v-if="scope.row.auditStatus === 0" type="info">
                    {{ '待提交' }}
                  </el-tag>
                  <el-tag v-else-if="scope.row.auditStatus === 10">
                    {{ '待审批' }}
                  </el-tag>
                  <el-tag v-else-if="scope.row.auditStatus === 20" type="success">
                    {{ '审批通过' }}
                  </el-tag>
                  <el-tag v-else-if="scope.row.auditStatus === 30" type="danger">
                    {{ '审批拒绝' }}
                  </el-tag>
                </template>
              </zm-table-column>
              <zm-table-column prop="deptName" label="施工队伍" />
              <zm-table-column prop="contractName" label="项目" />
              <zm-table-column prop="taskName" label="任务" />
              <zm-table-column
                prop="nonProductionRate"
                label="非生产时效"
                cover-formatter
                :real-value="
                  (row) => (Number(row.nonProductionRate ?? 0) * 100).toFixed(2) + '%'
                " />
              <zm-table-column label="非生产时间">
                <zm-table-column prop="accidentTime" label="工程质量" />
                <zm-table-column prop="repairTime" label="设备故障" />
                <zm-table-column prop="selfStopTime" label="设备保养" />
                <zm-table-column prop="complexityTime" label="技术受限" />
                <zm-table-column prop="relocationTime" label="生产配合" />
                <zm-table-column prop="rectificationTime" label="生产组织" />
                <zm-table-column prop="waitingStopTime" label="不可抗力" />
                <zm-table-column prop="winterBreakTime" label="待命" />
                <zm-table-column prop="partyaDesign" label="甲方设计" />
                <zm-table-column prop="partyaPrepare" label="甲方准备" />
                <zm-table-column prop="partyaResource" label="甲方资源" />
                <zm-table-column prop="otherNptTime" label="其它非生产时间" />
              </zm-table-column>
              <zm-table-column prop="otherNptReason" label="其他非生产时间原因" />
              <zm-table-column prop="responsiblePersonNames" label="带班干部" />
              <zm-table-column prop="submitterNames" label="填报人" />
            </zm-table>
          </template>
        </el-auto-resizer>
      </div>
      <div class="h-10 mt-4 flex items-center justify-end">
        <el-pagination
          size="default"
          v-show="total > 0"
          v-model:current-page="query.pageNo"
          v-model:page-size="query.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>
  <create-rd-form
    :isview="isview"
    :id="viewId"
    ref="formRef"
    :load-list="loadList"
    v-model:visible="visible" />
  <!-- <IotRdDailyReportForm ref="formRef" @success="loadList" /> -->
</template>

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

.daily-report-actions :deep(.el-button + .el-button) {
  margin-left: 0;
}
</style>
