<script lang="ts" setup>
import { createChangeOrderAPI, getEbikeDetailForWorkAPI } from '@/api/operator'
import bikeCodeScan from '@/components/bikeCodeScan/bikeCodeScan.vue'
import { useAppStore } from '@/store'
import { systemInfo } from '@/utils/systemInfo'

definePage({
  style: {
    navigationStyle: 'custom',
  },
})

const orderIds = ref<any>(undefined)
const appStore = useAppStore()
const labelStyle = {
  padding: '0 5px 0 0',
  color: '#7c7c7c',
  fontSize: '14px',
  fontWeight: 'normal',
  lineHeight: '32px',
}
const btnConfig = reactive({
  btnText: '生成工单',
  btnLoading: false,
  btnLoadingText: '正在生成',
})
const testBtnConfig = reactive({
  width: '145rpx',
  heigth: '60rpx',
})

const carDetail = ref<any>({
  soc: '',
  bikeCode: '',
  ecuSn: '',
}) // 车辆信息

const radiolist = ref<any>([
  { label: '是', value: true },
  { label: '否', value: false },
])
const acceptOrders = ref(false) // 是否接受订单
// 测试项列表
const list = reactive({
  findBike: {
    msg: '',
    name: '寻车铃',
    key: 'FIND_BIKE',
    status: 'none', // none,loading,success,fail
    tip: '',
    btnText: '寻车铃',
    btnLoadingText: '执行',
    btnLoading: false,
  },
  unlocking: {
    msg: '',
    name: '开锁',
    key: 'UNLOCK',
    status: 'none',
    tip: '',
    btnText: '开锁',
    btnLoadingText: '执行',
    btnLoading: false,
  },
  Locking: {
    msg: '',
    name: '关锁',
    key: 'LOCK',
    status: 'none',
    tip: '',
    btnText: '关锁',
    btnLoadingText: '执行',
    btnLoading: false,
  },
  openLock: {
    msg: '',
    name: '打开电池锁',
    key: 'OPEN_BATTERY_LOCK',
    status: 'none',
    tip: '',
    btnText: '执行',
    btnLoadingText: '执行中',
    btnLoading: false,
  },
})

// 表单引用
const form = ref(null)

// 表单校验规则
const formData = ref({
  bikeCode: '',
  batteryCode: '',
})

// 表单校验规则
const rules = {}

// 返回
function handleBack() {
  uni.navigateBack()
}

// 扫码车牌
function onScanByBikeCode(res: any) {
  formData.value.bikeCode = res
  getEbikeDetail()
}

function onScanByBatteryCode(res: any) {
  formData.value.batteryCode = res
}

// 获取车辆详情
async function getEbikeDetail() {
  if (!formData.value.bikeCode) {
    return console.error(new Error('请输入车辆编号'))
  }
  uni.showLoading({
    title: '加载中...',
  })
  try {
    const res = await getEbikeDetailForWorkAPI(formData.value.bikeCode)
    if (res) {
      carDetail.value = res
    }
  }
  catch (e) {
    console.error(new Error('获取车辆详情失败'))
  }
  finally {
    uni.hideLoading()
  }
}

function resetData() {
  formData.value = {
    bikeCode: '',
    batteryCode: '',
  }
  carDetail.value = {
    bikeCode: '',
    soc: '',
  }
}

// 提交表单
async function handleSubmit() {
  if (!formData.value.bikeCode) {
    uni.showToast({
      title: '请输入车辆编号',
      icon: 'none',
    })
    return
  }

  btnConfig.btnLoading = true
  try {
    const res: any = await createChangeOrderAPI(carDetail.value.ecuSn, acceptOrders.value)

    if (acceptOrders.value) {
      uni.showModal({
        title: '提示',
        content: '工单生成成功，是否前往完成工单？',
        confirmText: '继续完成',
        confirmColor: '#FF6B6B',
        cancelText: '取消',
        cancelColor: '#333333',
        success: (res) => {
          if (res.confirm) {
            uni.reLaunch({
              url: `/pages-sub/changebatteries/changebatteries?bikeCode=${formData.value.bikeCode}`,
            })
          }
          resetData()
        },
      })
    }
    else {
      uni.showToast({
        title: '工单生成',
        icon: 'success',
      })
      resetData()
    }
  }
  catch (e) {
    uni.showToast({
      title: e.message || '生成失败',
      icon: 'error',
    })
  }
  finally {
    btnConfig.btnLoading = false
  }
}

onLoad((query) => {
  const { bikeCode, orderId } = query

  if (bikeCode) {
    formData.value.bikeCode = bikeCode
    getEbikeDetail()
  }
})
</script>

<template>
  <z-paging
    ref="paging"
    bg-color="#f3f3f3"
  >
    <template #top>
      <view class="custom_navbar" :style="{ height: `${systemInfo.statusBarHeight + 44}px` }">
        <view class="back_bar">
          <uv-icon name="arrow-left" color="#222222" size="24" @click="handleBack" />
          <text class="text">换电工单</text>
        </view>
      </view>
    </template>
    <view>
      <uv-form
        ref="form"
        label-position="left"
        :model="formData"
        :rules="rules"
        :label-width="90"
        :label-style="labelStyle"
      >
        <uni-card>
          <uv-form-item label="车辆编号:" prop="name" border-bottom>
            <bikeCodeScan v-model="formData.bikeCode" @scan-change="onScanByBikeCode" />
          </uv-form-item>
          <uv-form-item label="车辆状态:" prop="name" border-bottom>
            {{ appStore.translateDictValue(carDetail?.usageStatus, 'BikeUsageStatus') || '--' }}
          </uv-form-item>
          <uv-form-item label="电池编号:" prop="name" border-bottom>
            {{ carDetail?.batteryCode || '--' }}
          </uv-form-item>
          <uv-form-item label="电池电量:" prop="name" border-bottom>
            {{ carDetail?.soc ? `${carDetail?.soc}%` : carDetail?.soc === 0 ? '0%' : '--' }}
          </uv-form-item>
          <uv-form-item label="车辆位置:" prop="name" border-bottom>
            {{ carDetail.chineseLocation || '--' }}
          </uv-form-item>
        </uni-card>

        <uni-card>
          <uv-form-item label="自己是否接单" border-bottom :label-width="100">
            <uv-radio-group v-model="acceptOrders">
              <uv-radio
                v-for="(item, index) in radiolist"
                :key="index"
                :custom-style="{ margin: '8px' }"
                :label="item.label"
                :name="item.value"
              />
            </uv-radio-group>
          </uv-form-item>
        </uni-card>
      </uv-form>
    </view>

    <template #bottom>
      <view class="bottom-button-zaping">
        <uv-button
          type="primary"
          :text="btnConfig.btnText"
          :loading="btnConfig.btnLoading"
          :loading-text="btnConfig.btnLoadingText"
          :custom-style="{
            backgroundImage: `linear-gradient(135deg, #1089FF 0%, #0F5BFF 100%)`,
            borderRadius: '28rpx',
            height: '100rpx',
          }"
          :custom-text-style="{
            fontSize: '32rpx',
            marginLeft: '8rpx',
          }"
          @click="handleSubmit"
        />
      </view>
    </template>
  </z-paging>
</template>

<style lang="scss" scoped>
 .btn_tools {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.custom_navbar {
  width: 100%;
  position: relative;
  background-color: white;

  .back_bar {
    display: flex;
    align-items: center;
    position: absolute;
    bottom: 25rpx;
    left: 30rpx;

    .text {
      font-family: SourceHanSansCN-Medium;
      font-size: 34rpx;
      color: #222222;
      letter-spacing: 0;
      font-weight: 500;
    }
  }
}
</style>
