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

const { isWeibao } = storeToRefs(useUserStore())

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

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

const isLeave = ref(false)
const toDetail = ({ id, elevatorNum }) => {
  const queryStr = `id=${id}&elevatorNum=${elevatorNum}`
  switch (currentState.value) {
    case 1:
      navigateTo({
        url: `/pages/views/elevator-maintain/not-started?${queryStr}`,
        events: {
          done: () => reload()
        }
      })
      break
    case 2:
      navigateTo(`/pages/views/elevator-maintain/undone-detail?${queryStr}`)
      break
    default:
      navigateTo({
        url: `/pages/views/elevator-maintain/event-detail?${queryStr}`,
        events: {
          done: () => reload()
        }
      })
      break
  }
}

const parseRepairMaterialData = (info, key) => {
  let { repairMaterialData } = info || '{}'
  try {
    repairMaterialData = JSON.parse(repairMaterialData) || {}
  } catch (error) {
    repairMaterialData = {}
  }
  return repairMaterialData[key] || ''
}

const query = ref({
  // 1 救援 2维修 3 维保
  workType: 2,
  repairAudit: '',
  stateList: '',
  elevatorNum: '',
  elevatorName: ''
})
const {
  paging,
  dataList,
  reload,
  queryHandler: oriQueryHandler,
  clearHandler,
  enterHandler
} = usePaging({
  apiFn: getWorkDataListApi,
  query
})
const queryHandler = (pageNum = 1, pageSize = 10, from) => {
  query.stateList = currentState.value
  setRepairAudit()
  oriQueryHandler(pageNum, pageSize, from, query.value)
}

const setRepairAudit = () => {
  if (currentTab.value === 0) {
    if (isWeibao.value) {
      query.value.repairAudit = 1
    } else {
      query.value.repairAudit = 0
    }
  } else {
    query.value.repairAudit = ''
  }
}

const getPlanTypeName = (planType) => {
  if (planType === 11) {
    return '系统调整优化'
  } else if (planType === 12) {
    return '维修换件'
  }
}

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

onShow(() => {
  if (isLeave.value) {
    reload()
    isLeave.value = false
  }
})
</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
        v-model="query.elevatorName"
        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>
      <z-paging
        ref="paging"
        v-model="dataList"
        :fixed="false"
        @query="queryHandler"
      >
        <up-card
          v-for="(item, index) in dataList"
          :key="index"
          :title="item.elevatorName"
          @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>
                <text v-else text-green>已完成</text>
              </view>
              <up-cell title="电梯名称" :value="item.elevatorName" />
              <up-cell
                title="维修类型"
                :value="getPlanTypeName(item.planType)"
              />
              <up-cell title="创建时间" :value="item.createdTime" />
              <template v-if="item.planType === 12">
                <up-cell
                  title="零部件名称"
                  :value="parseRepairMaterialData(item, 'partName')"
                />
                <up-cell
                  title="规则型号"
                  :value="parseRepairMaterialData(item, 'partModel')"
                />
                <up-cell
                  title="数量"
                  :value="parseRepairMaterialData(item, 'partNum')"
                />
                <up-cell
                  title="材料报价"
                  :value="`${item.materialQuote || 0}元`"
                />
                <up-cell
                  title="人工及杂费"
                  :value="`${item.otherExpenses || 0}元`"
                />
              </template>
              <template v-else>
                <up-cell
                  title="调整优化项目"
                  :value="parseRepairMaterialData(item, 'partName')"
                />
                <up-cell title="费用" :value="`${item.materialQuote || 0}元`" />
              </template>
              <!-- <up-cell title="期望时间" :value="item.expectTime" /> -->
              <up-cell title="维修描述" :value="item.description" />
            </view>
            <view v-if="[1].includes(item.state)" mt-20>
              <up-button size="normal" @click="toDetail(item)">
                去接单
              </up-button>
            </view>
          </template>
        </up-card>
      </z-paging>
    </view>
  </view>

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

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