<script lang="ts" setup>
import { completeMaintainWorkAPI, getEbikeDetailForWorkAPI } from '@/api/operator'
import { faultUrl, uploadImagesStrict } from '@/api/upload'
import { queryWorkOrderDetailAPI } from '@/api/work'
import instructTools from '@/components/instructTools/instructTools.vue'
import { useAppStore } from '@/store'
import { getImageFullPath } from '@/utils'
import CacheManager from '@/utils/CacheManager'
import { eventBus, EVENTS } from '@/utils/events'
import { systemInfo } from '@/utils/systemInfo'
import { scanCode, translateErrorCode } from '@/utils/tools'

definePage({
  style: {
    navigationStyle: 'custom',
  },
})
const labelStyle = {
  padding: '0 5px 0 0',
  color: '#333333',
  fontSize: '30rpx',
  fontWeight: '400',
}
const appStore = useAppStore()
const paging = ref<any>(null)
const popupRef = ref<any>(null)
const fileList = ref<any>([])
const orderQurey = ref({
  orderId: '',
  bikeCode: '',
})
const carDetails = ref<any>({
  bikeCode: '',
})
const workOrderDetail = ref<any>({
  handleState: -1,
  ecuSn: '',
  bikeCode: '',
  createdAt: '',
  soc: 0,
  location: {
    latitude: 0,
    longitude: 0,
  },
  parts: [], // 故障类型
  orderType: -1,
})
const btnConfig = reactive({
  btnLoading: false,
  btnLoadingText: '提交中...',
})
const formData = ref({
  type: 1,
  fileUrls: [],
  remarks: '',
})
const rules = {

}

// 返回
function handleBack() {
  uni.navigateBack()
}

// 获取车辆详情
async function getEbikeDetail() {
  uni.showLoading({
    title: '查询中...',
  })
  try {
    const [bikeRes, orderRes] = await Promise.all([
      getEbikeDetailForWorkAPI(orderQurey.value.bikeCode),
      queryWorkOrderDetailAPI(orderQurey.value.orderId),
    ])
    if (bikeRes) {
      carDetails.value = bikeRes
    }
    if (orderRes) {
      workOrderDetail.value = orderRes
    }
  }
  catch (e) {
    console.error('查询车辆详情失败')
  }
  finally {
    uni.hideLoading()
  }
}
const typeList = ref([
  { name: '故障误报', value: 1 },
  { name: '处理故障', value: 2 },
])

function findCar() {
  const { latitude, longitude } = carDetails.value.location
  const params = {
    elng: longitude,
    elat: latitude,
  }
  uni.navigateTo({
    url: `/pages-sub/map/findCar/findCar?params=${encodeURIComponent(JSON.stringify(params))}`,
  })
}

function handleComplete() {
  if (!orderQurey.value.bikeCode) {
    uni.showToast({
      title: '请选择车辆',
      icon: 'none',
    })
    return
  }
  popupRef.value.open('bottom')
}

async function afterRead(event: any) {
  const lists = [].concat(event.file)
  let fileListLen = fileList.value.length
  const token = CacheManager.get('token')

  lists.forEach((item) => {
    fileList.value.push({
      ...item,
      status: 'uploading',
      message: '上传中',
    })
  })

  for (let i = 0; i < lists.length; i++) {
    const item = fileList.value[fileListLen]
    try {
      const result: any = await uploadImagesStrict([lists[i].url], faultUrl, {
        name: 'file',
        header: {
          'Authorization': token,
          'Content-Type': 'multipart/form-data',
        },
      })
      formData.value.fileUrls.push(result[0])

      fileList.value.splice(fileListLen, 1, Object.assign(item, {
        status: 'success',
        message: '',
        url: result[0],
      }))
      fileListLen++
    }
    catch (err) {
      fileList.value.splice(fileListLen, 1, Object.assign(item, {
        status: 'failed',
        message: '',
        url: '',
      }))
    }
  }
}

function deletePic(e: any) {
  fileList.value.splice(e.index, 1)
  formData.value.fileUrls.splice(e.index, 1)
}

function handleScan() {
  scanCode({
    success: (res: any) => {
      orderQurey.value.bikeCode = res.code
      getEbikeDetail()
    },
    fail: () => {
      uni.showToast({
        title: '扫码失败',
        icon: 'none',
      })
    },
  })
}

function handleSelect(type: any) {
  formData.value.type = type
}

function handlePopupClose() {
  popupRef.value.close()
  formData.value = {
    type: 1,
    fileUrls: [],
    remarks: '',
  }
  fileList.value = []
}

async function submit() {
  try {
    const res: any = await completeMaintainWorkAPI({
      bikeCode: orderQurey.value.bikeCode,
      type: formData.value.type,
      fileUrls: formData.value.fileUrls,
      remarks: formData.value.remarks,
    })
    uni.showToast({
      title: '提交成功',
      icon: 'none',
    })
    eventBus.emit(EVENTS.ORDERCOMPLETE, 4)
    setTimeout(() => {
      uni.navigateBack()
    }, 1000)
  }
  catch (e) {
    console.log(e)
  }
  finally {
    btnConfig.btnLoading = false
  }
}

onLoad((query) => {
  const { bikeCode, orderId } = query
  orderQurey.value.orderId = orderId || ''
  orderQurey.value.bikeCode = bikeCode || ''
  if (bikeCode) {
    getEbikeDetail()
  }
})
</script>

<template>
  <z-paging
    ref="paging"
    bg-color="#f3f3f3"
  >
    <template #top>
      <view class="custom_navbar" :style="{ height: `${systemInfo.statusBarHeight + 44}px` }">
        <view class="back_bar">
          <uv-icon name="arrow-left" color="#222222" size="24" @click="handleBack" />
          <text class="text">维修工单</text>
        </view>
      </view>
    </template>
    <view class="y_card2_wrapper">
      <!-- 详情 -->
      <view class="card_box">
        <!-- 车辆编号 -->
        <view class="card_row_long_3">
          <view class="key">
            车辆编号
          </view>
          <view class="value">
            <uv-input v-model="orderQurey.bikeCode" placeholder="请输入或扫码" border="none" />
          </view>
          <view class="icon">
            <!-- <uv-icon name="scan" color="#1488f5" size="24" @click="handleScan" /> -->
          </view>
        </view>
        <!-- 第1行 -->
        <view class="card_row">
          <view class="row_item">
            <text class="label">在线状态</text>
            <text
              class="value"
              :style="{
                color: carDetails.online ? '#85c262' : orderQurey.bikeCode ? 'red' : '',
              }"
            >
              {{ carDetails.online ? '在线' : orderQurey.bikeCode ? '离线' : '--' }}
            </text>
          </view>
          <view class="row_item">
            <text class="label">实时电量</text>
            <text class="value">{{ carDetails.soc || '--' }}%</text>
          </view>
        </view>
        <!-- 第2行 -->
        <view class="card_row">
          <view class="row_item">
            <text class="label">车辆状态</text>
            <text class="value">{{ appStore.translateDictValue(carDetails.usageStatus, 'BikeUsageStatus') || '--' }}</text>
          </view>
          <view class="row_item">
            <text class="label">上报来源</text>
            <text class="value">{{ '--' }}</text>
          </view>
        </view>
        <!-- 最新定位 -->
        <view class="card_row_long_3">
          <view class="key">
            最新定位
          </view>
          <view class="value">
            {{ carDetails.chineseLocation || '--' }}
          </view>
          <view class="icon">
            <uv-image :src="getImageFullPath('CUSTOM_MAPNAV_IMAGE')" mode="widthFix" width="100%" @click="findCar" />
          </view>
        </view>
        <!-- 创建时间 -->
        <view class="card_row_long_3">
          <view class="key">
            创建时间
          </view>
          <view class="value">
            {{ workOrderDetail.createdAt || '--' }}
          </view>
          <view class="icon" />
        </view>
        <!-- 维修部件 -->
        <view class="card_row_long_3">
          <view class="key">
            损坏部件
          </view>
          <view class="value">
            {{ translateErrorCode(workOrderDetail.parts, 'inventory_type') || '--' }}
          </view>
          <view class="icon" />
        </view>
        <!-- 备注 -->
        <view class="card_row_long_3">
          <view class="key">
            备注
          </view>
          <view class="value">
            {{ workOrderDetail.remark || '--' }}
          </view>
          <view class="icon" />
        </view>
      </view>
      <!-- 操作 -->
      <view class="card_box">
        <instructTools :bike-code="orderQurey.bikeCode" />
      </view>
      <!-- 表单填写 -->
      <view class="card_box">
        <uv-form
          ref="formRef"
          label-position="top"
          :model="formData"
          :rules="rules"
          :label-width="200"
          :label-style="labelStyle"
        >
          <uv-radio-group v-model="formData.type" icon-placement="right">
            <uv-radio
              v-for="(item, index) in typeList"
              :key="index"
              :custom-style="{ margin: '8px 8px 8px 0' }"
              :label="item.name"
              :name="item.value"
            />
          </uv-radio-group>
          <uv-form-item label="填写处理结果" prop="remarks">
            <uv-textarea v-model="formData.remarks" placeholder="请输入处理结果" />
          </uv-form-item>
          <uv-form-item label="故障照片（最多5张）" prop="beforeInspectionFileUrls">
            <uv-upload
              :file-list="fileList"
              name="1"
              multiple
              :max-count="5"
              @after-read="afterRead"
              @delete="deletePic"
            />
          </uv-form-item>
        </uv-form>
      </view>
    </view>

    <template #bottom>
      <view class="bottom-button-zaping">
        <uv-button
          type="primary"
          text="完成维修"
          :custom-style="{
            backgroundImage: `linear-gradient(135deg, #1089FF 0%, #0F5BFF 100%)`,
            borderRadius: '28rpx',
            height: '100rpx',
          }"
          :custom-text-style="{
            fontSize: '32rpx',
            marginLeft: '8rpx',
          }"
          :loading="btnConfig.btnLoading"
          :loading-text="btnConfig.btnLoadingText"
          @click="submit"
        />
      </view>
    </template>
  </z-paging>
</template>

<style lang="scss" scoped>
.popup-content {
  padding: 20rpx;
  width: calc(100% - 40rpx);
  height: 70vh;
  position: relative;

  .popup-title {
    display: flex;
    justify-content: center;
    font-size: 34rpx;
    font-weight: 600;
  }

  .popup-select-bar {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 30rpx;

    .select-item {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 15rpx 50rpx;
      border: 2rpx solid #e9e9e9;
      border-radius: 10rpx;
      font-size: 28rpx;

      &-active {
        background-color: #f4f8fd !important;
        color: #3d96da !important;
        border-color: #3d96da !important;
      }
    }
  }

  .popup-select-row {
    margin-top: 40rpx;
    .row-title {
      font-size: 28rpx;
      color: #a7a7a7;
    }

    .row-content {
      margin-top: 20rpx;
    }
  }

  .popup-select-btn {
    position: absolute;
    bottom: 10px;
    width: calc(100% - 20px);
    display: flex;
    justify-content: space-around;
  }
}
.custom_navbar {
  width: 100%;
  position: relative;
  background-color: white;

  .back_bar {
    display: flex;
    align-items: center;
    position: absolute;
    bottom: 25rpx;
    left: 30rpx;

    .text {
      font-family: SourceHanSansCN-Medium;
      font-size: 34rpx;
      color: #222222;
      letter-spacing: 0;
      font-weight: 500;
    }
  }
}
::v-deep .uv-radio__label-wrap {
  padding-right: 9px !important;
}
</style>
