<script lang="ts" setup>
import { executeCommandAPI } from '@/api/centerControl'
import { acceptWorkOrderAPI, getScanBikeInfoBycodeAPI } from '@/api/work'
import { common_btn_style } from '@/configs'
import { useAppStore } from '@/store'
import { getImageFullPath } from '@/utils'
import { charge_toolbar_list } from '../config'

const appStore = useAppStore()
interface DetailType {
  bikeCode: string
  orders: any[]
  soc: number
  location: {
    latitude: number
    longitude: number
  }
  online: boolean
  speed?: number
  chineseLocation?: string
  usageStatus: number
  latestTime: string
  distance: string
}
const type = ref<number | string>('')// 工单类型

const detail = ref<DetailType>({
  bikeCode: '',
  orders: [],
  soc: 0,
  location: {
    latitude: 0,
    longitude: 0,
  },
  online: false,
  latestTime: '',
  chineseLocation: '',
  usageStatus: 1,
  distance: '',
})
async function ringCar() {
  uni.showLoading({
    title: '执行中...',
  })
  try {
    const result: boolean = await executeCommandAPI({
      bikeCode: detail.value.bikeCode,
      commandCode: 'FIND_BIKE',
    })
    if (result) {
      uni.showToast({
        title: '执行成功',
        icon: 'success',
      })
    }
    else {
      uni.showToast({
        title: '执行失败',
        icon: 'error',
      })
    }
  }
  catch (e) {
    uni.showToast({
      title: '执行异常',
      icon: 'error',
    })
  }
  finally {
    uni.hideLoading()
  }
}

// 获取车辆电量样式
function getBatteryStyle(soc: number) {
  const normalizedSoc = Math.max(0, Math.min(100, Number(soc) || 0))

  // 2. 过滤掉离线配置，再匹配对应电量区间
  const matchedItem = charge_toolbar_list
    .filter(item => item.type !== 'offline') // 排除离线项
    .find((item) => {
      const [min, max] = item.section
      return normalizedSoc >= min && normalizedSoc <= max
    })

  const targetItem = matchedItem || charge_toolbar_list.find(item => item.type === 'low')

  return {
    icon: targetItem?.icon || '',
    color: targetItem?.color || '',
    bgColor: targetItem?.activeBgColor || '',
    name: targetItem?.name || '',
  }
}

// 导航
function navToMap() {
  if (!detail.value.location.latitude || !detail.value.location.longitude) {
    return uni.showToast({
      title: '暂无数据',
      icon: 'none',
    })
  }
  uni.openLocation({
    latitude: detail.value.location.latitude,
    longitude: detail.value.location.longitude, // 目标经度
    name: `编号${detail.value.bikeCode}位置`, // 位置名称
    address: detail.value.chineseLocation, // 详细地址
    success: () => {
      console.log('唤起导航成功')
    },
    fail: (err) => {
      console.error('唤起导航失败', err)
    },
  })
}

// 去完成
function complete(type: number | string, orderId: string, bikeCode: string) {
  let url = ''
  switch (type) {
    case 1:
      url = '/pages-sub/warehouse/polling/polling'
      break
    case 2:
      url = '/pages-sub/changebatteries/changebatteries'
      break
    case 3:
      url = '/pages-sub/warehouse/dispatch/dispatch'
      break
    case 4:
      url = '/pages-sub/warehouse/inspection/inspection'
      break
  }
  uni.navigateTo({
    url: `${url}?orderId=${orderId}&bikeCode=${bikeCode}`,
  })
}

// 初始化
function init(info: any, orderType: number | string) {
  type.value = orderType
  detail.value = info
}
//  详情
function navDetail(bikeCode: string) {
  uni.navigateTo({
    url: `/pages-sub/common/carDetail?bikeCode=${bikeCode}`,
  })
}

/***
 *创建工单判断状态
 * @returns {string} complete:完成 create:创建 accept:接单 occupy:已有人接单
 **/

function createOrderStatus(): 'complete' | 'create' | 'accept' | 'occupy' | 'allBikesTake' {
  const { orders } = detail.value

  if (!type.value || type.value === 'all') {
    return 'allBikesTake'
  }

  // 这里是对应的去完成工单
  if (orders.length > 0) {
    const indexs = orders.findIndex(item => item.orderType === type.value)
    if (indexs !== -1) {
      const { acceptSelf, accepted } = orders[indexs]

      if (acceptSelf) {
        return 'complete'
      }
      else if (!accepted && !acceptSelf) {
        return 'accept'
      }
      else {
        return 'occupy'
      }
    }
    else {
      return 'create'
    }
  }
  else {
    return 'create'
  }
}

// 清除
function clear() {
  detail.value = {
    bikeCode: '',
    orders: [],
    soc: 0,
    location: {
      latitude: 0,
      longitude: 0,
    },
    online: false,
    latestTime: '',
    chineseLocation: '',
    usageStatus: 1,
    distance: '',
  }
}

function getOrderInfo(): Promise<any[]> {
  return new Promise((resolve, reject) => {
    const bikecode = detail.value.bikeCode
    getScanBikeInfoBycodeAPI(bikecode)
      .then((res) => {
        resolve(res.orders || [])
      })
      .catch((error) => {
        reject(error)
      })
  })
}

/**
 *接单
 */
function takeOrders() {
  const order = detail.value.orders.find(item => item.orderType === type.value)
  console.log(order)
  if (order) {
    uni.showModal({
      title: '提示',
      content: '确定要接单吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            const res = await acceptWorkOrderAPI(order.orderId)
            const orderInfo = await getOrderInfo()
            detail.value.orders = orderInfo
            uni.showModal({
              title: '提示',
              content: '接单成功，是否去完成工作？',
              confirmText: '去完成',
              cancelText: '取消',
              success: async (res) => {
                if (res.confirm) {
                  complete(type.value, order.orderId, detail.value.bikeCode)
                }
              },
            })
          }
          catch (err) {
            console.error('接单失败', err)
            uni.showToast({
              title: err.message || '接单失败，请稍后重试',
              icon: 'none',
            })
          }
        }
      },

    })
  }
}

/**
 *去完成
 */
function handleComplete() {
  const order = detail.value.orders.find(item => item.orderType === type.value)
  if (!order) {
    uni.showToast({
      title: '未找到工单信息',
      icon: 'none',
    })
  }
  complete(type.value, order.orderId, detail.value.bikeCode)
}

/**
 * 去车辆任务页面
 */
function getCarTaskList(bikeCode: string) {
  uni.navigateTo({
    url: `/pages-sub/common/scanResult?bikeCode=${bikeCode}`,
  })
}

defineExpose({
  init,
  clear,
})
</script>

<template>
  <view class="container">
    <view class="header">
      <view class="number">
        <text :style="{ color: '#666666' }">车辆编号:</text>
        {{ detail.bikeCode || '--' }}
      </view>
    </view>
    <scroll-view
      :scroll-x="true"
      :scroll-with-animation="true"
      class="label_container"
      :style="{ 'white-space': 'nowrap' }"
    >
      <view
        class="label"
        :style="{
          color: detail.online ? '#02B748' : '#999999',
          backgroundColor: detail.online ? '#e4f6eb' : '#e9e9e9',
          borderColor: detail.online ? '#02B748' : '#999999',
        }"
      >
        {{ detail.online ? '在线' : '离线' }}
      </view>
      <view
        class="label"
        :style="{
          color: getBatteryStyle(detail.soc).color,
          backgroundColor: getBatteryStyle(detail.soc).bgColor,
          borderColor: getBatteryStyle(detail.soc).color,
        }"
      >
        {{ getBatteryStyle(detail.soc).name }}
      </view>
      <view
        class="label"
        :style="{
          color: '#1088FF',
          backgroundColor: '#e6f2fe',
          borderColor: '#1088FF',
        }"
      >
        {{ appStore.translateDictValue(detail.usageStatus, 'BikeUsageStatus') }}
      </view>
    </scroll-view>
    <view class="digit_bar">
      <view class="soc">
        <view class="icon">
          <uv-image :src="getImageFullPath(getBatteryStyle(detail.soc).icon)" mode="widthFix" width="100%" />
        </view>
        <view
          :style="{
            color: getBatteryStyle(detail.soc).color,
          }"
          class="num"
        >
          {{ detail.soc || '0' }}%
        </view>
      </view>
      <view class="common">
        <view class="icon">
          <uv-image :src="getImageFullPath('MAP_ICON_SHANGBAOSHIJIAN_IMAGE')" mode="widthFix" width="100%" />
        </view>
        <view class="text">
          {{ detail.latestTime || '--' }}
        </view>
      </view>
      <view class="common" @click="navToMap">
        <view class="icon">
          <uv-image :src="getImageFullPath('MAP_ICON_BIKE_IMAGE')" mode="widthFix" width="100%" />
        </view>
        <view class="text">
          {{ detail.distance || '--' }}
        </view>
        <view class="nav">
          <uv-image :src="getImageFullPath('CUSTOM_MAPNAV_IMAGE')" mode="widthFix" width="100%" />
        </view>
      </view>
    </view>
    <view class="btn_bar">
      <UniCommonBtn
        :custom-style="common_btn_style.info"
        btn-text="寻车铃"
        @click="ringCar"
      >
        <template #prefix>
          <uv-image :src="getImageFullPath('ZHILING_XUNCHELING_IMAGE')" mode="widthFix" width="45rpx" height="45rpx" />
        </template>
      </UniCommonBtn>
      <UniCommonBtn
        :custom-style="common_btn_style.info"
        btn-text="车辆详情"
        @click="navDetail(detail.bikeCode)"
      >
        <template #prefix>
          <uv-image :src="getImageFullPath('MAP_ICON_BIKE_IMAGE')" mode="widthFix" width="45rpx" height="45rpx" />
        </template>
      </UniCommonBtn>

      <!-- 工单状态 -->
      <UniCommonBtn
        v-if="createOrderStatus() === 'complete'"
        :custom-style="{
          ...common_btn_style.primary,
          width: '200rpx',
          height: '80rpx',
        }"
        btn-text="去完成"
        @click="handleComplete"
      />
      <UniCommonBtn
        v-if="createOrderStatus() === 'accept'"
        :custom-style="{
          ...common_btn_style.primary,
          width: '200rpx',
          height: '80rpx',
        }"
        btn-text="接单"
        @click="takeOrders"
      />
      <UniCommonBtn
        v-if="createOrderStatus() === 'create'"
        :custom-style="{
          ...common_btn_style.primary,
          width: '170rpx',
          height: '80rpx',
        }"
        btn-text="生成工单"
        @click="navDetail(detail.bikeCode)"
      />
      <UniCommonBtn
        v-if="createOrderStatus() === 'allBikesTake'"
        :custom-style="{
          ...common_btn_style.primary,
          width: '190rpx',
          height: '80rpx',
        }"
        btn-text="车辆任务"
        @click="getCarTaskList(detail.bikeCode)"
      />
    </view>
  </view>
</template>

<style lang="scss" scoped>
.container {
  width: calc(100% - 40rpx);
  padding: 10rpx 20rpx;

  .header {
    width: 100%;
    display: flex;
    align-items: center;

    .number {
      font-family: PingFangSC;
      font-size: 32rpx;
      color: #333333;
      letter-spacing: 0;
      font-weight: 400;
    }
  }

  .label_container {
    margin-top: 10rpx;
    display: flex;
    align-items: center;

    .label {
      font-family: PingFangSC-Medium;
      font-size: 22rpx;
      letter-spacing: 0;
      font-weight: 500;
      border-radius: 8rpx;
      padding: 5rpx 20rpx;
      border: 1rpx solid #333333;
      display: inline-block;
      margin-right: 10rpx;

      &:last-child {
        margin-right: 0;
      }
    }
  }

  .digit_bar {
    margin-top: 30rpx;
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .soc {
      display: flex;
      align-items: center;
      margin-left: 20rpx;

      .icon {
        width: 46rpx;
        height: 50rpx;
        overflow: hidden;
      }

      .num {
        margin-left: 7rpx;
        font-family: PingFangSC-Regular;
        font-size: 24rpx;
        letter-spacing: 0;
        font-weight: 400;
      }
    }

    .common {
      display: flex;
      align-items: center;

      .icon {
        width: 50rpx;
        height: 50rpx;
        overflow: hidden;
      }

      .nav {
        margin-left: 24rpx;
        width: 40rpx;
        height: 40rpx;
        overflow: hidden;
      }

      .text {
        font-family: PingFangSC-Regular;
        font-size: 24rpx;
        color: #333333;
        letter-spacing: 0;
        margin-left: 10rpx;
        font-weight: 400;
      }
    }
  }

  .btn_bar {
    margin-top: 40rpx;
    width: 100%;
    display: flex;
    gap: 20rpx;
    align-items: center;
  }
}
</style>
