<script lang="ts" setup>
import { onlineUpdateAPI } from '@/api/onlineUpdate'
import { remoteUpgradeUrl, uploadImagesStrict } from '@/api/upload'
import { useAppStore } from '@/store'
import CacheManager from '@/utils/CacheManager'

definePage({
  style: {
    navigationBarTitleText: '在线升级',
    navigationBarBackgroundColor: '#1488f5',
    navigationBarTextStyle: 'white',
  },
})

const appStore = useAppStore()
const fileList = ref<any[]>([])
const form = ref<any>(null)
const formData = reactive<any>({
  fullUpgrade: false,
  ecuSn: '',
  bikeCode: '',
  ecuBrand: '',
  type: '',
  url: '',
})
const typeList = ref([])
const ecuBrandList = ref([])
const rules = {
  fullUpgrade: [
    { required: true, message: '请选择是否全部升级', trigger: 'change', type: 'boolean' },
  ],
  ecuBrand: [
    { required: true, message: '请选择中控品牌', trigger: 'change' },
  ],
  type: [
    { required: true, message: '请选择升级类型', trigger: 'change' },
  ],
  url: [
    { required: true, message: '请上传文件地址', trigger: 'change' },
  ],
}
const btnConfig = reactive({
  loading: false,
  loadingText: '提交中...',
})

async function afterRead(event: any) {
  const { file } = event
  const token = CacheManager.get('token')
  const fileListLen = fileList.value.length

  fileList.value.push({
    ...file,
    status: 'uploading',
    message: '上传中',
  })
  console.log(file)
  try {
    const result: any = await uploadImagesStrict([file.url], remoteUpgradeUrl, {
      name: 'file',
      header: {
        'Authorization': token,
        'Content-Type': 'multipart/form-data',
      },
    })
    fileList.value.splice(fileListLen, 1, Object.assign(file, {
      status: 'success',
      message: '',
      url: result[0],
    }))
    formData.url = result[0]
    console.log(result)
    console.log(formData)
  }
  catch (e) {
    console.error(e)
    fileList.value.splice(fileListLen, 1, Object.assign(file, {
      status: 'failed',
      message: '',
      url: '',
    }))
  }
}

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

function resetForm() {
  formData.fullUpgrade = false
  formData.ecuSn = ''
  formData.bikeCode = ''
  formData.ecuBrand = ''
  formData.type = ''
  formData.url = ''
  fileList.value = []
}

// 提交表单
async function submit() {
  try {
    const status = await form.value.validate()

    if (status) {
      btnConfig.loading = true
      console.log('提交的表单数据:', formData)
      const res: any = await onlineUpdateAPI(formData)
      uni.showToast({
        title: '提交成功',
        icon: 'success',
      })
      btnConfig.loading = false
      resetForm()
    }
  }
  catch (error) {
    console.error('提交失败:', error)
    btnConfig.loading = false
    uni.showToast({
      title: '提交失败',
      icon: 'none',
    })
  }
}

onMounted(() => {
  const list = appStore.getDictByCode('ECU_UPGRADE')
  const list2 = appStore.getDictByCode('ecuBrandCode')
  typeList.value = list.map((item: any) => ({
    value: item.dicValue,
    text: item.dicValueName,
  }))
  ecuBrandList.value = list2.map((item: any) => ({
    value: item.dicValue,
    text: item.dicValueName,
  }))
})
</script>

<template>
  <z-paging
    ref="paging"
  >
    <view class="container">
      <uv-form ref="form" label-position="left" :model="formData" :rules="rules" label-width="100">
        <uv-form-item label="是否全部升级:" prop="fullUpgrade" required>
          <uv-radio-group v-model="formData.fullUpgrade">
            <uv-radio :name="true" label="是" style="margin-right: 50rpx;" />
            <uv-radio :name="false" label="否" />
          </uv-radio-group>
        </uv-form-item>
        <uv-form-item v-if="!formData.fullUpgrade" label="车辆编号:" prop="bikeCode">
          <uv-input v-model="formData.bikeCode" placeholder="请输入" border="surround" />
        </uv-form-item>
        <uv-form-item v-if="!formData.fullUpgrade" label="中控编号:" prop="ecuSn">
          <uv-input v-model="formData.ecuSn" placeholder="请输入" border="surround" />
        </uv-form-item>
        <uv-form-item label="中控品牌:" prop="ecuBrand" required>
          <uni-data-select
            v-model="formData.ecuBrand"
            :localdata="ecuBrandList"
            placeholder="请选择"
            clear
          />
        </uv-form-item>
        <uv-form-item label="升级类型:" prop="type" required>
          <uni-data-select
            v-model="formData.type"
            :localdata="typeList"
            placeholder="请选择"
            clear
          />
        </uv-form-item>
        <uv-form-item label="文件地址:" prop="url" required>
          <uv-upload
            :file-list="fileList"
            name="1"
            upload-icon="folder"
            accept="all"
            :max-count="1"
            @after-read="afterRead"
            @delete="deletePic"
          />
        </uv-form-item>
      </uv-form>
    </view>
    <template #bottom>
      <view class="bottom-button-zaping">
        <uv-button
          type="primary"
          text="升级设备"
          :loading="btnConfig.loading"
          :loading-text="btnConfig.loadingText"
          @click="submit"
        />
      </view>
    </template>
  </z-paging>
</template>

<style lang="scss" scoped>
.container {
  width: calc(100% - 60rpx);
  padding: 20rpx 30rpx;
}
</style>
