<script lang="ts" setup>
import { completeMaintainWorkAPI, getEbikeDetailForWorkAPI } from '@/api/operator'
import { faultUrl, uploadImagesStrict } from '@/api/upload'
import instructTools from '@/components/instructTools/instructTools.vue'
import CacheManager from '@/utils/CacheManager'
import { scanCode } from '@/utils/tools'

definePage({
  style: {
    navigationBarTitleText: '故障维修',
    navigationBarBackgroundColor: '#1488f5',
    navigationBarTextStyle: 'white',
  },
})

const carIds = ref<any>('')
const paging = ref<any>(null)
const popupRef = ref<any>(null)
const fileList = ref<any>([])
const carDetails = ref<any>({
  bikeCode: '',
})
const btnConfig = reactive({
  btnLoading: false,
  btnLoadingText: '提交中...',
})
const formData = ref({
  type: 1,
  fileUrls: [],
  remarks: '',
})

// 获取车辆详情
async function getEbikeDetail() {
  uni.showLoading({
    title: '查询中...',
  })
  try {
    const res = await getEbikeDetailForWorkAPI(carIds.value, '4')
    if (res) {
      carDetails.value = res
    }
  }
  catch (e) {
    console.error('查询车辆详情失败')
  }
  finally {
    uni.hideLoading()
  }
}

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 (!carIds.value) {
    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) => {
      carIds.value = 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: carIds.value,
      type: formData.value.type,
      fileUrls: formData.value.fileUrls,
      remarks: formData.value.remarks,
    })
    uni.showToast({
      title: '提交成功',
      icon: 'none',
    })
    setTimeout(() => {
      uni.navigateBack()
    }, 1000)
  }
  catch (e) {
    console.log(e)
  }
  finally {
    btnConfig.btnLoading = false
  }
}

onLoad((query) => {
  const { bikeCode } = query
  if (bikeCode) {
    carIds.value = bikeCode
    getEbikeDetail()
  }
})
</script>

<template>
  <z-paging
    ref="paging"
    bg-color="#f3f3f3"
  >
    <view class="y_card_wrapper">
      <view class="card_box">
        <!-- 车辆编号 -->
        <view class="card_row">
          <view class="card_row_key">
            车辆编号
          </view>
          <view class="card_row_value">
            <uv-input v-model="carIds" placeholder="请输入车辆编号" border="none">
              <template #suffix>
                <uv-icon name="scan" color="#1488f5" size="22" @click="handleScan" />
              </template>
            </uv-input>
          </view>
        </view>
        <!-- 创建时间 -->
        <view class="card_row">
          <view class="card_row_key">
            创建时间
          </view>
          <view class="card_row_value">
            {{ carDetails.createdAt || '-' }}
          </view>
        </view>
        <!-- 电池电量 -->
        <view class="card_row">
          <view class="card_row_key">
            电池电量
          </view>
          <view class="card_row_value">
            {{ carDetails.soc || '-' }}%
          </view>
        </view>
        <!-- 车辆位置 -->
        <view class="card_row">
          <view class="card_row_key">
            车辆位置
          </view>
          <view class="card_row_value_two" @click="findCar">
            <view>查看地图</view>
            <view class="card_row_small_text">
              {{ carDetails?.location?.longitude || '-' }},{{ carDetails?.location?.latitude || '-' }}
            </view>
          </view>
          <view class="card_row_link">
            <uv-icon name="arrow-right" />
          </view>
        </view>
        <!-- 信号强度 -->
        <view class="card_row">
          <view class="card_row_key">
            信号强度
          </view>
          <view class="card_row_value">
            {{ carDetails?.gsm || '-' }}
          </view>
        </view>
      </view>

      <!-- 指令工具栏 -->
      <view class="card_box" style="margin-top: 30rpx;">
        <instructTools :bike-code="carDetails.bikeCode" />
      </view>
    </view>
    <template #bottom>
      <view class="bottom-button-zaping">
        <uv-button
          type="primary"
          text="处理完成"
          @click="handleComplete"
        />
      </view>
    </template>

    <!-- 弹窗 -->
    <uv-popup ref="popupRef" round="20" :close-on-click-overlay="false">
      <view class="popup-content">
        <view class="popup-title">
          {{ formData.type === 1 ? '故障误报' : '处理故障' }}
        </view>
        <!-- 选择栏 -->
        <view class="popup-select-bar">
          <view
            class="select-item"
            :class="[formData.type === 1 ? `select-item-active` : ``]"
            @click="handleSelect(1)"
          >
            故障误报
          </view>
          <view
            class="select-item"
            :class="[formData.type === 2 ? `select-item-active` : ``]"
            style="margin-left: 30rpx;"
            @click="handleSelect(2)"
          >
            处理故障
          </view>
        </view>
        <!-- 描述 -->
        <view class="popup-select-row">
          <view class="row-title">
            填写处理结果
          </view>
          <view class="row-content">
            <uv-textarea v-model="formData.remarks" placeholder="请输入处理结果" />
          </view>
        </view>
        <!-- 照片上传 -->
        <view class="popup-select-row">
          <view class="row-title">
            故障照片（最多5张）
          </view>
          <view class="row-content">
            <uv-upload
              :file-list="fileList"
              name="1"
              multiple
              :max-count="5"
              @after-read="afterRead"
              @delete="deletePic"
            />
          </view>
        </view>
        <view class="popup-select-btn">
          <uv-button type="info" text="取消" style="width: 45%;" @click="handlePopupClose" />
          <uv-button
            type="primary"
            text="提交"
            :loading="btnConfig.btnLoading"
            :loading-text="btnConfig.btnLoadingText"
            style="width: 45%;"
            @click="submit"
          />
        </view>
      </view>
    </uv-popup>
  </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;
  }
}
</style>
