<script lang="ts" setup>
import { getEbikeDetailForWorkAPI, postOperatoringChangeBatteryAPI } from '@/api/operator'
import bikeCodeScan from '@/components/bikeCodeScan/bikeCodeScan.vue'
import instructTools from '@/components/instructTools/instructTools.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 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('请输入车辆编号'))
  }
  try {
    const res = await getEbikeDetailForWorkAPI(formData.value.bikeCode)
    if (res) {
      carDetail.value = res
    }
  }
  catch (e) {
    console.error(new Error('获取车辆详情失败'))
  }
}

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

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

  btnConfig.btnLoading = true
  try {
    const res: any = await postOperatoringChangeBatteryAPI({
      bikeCode: formData.value.bikeCode,
      batteryCode: formData.value.batteryCode,
    })
    uni.showToast({
      title: '提交成功',
      icon: 'success',
    })
    resetData()
  }
  catch (e) {
    uni.showToast({
      title: e.message || '提交失败',
      icon: 'none',
    })
  }
  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}%` : '--' }}
          </uv-form-item>
          <uv-form-item label="车辆位置:" prop="name" border-bottom>
            {{ '--' }}
          </uv-form-item>
        </uni-card>

        <!-- 新电池编号 -->
        <uni-card>
          <uv-form-item label="新电池编号:" prop="name">
            <bikeCodeScan v-model="formData.batteryCode" placeholder="请输入或扫码" @scan-change="onScanByBatteryCode" />
          </uv-form-item>
        </uni-card>
      </uv-form>

      <uni-card>
        <instructTools :bike-code="formData.bikeCode" />
      </uni-card>

      <!-- 温馨提示 -->
      <view class="u-p-a-20">
        <view
          class="fz-28 text-gray"
          style="margin-bottom: 10px; font-weight: bold"
        >
          温馨提示
        </view>
        <view class="fz-24 text-gray">
          1、读取到新电池的电量即视为更换成功新的电池;
        </view>
        <view class="fz-24 text-gray">
          2、电池更换完成自动读取设备状态和电池电量，过程可能需要个几分钟；
        </view>
        <view class="fz-24 text-gray">
          3、更换完成请点击下面完成换电按钮；
        </view>
        <view class="fz-24 text-gray">
          4、如果直接点击更换完成，电量会暂时变成41%，系统检测到电
          量上报后会自动变成上报的电量；
        </view>
      </view>
    </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>
