<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 { formatT, rangeShortcuts } from '@/utils/formatTime'
import { useDebounceFn } from '@vueuse/core'
import dayjs from 'dayjs'
import download from '@/utils/download'
import createRdForm from './create-rd-form.vue'

defineOptions({ name: 'IotRdDailyReport' })

const { t } = useI18n()

const router = useRouter()
const route = useRoute()

const message = useMessage()

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: route.query.deptId ? Number(route.query.deptId) : id,
  createTime: route.query.createTime ? (route.query.createTime as string[]) : undefined,
  wellName: route.query.wellName ? (route.query.wellName as string) : undefined,
  taskId: route.query.taskId ? Number(route.query.taskId) : undefined
}

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

interface ListItem {
  createTime: string
  deptName: string
  taskName: string
  rdStatus: string
  productionStatus: string
  nextPlan: string
  cumulativeWorkingWell: number
  cumulativeWorkingLayers: number
  dailyPumpTrips: number
  dailyToolsSand: number
  runCount: number
  bridgePlug: number
  waterVolume: number
  hourCount: number
  dailyFuel: number
  externalRental: string
  malfunction: string
  faultDowntime: 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
  nonProductFlag: boolean
  nonProductionRate: number
  contractName: string
  timeRange: string
  auditStatus: number
  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 formRef = ref()
// const openForm = (type: string, id?: number) => {
//   formRef.value.open(type, id)
// }

const exportLoading = ref(false)

async function handleExport() {
  try {
    await message.exportConfirm()

    exportLoading.value = true
    const res = await IotRdDailyReportApi.exportIotRdDailyReportDetails(query.value)

    download.excel(res, '瑞都日报明细.xlsx')
  } finally {
    exportLoading.value = false
  }
}

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)
//   }
// }

// function handleApprove(id: number) {
//   try {
//     router.push({
//       name: 'FillDailyReportForm',
//       params: {
//         id: id.toString(),
//         mode: 'approval'
//       }
//     })
//   } catch (error) {
//     console.error('跳转审批页面失败:', error)
//   }
// }

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) {
  console.log('row', row)
  if (row && row.projectId === null && row.taskId === null) {
    handleOpenCreateForm(id, type)
    return
  }
  router.push({
    name: 'FillDailyReportForm',
    query: { id: id, mode: type, backpath: route.path }
  })
}

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

<template>
  <div
    class="grid grid-cols-[auto_1fr] grid-rows-[62px_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" />

    <!-- <div class="p-4 bg-white dark:bg-[#1d1e1f] shadow rounded-lg row-span-2"> </div> -->
    <el-form
      size="default"
      class="bg-white dark:bg-[#1d1e1f] rounded-lg shadow px-8 gap-8 flex items-center justify-between"
    >
      <div class="flex items-center gap-8">
        <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-220px"
            :shortcuts="rangeShortcuts"
          />
        </el-form-item>
      </div>
      <el-form-item>
        <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-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="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
                prop="createTime"
                label="创建时间"
                cover-formatter
                :real-value="formCreateTime"
              />
              <zm-table-column prop="deptName" label="施工队伍" />
              <zm-table-column prop="taskName" label="任务" />
              <zm-table-column
                prop="rdStatus"
                :label="t('project.status')"
                :real-value="
                  (row: ListItem) => realValue(DICT_TYPE.PMS_PROJECT_RD_STATUS, row.rdStatus ?? '')
                "
              >
                <template #default="scope">
                  <dict-tag
                    :type="DICT_TYPE.PMS_PROJECT_RD_STATUS"
                    :value="scope.row.rdStatus ?? ''"
                  />
                </template>
              </zm-table-column>
              <zm-table-column
                prop="reportDetails"
                label="当日生产动态"
                width="320"
                :show-overflow-tooltip="false"
              >
                <template #default="{ row }">
                  <div v-if="row.reportDetails && row.reportDetails.length > 0" class="py-2">
                    <el-popover placement="right" trigger="hover" width="320" popper-class="!p-0">
                      <template #reference>
                        <el-badge
                          :value="row.reportDetails.length"
                          type="primary"
                          class="max-w-full"
                        >
                          <div
                            class="w-72 flex flex-col bg-gray-200/80 hover:bg-blue-100 transition-colors relative group cursor-pointer p-2 rounded gap-y-2"
                          >
                            <div class="flex items-center gap-x-2">
                              <div class="flex items-center">
                                <div class="i-carbon-calendar mr-1 -translate-y-[0.5px]"></div>
                                <div class="font-medium mr-2">{{
                                  dayjs(row.createTime).format('YYYY-MM-DD')
                                }}</div>
                                <div class="flex items-center">
                                  <span>{{ formatT(row.reportDetails[0].startTime) }}</span>
                                  <span class="mx-1">-</span>
                                  <span>{{ formatT(row.reportDetails[0].endTime) }}</span>
                                </div>
                              </div>

                              <div class="ml-auto group-hover:text-blue-600 font-medium">
                                {{ row.reportDetails[0].duration }} H
                              </div>
                            </div>
                            <!--
                            <div class="flex items-center">
                              <div class="font-medium flex-shrink-0">施工详情：</div>
                              <el-tooltip
                                effect="dark"
                                :content="row.reportDetails[0].constructionDetail"
                                placement="top"
                                popper-class="max-w-100"
                              >
                                <span
                                  class="font-medium truncate group-hover:text-blue-600 transition-colors"
                                >
                                  {{ row.reportDetails[0].constructionDetail || '-' }}
                                </span>
                              </el-tooltip>
                            </div> -->
                          </div>
                        </el-badge>
                      </template>
                      <el-scrollbar max-height="480px" view-class="!p-3 flex flex-col gap-y-2">
                        <div
                          v-for="(item, index) in row.reportDetails"
                          :key="index"
                          class="flex flex-col bg-gray-200/80 hover:bg-blue-100 transition-colors relative group cursor-pointer p-2 rounded gap-y-2 max-w-80"
                        >
                          <div class="flex items-center gap-x-2">
                            <div class="flex items-center">
                              <div class="i-carbon-calendar mr-1 -translate-y-[0.5px]"></div>
                              <div class="font-medium mr-2">{{
                                dayjs(row.createTime).format('YYYY-MM-DD')
                              }}</div>
                              <div class="flex items-center">
                                <span>{{ formatT(item.startTime) }}</span>
                                <span class="mx-1">-</span>
                                <span>{{ formatT(item.endTime) }}</span>
                              </div>
                            </div>

                            <div class="ml-auto group-hover:text-blue-600 font-medium">
                              {{ item.duration }} H
                            </div>
                          </div>

                          <div class="flex items-center">
                            <div class="font-medium flex-shrink-0">施工详情：</div>
                            <span
                              class="font-medium group-hover:text-blue-600 transition-colors break-all whitespace-pre-wrap"
                            >
                              {{ item.constructionDetail || '-' }}
                            </span>
                          </div>
                        </div>
                      </el-scrollbar>
                    </el-popover>
                  </div>
                  <span v-else class="text-gray-300">-</span>
                </template>
              </zm-table-column>
              <zm-table-column prop="constructionBrief" label="当日施工简报" />
              <zm-table-column prop="nextPlan" label="下步工作计划" />
              <zm-table-column label="当日">
                <zm-table-column prop="cumulativeWorkingWell" label="施工井" />
                <zm-table-column prop="cumulativeWorkingLayers" label="施工层" />
                <zm-table-column prop="dailyPumpTrips" label="泵车台次" />
                <zm-table-column prop="dailyToolsSand" label="仪表/混砂" />
              </zm-table-column>
              <zm-table-column prop="runCount" label="趟数" />
              <zm-table-column prop="bridgePlug" label="桥塞" />
              <zm-table-column prop="waterVolume" label="水方量" />
              <zm-table-column prop="hourCount" label="时间(H)" />
              <zm-table-column prop="dailyFuel" label="油耗(L)" />
              <zm-table-column prop="externalRental" label="外租设备" />
              <zm-table-column prop="malfunction" label="故障情况" />
              <zm-table-column prop="faultDowntime" label="故障误工(H)" />
              <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="nonProductFlag" label="非生产时间填写">
                <template #default="scope">
                  <el-tag
                    :type="
                      scope.row.nonProductFlag || scope.row.processInstanceId === '2'
                        ? 'success'
                        : 'danger'
                    "
                  >
                    {{
                      scope.row.nonProductFlag || scope.row.processInstanceId === '2'
                        ? '已填写'
                        : '未填写'
                    }}
                  </el-tag>
                </template>
              </zm-table-column>
              <zm-table-column prop="contractName" label="项目" />
              <zm-table-column prop="timeRange" label="时间节点" />
              <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 label="操作" width="120" fixed="right">
                <template #default="scope">
                  <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="warning"
                    @click="handleOpenForm(scope.row.id, 'approval')"
                    v-hasPermi="['pms:iot-rd-daily-report:update']"
                    v-if="scope.row.auditStatus === 10"
                  >
                    审批
                  </el-button>
                </template>
              </zm-table-column>
            </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;
}
</style>
