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

definePage({
  style: {
    navigationBarTitleText: '换电',
    navigationBarBackgroundColor: '#1488f5',
    navigationBarTextStyle: 'white',
  },
})

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: '',
}) // 车辆信息

// 测试项列表
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 openfaultreport() {

}

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

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

async function openBatteryLock() {

}

// 获取车辆详情
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('获取车辆详情失败'))
  }
}

//  确定按钮点击事件
async function handleBtnClick(value: any, key: string, index: number) {
  if (!formData.value.bikeCode) {
    return uni.showToast({
      title: '无车辆编号',
      icon: 'none',
    })
  }
  list[key].btnLoading = true
  try {
    const result: boolean = await executeCommandAPI({
      ecuSn: undefined,
      bikeCode: formData.value.bikeCode,
      commandCode: value.key,
    })
    if (result) {
      uni.showToast({
        title: '执行成功',
        icon: 'success',
      })
    }
    else {
      uni.showToast({
        title: '执行失败',
        icon: 'error',
      })
    }
  }
  catch (e) {
    uni.showToast({
      title: e.message,
      icon: 'error',
    })
    console.error('中控测试报错------>', e)
  }
  finally {
    list[key].btnLoading = false
  }
}

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: '提交失败',
      icon: 'error',
    })
  }
  finally {
    btnConfig.btnLoading = false
  }
}

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

<template>
  <z-paging
    ref="paging"
    bg-color="#f3f3f3"
  >
    <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?.name || '--' }}
          </uv-form-item>
          <uv-form-item label="电池电量:" prop="name" border-bottom>
            {{ carDetail?.soc || '--' }}%
          </uv-form-item>
          <!-- <uv-form-item label="车辆位置:" prop="name" border-bottom>
            <uv-cell-group>
              <uv-cell title="查看地图" is-link :title-style="labelStyle" />
            </uv-cell-group>
            <view class="m-t-5 flex-row gap-5">
              <uv-button type="primary" size="small" text="寻车铃" />
              <uv-button type="primary" size="small" text="开锁" />
              <uv-button type="primary" size="small" text="关锁" />
            </view>
          </uv-form-item> -->
          <uv-form-item label="新电池编号:" prop="name">
            <bikeCodeScan v-model="formData.batteryCode" placeholder="请输入或扫码" @scan-change="onScanByBatteryCode" />
          </uv-form-item>
          <!-- 按钮 -->
          <!-- <uv-button class="m-t-5" type="primary" text="打开电池仓" @click="openBatteryLock" /> -->
          <!-- 提示 -->
          <view class="fz-24 text-right">
            <text class="b-font-gray-sm">电池仓打不开，</text>
            <text
              class="text-primary"
              style="font-weight: bold"
              @click="openfaultreport"
            >
              上报故障
            </text>
          </view>
        </uni-card>
      </uv-form>

      <!-- 按钮 -->
      <uni-card>
        <view class="btn_tools">
          <uv-button
            v-for="(value, key, index) in list"
            :key="key"
            :loading="value.btnLoading"
            :loading-text="value.btnLoadingText"
            type="primary"
            :text="value.btnText"
            :custom-text-style="{
              fontSize: '28rpx',
            }"
            :custom-style="testBtnConfig"
            @click="handleBtnClick(value, key, index)"
          />
        </view>
      </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"
          @click="handleSubmit"
        />
      </view>
    </template>
  </z-paging>
</template>

<style lang="scss" scoped>
.container {
}

.btn_tools {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
