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

definePage({
  style: {
    navigationBarTitleText: '车辆巡检',
    navigationBarBackgroundColor: '#1488f5',
    navigationBarTextStyle: 'white',
  },
})

const appStore = useAppStore()
const paging = ref<any>(null)
const carIds = ref<any>('')
const formRef = ref<any>(null)
const carDetails = ref<any>({
  bikeCode: '',
})
const customStyle = computed(() => {
  return {
    height: '60rpx',
    fontSize: '26rpx',
    padding: '20rpx 15rpx',
  }
})
const radiolist = ref([
  {
    name: '苹果',
  },
  {
    name: '香蕉',
  },
])

/**
 * 表单数据
 */
const isSubmit = ref(false)
const limit = ref(4)
const fileList_before = ref([])
const fileList_after = ref([])
const formData = ref({
  bikeCode: '',
  beforeInspectionFileUrls: [],
  afterInspectionFileUrls: [],
  isFault: false,
  remarks: '',
})
const rules = {
  isFault: {
    type: 'boolean',
    required: true,
    message: '请选择',
    trigger: 'change',
  },
}

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

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

// 地图找车
function handleMapClick() {
  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))}`,
  })
}

// 上传图片
async function afterRead(event: any, type: string) {
  const lists = [].concat(event.file)
  let fileListLen = type === 'before' ? fileList_before.value.length : fileList_after.value.length
  const token = CacheManager.get('token')

  lists.forEach((item) => {
    if (type === 'before') {
      fileList_before.value.push({
        ...item,
        status: 'uploading',
        message: '上传中',
      })
    }
    else {
      fileList_after.value.push({
        ...item,
        status: 'uploading',
        message: '上传中',
      })
    }
  })

  for (let i = 0; i < lists.length; i++) {
    const item = type === 'before' ? fileList_before.value[fileListLen] : fileList_after.value[fileListLen]
    try {
      const result: any = await uploadImagesStrict([lists[i].url], faultUrl, {
        name: 'file',
        header: {
          'Authorization': token,
          'Content-Type': 'multipart/form-data',
        },
      })
      console.log(result)

      // 列表参数添加
      if (type === 'before') {
        formData.value.beforeInspectionFileUrls.push(result[0])
      }
      else {
        formData.value.afterInspectionFileUrls.push(result[0])
      }

      if (type === 'before') {
        fileList_before.value.splice(fileListLen, 1, Object.assign(item, {
          status: 'success',
          message: '',
          url: result[0],
        }))
      }
      else {
        fileList_after.value.splice(fileListLen, 1, Object.assign(item, {
          status: 'success',
          message: '',
          url: result[0],
        }))
      }
      fileListLen++
    }
    catch (err) {
      console.log('错误')

      if (type === 'before') {
        fileList_before.value.splice(fileListLen, 1, Object.assign(item, {
          status: 'failed',
          message: '',
          url: '',
        }))
      }
      else {
        fileList_after.value.splice(fileListLen, 1, Object.assign(item, {
          status: 'failed',
          message: '',
          url: '',
        }))
      }
    }
  }
}

// 删除图片
function deletePic(e: any, type: string) {
  if (type === 'before') {
    fileList_before.value.splice(e.index, 1)
    formData.value.beforeInspectionFileUrls.splice(e.index, 1)
  }
  else {
    fileList_after.value.splice(e.index, 1)
    formData.value.afterInspectionFileUrls.splice(e.index, 1)
  }
}

// 表单重置
function resetForm() {
  formData.value = {
    bikeCode: '',
    beforeInspectionFileUrls: [],
    afterInspectionFileUrls: [],
    isFault: false,
    remarks: '',
  }
  fileList_before.value = []
  fileList_after.value = []
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 提交表单
async function handleComplete() {
  if (!carIds.value) {
    return uni.showToast({
      title: '请输入车牌号',
      icon: 'none',
    })
  }

  isSubmit.value = true
  try {
    const status = await formRef.value.validate()
    if (status) {
      const res: any = await completeInspectionWorkAPI({
        ...formData.value,
        bikeCode: carIds.value,
      })
      uni.showToast({
        title: '提交成功',
        icon: 'none',
      })
      resetForm()
    }
  }
  catch (e: any) {
    console.error('提交失败')
  }
  finally {
    isSubmit.value = false
  }
}

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

<template>
  <z-paging
    ref="paging"
    bg-color="#f3f3f3"
  >
    <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="carIds" 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' : carIds ? 'red' : '',
              }"
            >
              {{ carDetails.online ? '在线' : carIds ? '离线' : '--' }}
            </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">{{ carDetails.voltage || '--' }}V</text>
          </view>
        </view>
        <!-- 第3行 -->
        <view class="card_row">
          <view class="row_item">
            <text class="label">电门状态</text>
            <text class="value">{{ carDetails.accOn || '--' }}</text>
          </view>
          <view class="row_item">
            <text class="label">轮锁状态</text>
            <text class="value">{{ carDetails.wheelLocked || '--' }}</text>
          </view>
        </view>
        <!-- 第4行 -->
        <view class="card_row">
          <view class="row_item">
            <text class="label">电池仓状态</text>
            <text class="value">{{ carDetails.seatLocked || '--' }}</text>
          </view>
          <view class="row_item">
            <text class="label">网络信号</text>
            <text class="value">{{ carDetails.gsm || '--' }}</text>
          </view>
        </view>
        <!-- 第5行 -->
        <view class="card_row">
          <view class="row_item">
            <text class="label">运动状态</text>
            <text class="value">{{ carDetails.isMoving || '--' }}</text>
          </view>
          <view class="row_item">
            <text class="label">车辆速度</text>
            <text class="value">{{ carDetails.speed || '--' }}</text>
          </view>
        </view>
        <!-- 第6行 -->
        <view class="card_row">
          <view class="row_item">
            <text class="label">头盔锁状态</text>
            <text class="value">{{ carDetails.isHelmetLocked || '--' }}</text>
          </view>
          <view class="row_item">
            <text class="label">头盔是否在位</text>
            <text class="value">{{ carDetails.helmetExit || '--' }}</text>
          </view>
        </view>
        <!-- 车辆编号 -->
        <view class="card_row_long_3">
          <view class="key">
            最新定位
          </view>
          <view class="value">
            {{ carDetails.chineseLocation || '--' }}
          </view>
          <view class="icon">
            <uv-button
              type="primary"
              :plain="true"
              text="地图找车"
              icon-color="#1488f5"
              icon="map"
              shape="circle"
              :custom-style="customStyle"
              @click="handleMapClick"
            />
          </view>
        </view>
      </view>
      <!-- 操作 -->
      <view class="card_box">
        <instructTools :bike-code="carIds" />
      </view>

      <!-- 表单填写 -->
      <view class="card_box">
        <uv-form
          ref="formRef"
          label-position="top"
          :model="formData"
          :rules="rules"
          :label-width="300"
          :label-style="{
            fontSize: '28rpx',
            color: '#969696',
          }"
        >
          <!-- TUDU:没有确定 -->
          <!-- <uv-form-item label="巡检类型" prop="">
            <uv-radio-group v-model="formData.radiovalue">
              <uv-radio
                v-for="(item, index) in radiolist"
                :key="index"
                :custom-style="{ margin: '8px' }"
                :label="item.name"
                :name="item.name"
              />
            </uv-radio-group>
          </uv-form-item> -->
          <uv-form-item label="是否直接上报故障" prop="isFault" required>
            <uv-radio-group v-model="formData.isFault">
              <uv-radio
                :custom-style="{ margin: '8px' }"
                label="否"
                :name="false"
              />
              <uv-radio
                :custom-style="{ margin: '8px' }"
                label="是"
                :name="true"
              />
            </uv-radio-group>
          </uv-form-item>
          <uv-form-item label="巡检前照片(最多4张)" prop="beforeInspectionFileUrls">
            <uv-upload
              :file-list="fileList_before"
              name="before"
              multiple
              :max-count="limit"
              :preview-full-image="true"
              @after-read="(e:any) => afterRead(e, 'before')"
              @delete="(e:any) => deletePic(e, 'before')"
            />
          </uv-form-item>
          <uv-form-item label="巡检后照片(最多4张)" prop="afterInspectionFileUrls">
            <uv-upload
              :file-list="fileList_after"
              name="after"
              multiple
              :max-count="limit"
              :preview-full-image="true"
              @after-read="(e:any) => afterRead(e, 'after')"
              @delete="(e:any) => deletePic(e, 'after')"
            />
          </uv-form-item>
          <uv-form-item label="巡检备注" prop="remarks">
            <uv-textarea v-model="formData.remarks" placeholder="请输入备注内容" />
          </uv-form-item>
        </uv-form>
        <!-- 提示 -->
        <view class="tips_bar">
          <view class="title">
            温馨提示
          </view>
          <view class="text">
            1、请根据要求提交照片，将以此作为审核参考凭证。
          </view>
        </view>
      </view>
    </view>

    <template #bottom>
      <view class="bottom-button-zaping">
        <uv-button
          type="primary"
          :loading="isSubmit"
          text="确认提交"
          loading-text="提交中..."
          @click="handleComplete"
        />
      </view>
    </template>
  </z-paging>
</template>

<style lang="scss" scoped>
.tips_bar {
  color: #b3b3b3;

  .title {
    font-size: 32rpx;
    margin: 15rpx 0;
  }

  .text {
    font-size: 28rpx;
    margin: 10rpx 0;
  }
}
</style>
