<script setup>
import dayjs from 'dayjs'
import { getMaintainPlanListApi } from '@/api/elevator'
import { operationTypeMap, planTypeMap } from '@/constants/state'

// 3 年前的年月日
const startDate = dayjs().subtract(3, 'year').format('YYYY-MM-DD')
const endDate = dayjs().format('YYYY-MM-DD')
const change = (value) => {
  console.log(value)
  const { fulldate } = value
  // query.value.startTime = `${fulldate} 00:00:00`
  // query.value.endTime = `${fulldate} 23:59:59`
  query.value.planTime = fulldate
  query.value.pageNum = 1
  dataList.value = []
  hasMore.value = true
  getList()
}

const keyValue = reactive([
  { key: '电梯编号', value: '', field: 'elevatorNum' },
  {
    key: '完成状态',
    value: '',
    field: 'finishState',
    format: (item) => (item.finishState ? '是' : '否')
  },
  { key: '计划日期', value: '', field: 'planTime' },
  {
    key: '计划类型',
    value: '',
    field: 'planType',
    format: (item) => planTypeMap[item.planType]
  },
  {
    key: '当前状态',
    value: '',
    field: 'state',
    format: (item) => {
      return operationTypeMap[item.state] || '未知'
    }
  }
])

const dataList = ref([])
const hasMore = ref(true)
const query = ref({
  pageNum: 1,
  pageSize: 10,
  startTime: '',
  endTime: ''
})
const getList = async () => {
  let list = []
  const { error, result } = await getMaintainPlanListApi({
    ...options.value,
    ...query.value
  })

  if (error) {
    return
  }
  list = result.rows
  dataList.value.push(...list)
  hasMore.value = list.length == query.value.pageSize
}

const options = ref({})
onLoad(async (e) => {
  options.value = e
  // const start = `${dayjs().format('YYYY-MM-DD')} 00:00:00`
  // const end = `${dayjs().format('YYYY-MM-DD')} 23:59:59`
  query.value = {
    ...query.value,
    planTime: dayjs().format('YYYY-MM-DD')
    // startTime: start,
    // endTime: end
  }
  await getList()
})

onReachBottom(() => {
  if (!hasMore.value) {
    return
  }
  query.value.pageNum++
  getList()
})
</script>

<template>
  <view>
    <uni-calendar
      :insert="true"
      :lunar="true"
      :start-date="startDate"
      :end-date="endDate"
      :is-extend-day="true"
      @change="change"
    />

    <view mt-30>
      <up-card
        v-for="(item, index) in dataList"
        :key="index"
        :title="item.elevatorNum"
      >
        <template #body>
          <view>
            <up-cell
              v-for="(val, idx) in keyValue"
              :key="idx"
              :title="val.key"
              :value="val.format ? val.format(item) : item[val.field]"
            />
          </view>
        </template>
      </up-card>

      <up-loadmore
        v-if="!hasMore && dataList.length"
        :line="true"
        status="nomore"
      />
    </view>
  </view>
</template>
