<script lang="ts" setup>
import { IotRyDailyReportApi } from '@/api/pms/iotrydailyreport'
import { useUserStore } from '@/store/modules/user'
import download from '@/utils/download'
import { rangeShortcuts } from '@/utils/formatTime'
import { useDebounceFn } from '@vueuse/core'
import ryForm from './ry-form.vue'
import dayjs from 'dayjs'
import RyTable from './ry-table.vue'

defineOptions({ name: 'IotRyDailyReport' })

const { t } = useI18n()

const route = useRoute()

const message = useMessage()

const id = useUserStore().getUser.deptId

const deptId = id

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

const initQuery: Query = {
  pageNo: 1,
  pageSize: 10,
  projectClassification: '1',
  deptId: route.query.deptId ? Number(route.query.deptId) : id,
  createTime: route.query.createTime
    ? (route.query.createTime as string[])
    : [...rangeShortcuts[1].value().map((item) => dayjs(item).format('YYYY-MM-DD HH:mm:ss'))],
  nonProductFlag: route.query.nonProductFlag ? (route.query.nonProductFlag as string) : undefined
}

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

const getRouteCreateTime = () => {
  const createTime = route.query.createTime

  if (Array.isArray(createTime)) {
    return createTime.filter((item): item is string => typeof item === 'string')
  }

  return typeof createTime === 'string'
    ? [createTime]
    : [...rangeShortcuts[1].value().map((item) => dayjs(item).format('YYYY-MM-DD HH:mm:ss'))]
}

const syncQueryFromRoute = () => {
  query.value.deptId = route.query.deptId ? Number(route.query.deptId) : id
  query.value.createTime = getRouteCreateTime()
  query.value.projectClassification = route.query.projectClassification
    ? String(route.query.projectClassification)
    : '1'
}

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

const loading = ref(false)

const loadList = useDebounceFn(async function () {
  loading.value = true
  try {
    const data = await IotRyDailyReportApi.getIotRyDailyReportPage(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,
    () => query.value.nonProductFlag
  ],
  () => {
    handleQuery()
  },
  { immediate: true }
)

watch(
  () => [route.query.deptId, route.query.createTime, route.query.projectClassification],
  () => {
    syncQueryFromRoute()
  }
)

const exportLoading = ref(false)

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

    exportLoading.value = true
    const res = await IotRyDailyReportApi.exportIotRyDailyReport(query.value)

    download.excel(res, '瑞鹰钻井日报.xlsx')
  } finally {
    exportLoading.value = false
  }
}

const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await IotRyDailyReportApi.deleteIotRyDailyReport(id)
    message.success(t('common.delSuccess'))
    await loadList()
  } catch {}
}

const visible = ref(false)

const formRef = ref()

const alarmCollapse = ref<string[]>([])

function handleOpenForm(id: number, type: 'edit' | 'readonly') {
  if (formRef.value) {
    formRef.value.handleOpenForm(id, type)
  }
}
</script>

<template>
  <div
    class="grid grid-cols-[auto_1fr] grid-rows-[48px_1fr_auto] 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-3" />
    <!-- <div class="p-4 bg-white dark:bg-[#1d1e1f] shadow rounded-lg row-span-3"> </div> -->
    <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-input
            v-model="query.contractName"
            placeholder="请输入项目"
            clearable
            @keyup.enter="handleQuery()"
            class="!w-180px" />
        </el-form-item>
        <el-form-item label="任务">
          <el-input
            v-model="query.taskName"
            placeholder="请输入任务"
            clearable
            @keyup.enter="handleQuery()"
            class="!w-180px" />
        </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>
        <el-form-item label="非生产时效" prop="nonProductFlag">
          <el-switch v-model="query.nonProductFlag" active-value="Y" inactive-value="N" />
        </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-ry-daily-report:create']"
            >
              <Icon icon="ep:plus" class="mr-5px" /> 新增
            </el-button> -->
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['pms:iot-ry-daily-report:export']">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>

    <ry-table
      :list="list"
      :total="total"
      :loading="loading"
      :page-no="query.pageNo"
      :page-size="query.pageSize"
      is-index
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange">
      <template #action="{ row }">
        <el-button
          link
          type="primary"
          @click="handleOpenForm(row.id, 'edit')"
          v-hasPermi="['pms:iot-ry-daily-report:update']">
          编辑
        </el-button>
        <el-button
          link
          type="danger"
          @click="handleDelete(row.id)"
          v-hasPermi="['pms:iot-ry-daily-report:delete']">
          删除
        </el-button>
      </template>
    </ry-table>

    <div class="p-1 bg-white dark:bg-[#1d1e1f] rounded-lg shadow">
      <el-collapse v-model="alarmCollapse" class="alarm-collapse">
        <el-collapse-item title="告警提示" name="alarm">
          <div class="flex flex-col gap-2">
            <el-alert
              class="h-8!"
              title="当日油耗大于9000升&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;红色预警"
              type="error"
              show-icon
              :closable="false" />
            <el-alert
              class="h-8!"
              title="进尺工作时间+其它生产时间+非生产时间=24H&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;否则橙色预警"
              type="warning"
              show-icon
              :closable="false" />
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
  </div>

  <ry-form
    v-model:visible="visible"
    type="edit"
    ref="formRef"
    :load-list="loadList"
    no-validate-status />
</template>

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

:deep(.alarm-collapse) {
  border-top: 0;
  border-bottom: 0;

  .el-collapse-item__header {
    height: 32px;
    padding-left: 12px;
    font-size: 15px;
    font-weight: 700;
    line-height: 32px;
    border-bottom: 0;
  }

  .el-collapse-item__wrap {
    border-bottom: 0;
  }

  .el-collapse-item__content {
    padding-bottom: 4px;
  }
}
</style>
