<script setup>
import { adminTabs, maintainTabs } from 'constants/work'
import dayjs from 'dayjs'
import { useUniApi } from 'hooks/use-uni-api'
import { getWorkDataListApi } from '@/api/elevator'
import { usePaging } from '@/composables/use-paging'
import { planTypeMap } from '@/constants/state'
import { useUserStore } from '@/store/user'
const { navigateTo } = useUniApi()

const tabs = ref([])
const currentTab = ref(0)
const currentState = ref(0)
const handleTab = (e) => {
  console.log('handleTab', e)
  const { index, stateList, state } = e
  currentTab.value = index
  currentState.value = state
  query.value.stateList = stateList
  reload()
}

const query = ref({
  // 1 救援 2维修 3 维保
  workType: 3,
  stateList: '',
  elevatorNum: '',
  elevatorName: ''
})
const { paging, dataList, reload, queryHandler, clearHandler, enterHandler } =
  usePaging({
    apiFn: getWorkDataListApi,
    query
  })

const addHandler = () => {
  const { id, elevatorNum, enterType } = options.value
  if (enterType === 'hasId') {
    navigateTo(
      `/pages/views/elevator-maintenance/create?id=${id}&elevatorNum=${elevatorNum}`
    )
  } else {
    navigateTo(
      '/pages/views/choose-elevator/index?redirect=/pages/views/elevator-maintenance/create'
    )
  }
}

// 期望时间 关联电梯 电梯地址 维保人员 物业是否评价 工作描述
const keyValue = reactive([
  {
    key: '维保时长',
    field: 'maintenanceTime',
    showFunc: (item) => {
      return [4, 7].includes(item.state)
    }
  },
  {
    key: '维保类型',
    format: (item) => {
      const { planType } = item
      return planType ? `${planTypeMap[planType]}维保` : ''
    }
  },
  { key: '期望时间', value: '', field: 'expectTime' },
  { key: '关联电梯', value: '', field: 'elevatorName' },
  { key: '电梯地址', value: '', field: 'elevatorAddress' },
  {
    key: '维保人员',
    value: '',
    field: 'receiveStaff',
    showFunc: (item) => {
      return ![1].includes(item.state)
    }
  },
  {
    key: '协同人员',
    field: 'collaborator',
    showFunc: (item) => {
      return ![1].includes(item.state)
    }
  },
  // {
  //   key: '物业是否评价',
  //   value: '',
  //   field: '',
  //   format: (item) => {
  //     return item.isEvaluation ? '是' : '否'
  //   }
  // },
  { key: '工作描述', value: '', field: 'description' }
])
const toDetail = ({ id, elevatorNum }) => {
  const queryStr = `id=${id}&elevatorNum=${elevatorNum}`
  switch (currentState.value) {
    case 1:
      navigateTo({
        url: `/pages/views/elevator-maintenance/not-started?${queryStr}`,
        events: {
          done: () => reload()
        }
      })
      break
    case 2:
      navigateTo(`/pages/views/elevator-maintenance/undone-detail?${queryStr}`)
      break
    default:
      navigateTo(`/pages/views/elevator-maintenance/detail?${queryStr}`)
      break
  }
}
// 是否超期
const isOverdue = (item) => {
  const { expectTime, finishTime } = item
  // dayjs对比 期望时间和当前时间
  const diffDay = finishTime ? dayjs(finishTime) : dayjs()
  const day = diffDay.diff(dayjs(expectTime), 'day')
  if (day > 0) {
    return '超期'
  }
  return '未超期'
}

const { isWeibao } = storeToRefs(useUserStore())
const options = ref({})
onLoad(async (e) => {
  options.value = e

  const { elevatorNum } = options.value
  query.value.elevatorNum = elevatorNum || ''

  let currTab
  if (isWeibao.value) {
    [currTab] = tabs.value = maintainTabs
  } else {
    [currTab] = tabs.value = adminTabs
  }
  currentState.value = currTab.state
  query.value.stateList = currTab.stateList
})
</script>

<template>
  <view class="elevator-rescue" w-full h-100vh flex-col f-s-c bg="#F8F8F8">
    <view w-full>
      <up-tabs
        :current="currentTab"
        :list="tabs"
        :scrollable="false"
        :item-style="{
          width: '50%',
          height: '80rpx'
        }"
        :active-style="{
          color: '#3c9cff',
          fontWeight: 'bold'
        }"
        @click="handleTab"
      />
    </view>

    <view f-c-c mt-8 w-full flex-none bg-white>
      <up-input
        placeholder="请输入电梯名称"
        prefix-icon="search"
        prefix-icon-style="font-size: 22px;color: #909399"
        clearable
        :border="`${'none'}`"
        :custom-style="{
          height: '80rpx',
          padding: '0 20rpx'
        }"
        @clear="
          () => {
            query.elevatorName = ''
            clearHandler()
          }
        "
        @confirm="enterHandler"
      />
    </view>

    <view w-full flex-auto overflow-hidden mt-8 bg-white>
      <scroll-view :scroll-y="true" h-full>
        <z-paging
          ref="paging"
          v-model="dataList"
          :fixed="false"
          @query="queryHandler"
        >
          <up-card
            v-for="(item, index) in dataList"
            :key="index"
            :title="`发布人员：${item.publisher || '未知'}`"
            @click="toDetail(item)"
          >
            <template #body>
              <view>
                <view px-30 text-36 font-500 f-c-c justify-between>
                  <text v-if="[1].includes(item.state)" text-red>未接单</text>
                  <text v-else-if="[2, 3].includes(item.state)" text-amber>
                    进行中
                  </text>
                  <template v-else>
                    <text text-green>已完成</text>
                    <text text-28 text="#909399">{{ item.finishTime }}</text>
                  </template>
                </view>

                <up-cell title="是否超期" :value="isOverdue(item)" />
                <template v-for="(val, idx) in keyValue" :key="idx">
                  <up-cell
                    v-if="val.showFunc ? val.showFunc(item) : true"
                    :title="val.key"
                    :value="val.format ? val.format(item) : item[val.field]"
                  />
                </template>
              </view>
            </template>
          </up-card>
        </z-paging>
      </scroll-view>
    </view>
  </view>

  <FloatFixedAddBtn @click="addHandler" />
</template>

<style>
.elevator-rescue .u-tabs {
  background-color: #fff !important;
}
</style>
