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

definePage({
  style: {
    navigationBarTitleText: '调度',
    navigationBarBackgroundColor: '#1488f5',
    navigationBarTextStyle: 'white',
  },
})
const popupRef = ref(null)
const fileList = ref([])
const btnConfig = reactive({
  loading: false,
  loadingText: '提交中...',
})

const selctSiteName = ref('')
const orderDetail = ref<any>({
  location: {
    latitude: 0,
    longitude: 0,
  },
  soc: 0,
})

const formData = reactive({
  bikeCode: '',
  value: '',
  fileUrls: [],
})

function handleSiteClick() {
  console.log(123)
}

// 获取站点信息
function selecSite() {
  popupRef.value.open()
}

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

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

function handleComplete() {

}

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.fileUrls.push(result[0])
      fileList.value.splice(fileListLen, 1, Object.assign(item, {
        status: 'success',
        message: '',
        url: result[0].fileUrl,
      }))
      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.fileUrls.splice(e.index, 1)
}

/**
 * 弹窗关闭回调
 */

function popupBack() {
  popupRef.value.close()
}

function popupChage(val: any) {
  const { siteName } = val
  popupBack()
  console.log(val, 'popupChage')
  selctSiteName.value = siteName
}

onMounted(() => {

})
</script>

<template>
  <view>
    <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="formData.bikeCode" border="none" placeholder="请输入">
                <template #suffix>
                  <uv-icon name="scan" color="#2979ff" size="28" @click="scan" />
                </template>
              </uv-input>
            </view>
          </view>
          <!-- 电池电量 -->
          <view class="card_row">
            <view class="card_row_key">
              电池电量
            </view>
            <view class="card_row_value">
              {{ orderDetail.soc || 0 }}%
            </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">
                {{ orderDetail.location.longitude || '-' }},{{ orderDetail.location.latitude || '-' }}
              </view>
            </view>
            <view class="card_row_link">
              <uv-icon name="arrow-right" />
            </view>
          </view>
        </view>

        <!-- 工具栏 -->
        <view class="card_box u-m-t-20">
          <instructTools />
        </view>

        <!-- 站点选择 -->
        <view class="card_box u-m-t-20">
          <view class="select_bar" @click="selecSite">
            <view
              :style="{
                color: selctSiteName ? '#333' : '#a3a3a3',
              }"
              class="text"
            >
              {{ selctSiteName ? selctSiteName : '请选择站点' }}
            </view>
            <uv-icon name="arrow-down-fill" color="#010101" size="12" />
          </view>
        </view>

        <!-- 调度原因 -->
        <view class="row_item">
          <view class="u-m-b-15">
            调度原因
          </view>
          <uv-textarea v-model="formData.value" placeholder="请输入调度原因" />
        </view>

        <!-- 调度图片 -->
        <view class="row_item">
          <view class="u-m-b-15">
            上传调度照片
          </view>
          <uv-upload
            :file-list="fileList"
            name="1"
            multiple
            upload-icon-color="#868686"
            :max-count="5"
            :preview-full-image="true"
            @after-read="afterRead"
            @delete="deletePic"
          />
        </view>
      </view>

      <template #bottom>
        <view class="bottom-button-zaping">
          <uv-button
            type="primary"
            text="完成调度"
            :loading="btnConfig.loading"
            :loading-text="btnConfig.loadingText"
            @click="handleComplete"
          />
        </view>
      </template>
    </z-paging>

    <!-- 弹窗 -->
    <uv-popup ref="popupRef" mode="right">
      <view class="popup_box">
        <siteSelectList
          :value="selctSiteName"
          @back="popupBack"
          @change="popupChage"
        />
      </view>
    </uv-popup>
  </view>
</template>

<style lang="scss" scoped>
.select_bar {
  width: calc(100% - 40rpx);
  padding: 20rpx;
  border: 2rpx solid #ededed;
  border-radius: 10rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .text {
    width: 90%;
    font-size: 28rpx;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
  }
}

.row_item {
  margin: 20px 0;
}

.popup_box {
  width: 100vw;
}

:deep(.uv-upload .uv-upload__wrap .uv-upload__button) {
  background-color: #dedede;
}
</style>
