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

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

const btnConfig = reactive({
  btnLoading: false,
  btnLoadingText: '提交中...',
})
const partsList = ref<any>([])
const form = ref<any>(null)
const fileList = ref([])
const formData = ref({
  bikeCode: '',
  parts: [],
  fileUrls: [],
  remarks: '',
})

const currentLocation = reactive ({
  longitude: '',
  latitude: '',
})

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

function mapChange(e: any) {
  const { longitude, latitude } = e
  currentLocation.longitude = longitude
  currentLocation.latitude = latitude
}

function handlePartsClick(item: any, index: number) {
  uni.vibrateShort()
  partsList.value[index].selected = !item.selected
}

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

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])
      console.log(result)

      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: '',
      }))
    }
  }
}

async function submit() {
  const parts = partsList.value.filter(item => item.selected)
  if (!formData.value.bikeCode) {
    uni.showToast({
      title: '请填写车牌号',
      icon: 'none',
    })
    return
  }
  if (parts.length <= 0) {
    uni.showToast({
      title: '请选择故障部件',
      icon: 'none',
    })
    return
  }
  formData.value.parts = parts.map(item => item.value)
  console.log(formData.value)
  btnConfig.btnLoading = true
  try {
    const res: any = await createMaintainOrderAPI(formData.value)
    console.log(res)
    uni.showToast({
      title: '提交成功',
      icon: 'none',
    })
    setTimeout(() => {
      uni.navigateBack()
    }, 1000)
  }
  catch (e) {
    console.error(e)
  }
  finally {
    btnConfig.btnLoading = false
  }
}

onLoad(() => {
  const dicList: any = CacheManager.get('dictData')
  if (Array.isArray(dicList) && dicList.length > 0) {
    const list = dicList.find((item: any) => item.dicCode === 'inventory_type').values
    partsList.value = list.map((item: any) => ({
      icon: item.dicIcon || '',
      name: item.dicValueName,
      value: Number(item.dicValue),
      selected: false,
    }))
  }
})
</script>

<template>
  <view>
    <z-paging
      ref="paging"
    >
      <view class="content_box">
        <uv-form
          ref="form"
          label-position="left"
          label-width="80"
          :label-style="{
            fontSize: '28rpx',
          }"
        >
          <uv-form-item label="车辆编号" prop="userInfo.name" border-bottom>
            <uv-input v-model="formData.bikeCode" border="none" placeholder="请输入">
              <template #suffix>
                <uv-icon name="scan" color="#2979ff" size="28" @click="scan" />
              </template>
            </uv-input>
          </uv-form-item>
          <uv-form-item label="当前坐标" prop="userInfo.name" border-bottom>
            <view style="width: 90%;">
              {{ currentLocation.longitude || '-' }}, {{ currentLocation.latitude || '-' }}
            </view>
          </uv-form-item>
        </uv-form>

        <!-- 地图 -->
        <view>
          <mapOrientation @change="mapChange" />
        </view>
      </view>
    </z-paging>
  </view>

  <!-- 弹窗 -->
  <you-touchbox
    :custom-style="{
      backgroundColor: '#eff3f6',
      borderTopLeftRadius: '20px',
      borderTopRightRadius: '20px',
      boxShadow: '0 2rpx 8rpx rgba(0, 0, 0, 0.4)',

    }"
    min-top="200"
    max-top="150"
  >
    <scroll-view
      scroll-y
      :scroll-anchoring="false"
      class="order_scroll"
    >
      <view class="order_container">
        <view class="title">
          请选择车辆<text style="color: #1488f5;">损坏部位</text>
        </view>
        <view class="list_grid">
          <view
            v-for="(item, index) in partsList"
            :key="index"
            class="fault_item"
            @click="handlePartsClick(item, index)"
          >
            <view class="icon">
              <uv-icon
                size="30"
                :name="item.icon"
                :color="item.selected ? '#1488f5' : ''"
                custom-prefix="custom-icon"
              />
            </view>
            <view class="text" :style="{ color: item.selected ? '#1488f5' : '' }">
              {{ item.name }}
            </view>
          </view>
        </view>

        <view class="describe">
          <uv-textarea v-model="formData.remarks" placeholder="其他想说的" />
        </view>

        <!-- 上传图片 -->
        <view class="upload-img">
          <view style="margin-bottom: 20rpx;">
            上传图片（最多五张）
          </view>
          <uv-upload
            :file-list="fileList"
            name="1"
            multiple
            :max-count="5"
            :preview-full-image="true"
            @after-read="afterRead"
            @delete="deletePic"
          />
        </view>
      </view>
    </scroll-view>
    <view class="btn_box">
      <uv-button
        type="primary"
        text="确定提交"
        :loading="btnConfig.btnLoading"
        :loading-text="btnConfig.btnLoadingText"
        @click="submit"
      />
    </view>
  </you-touchbox>
</template>

<style lang="scss" scoped>
.content_box {
  padding: 25rpx;
  width: calc(100% - 50rpx);
}

.order_scroll {
  padding: 20rpx;
  background-color: white;
  width: calc(100% - 40rpx);

  .order_container {
    height: 1000px;

    .title {
      font-size: 32rpx;
      font-weight: bold;
      text-align: center;
      margin-bottom: 30rpx;
    }

    .list_grid {
      margin-top: 20rpx;
      padding-top: 5rpx;
      display: grid;
      overflow-y: auto;
      grid-template-columns: repeat(4, 1fr); /* 固定5列 */
      grid-template-rows: auto auto; /* 两行 */
      gap: 16px; /* 项目之间的间距 */
    }

    .fault_item {
      display: flex;
      flex-direction: column;
      align-items: center;
      background-color: #fff;
      border-radius: 12rpx;

      .icon {
        width: 60px;
        height: 60px;
        border-radius: 4px;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 0 4px rgba(0, 0, 0, 0.1);
      }

      .text {
        text-align: center;
        font-size: 12px;
        text-shadow: 0 0 4px rgba(0, 0, 0, 0.1);
        margin-top: 5px;
      }
    }
    .describe {
      margin-top: 20rpx;
    }

    .upload-img {
      font-size: 28rpx;
      margin-top: 50rpx;
    }
  }
}

.btn_box {
  position: fixed;
  bottom: 0;
  padding: 10px 20rpx 20px 20rpx;
  width: calc(100% - 40rpx);
  background-color: white;
  position: 99;
}
</style>
