<script lang="ts" setup>
import { changeBindEbikeAPI, getEbikeDetailForWorkAPI, getEbikeInfoByEcuSnAPI } from '@/api/operator'
import AMapWX from '@/plugIns/amap-wx.130.js'
import { reverseGeocoder } from '@/utils/map'
import { systemInfo } from '@/utils/systemInfo'
import { scanCode } from '@/utils/tools'

const { VITE_AMAP_KEY } = import.meta.env
const amapsdk = new AMapWX({
  key: VITE_AMAP_KEY,
})

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

const paging = ref(null)
const btnConfig = reactive({
  loading: false,
  loadingText: '提交中...',
})
const rawAddress = ref('--')
const newAddress = ref('--')
const carDetails = ref<any>({
  ecuSn: undefined,
  location: {
    longitude: undefined,
    latitude: undefined,
  },
  voltage: undefined,
})
const formData = ref({
  bikeCode: '',
  remark: '',
  ecuSn: '',
})
const centerControlDetail = ref<any>({})

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

// 解析位置
async function getLocation(longitude: number, latitude: number): Promise<string> {
  if (!longitude || !latitude) {
    return Promise.resolve('__')
  }

  return new Promise((resolve, reject) => {
    reverseGeocoder({
      mapsdk: amapsdk,
      longitude,
      latitude,
      success: (res: any) => {
        const { formatted_address } = res.regeocodeData
        resolve(formatted_address || '__')
      },
      fail: (err: any) => {
        console.error('解析位置失败', err)
        reject(err)
      },
    })
  })
}
// 车辆编号扫码
function handleScanByCarCode() {
  scanCode({
    success: (res: any) => {
      formData.value.bikeCode = res.code
      getEbikeDetailForWork()
    },
    fail: () => {
    },
  })
}

function handleScanByCenterCode() {
  scanCode({
    isSN: true,
    success: (res: any) => {
      const { SN } = res
      if (!SN) {
        uni.showToast({
          title: '解析失败',
          icon: 'error',
        })
        return
      }
      formData.value.ecuSn = SN
      getEbikeInfoByEcuSn()
    },
    fail: () => {
      uni.showToast({
        title: '扫码失败',
        icon: 'error',
      })
    },
  })
}

async function getEbikeDetailForWork() {
  uni.showLoading({
    title: '加载中...',
  })
  try {
    const res = await getEbikeDetailForWorkAPI(formData.value.bikeCode)
    if (res) {
      carDetails.value = res
      rawAddress.value = await getLocation(res?.location?.longitude, res?.location?.latitude)
    }
  }
  catch (e) {
    console.error(e)
  }
  finally {
    uni.hideLoading()
  }
}

async function getEbikeInfoByEcuSn() {
  try {
    const res = await getEbikeInfoByEcuSnAPI({ ecuSn: formData.value.ecuSn })
    if (res) {
      centerControlDetail.value = res
      newAddress.value = await getLocation(res?.longitude, res?.latitude)
    }
  }
  catch (e) {
    console.error(e)
    formData.value.ecuSn = ''
    centerControlDetail.value = {}
  }
}

// 提交更换中控
function handleChange() {
  if (!formData.value.bikeCode) {
    uni.showToast({
      title: '请输入车辆编号',
      icon: 'none',
    })
    return
  }

  if (!formData.value.ecuSn) {
    uni.showToast({
      title: '请输入中控编号',
      icon: 'none',
    })
    return
  }

  uni.showModal({
    title: '提示',
    content: '确认更换当前中控绑定的设备吗?换绑后原设备将失去控制权限。',
    success: async (res) => {
      if (res.confirm) {
        uni.showLoading({
          title: '提交中...',
        })
        try {
          const res = await changeBindEbikeAPI({
            bikeCode: formData.value.bikeCode,
            ecuSn: formData.value.ecuSn,
          })
          uni.showToast({
            title: '已换绑',
            icon: 'success',
          })
          setTimeout(() => {
            uni.navigateBack()
          }, 800)
        }
        catch (e) {
          console.error(e)
        }
        finally {
          uni.hideLoading()
        }
      }
    },
  })
}
</script>

<template>
  <z-paging
    ref="paging"
    bg-color="#f9f9f9"
  >
    <template #top>
      <view class="custom_navbar" :style="{ height: `${systemInfo.statusBarHeight + 44}px` }">
        <view class="back_bar">
          <uv-icon name="arrow-left" color="white" size="24" @click="handleBack" />
          <text class="text">中控换绑</text>
        </view>
      </view>
    </template>

    <view class="container">
      <!-- 车辆原中控 -->
      <view class="card_wrapper">
        <view class="header">
          车辆原中控
        </view>
        <view class="row_long">
          <view class="label">
            车辆编码：
          </view>
          <view class="value">
            <uv-input
              v-model="formData.bikeCode"
              border="none"
              placeholder="请扫描或输入车辆编号"
              clearable
              @confirm="getEbikeDetailForWork"
            >
              <template #suffix>
                <uv-icon name="scan" color="#999999" size="28" @click="handleScanByCarCode" />
              </template>
            </uv-input>
          </view>
        </view>
        <view class="info_row">
          <view class="col">
            <view class="key">
              中控编号：
            </view>
            <view class="value">
              {{ carDetails.ecuSn || '--' }}
            </view>
          </view>
          <view class="col">
            <view class="key">
              车辆状态：
            </view>
            <view class="value">
              {{ carDetails?.online ? '在线' : carDetails.bikeCode ? '离线' : '--' }}
            </view>
          </view>
        </view>
        <view class="info_row">
          <view class="col">
            <view class="key">
              电压：
            </view>
            <view class="value">
              {{ carDetails.voltage || '--' }} V
            </view>
          </view>
        </view>
        <view class="info_row">
          <view class="col">
            <view class="key">
              定位时间：
            </view>
            <view class="value">
              {{ carDetails.latestTime || '--' }}
            </view>
          </view>
        </view>
        <view class="info_row">
          <view class="col">
            <view class="key">
              中控位置：
            </view>
            <view class="value">
              {{ rawAddress || '--' }}
            </view>
          </view>
        </view>
        <view class="row_long" style="padding-top: 0;">
          <view class="label">
            更换原因：
          </view>
          <view class="value">
            <uv-textarea v-model="formData.remark" placeholder="请输入更换原因" auto-height border="none" />
          </view>
        </view>
      </view>
      <!-- 更换中控 -->
      <view class="card_wrapper">
        <view class="header">
          更换中控
        </view>
        <view class="row_long">
          <view class="label">
            SN编号：
          </view>
          <view class="value">
            <uv-input v-model="formData.ecuSn" border="none" placeholder="请扫描或输入SN编号" @confirm="getEbikeInfoByEcuSn">
              <template #suffix>
                <uv-icon name="scan" color="#999999" size="28" @click="handleScanByCenterCode" />
              </template>
            </uv-input>
          </view>
        </view>
        <view class="info_row">
          <!-- <view class="col">
            <view class="key">
              设备状态：
            </view>
            <view class="value">
              {{ centerControlDetail?.online ? '在线' : centerControlDetail.bikeCode ? '离线' : '--' }}
            </view>
          </view> -->
          <view class="col">
            <view class="key">
              电压：
            </view>
            <view class="value">
              {{ centerControlDetail.realVoltage || '--' }} V
            </view>
          </view>
        </view>
        <view class="info_row">
          <view class="col">
            <view class="key">
              定位时间：
            </view>
            <view class="value">
              {{ centerControlDetail.latestTime || '--' }}
            </view>
          </view>
        </view>
        <view class="info_row">
          <view class="col">
            <view class="key">
              中控位置：
            </view>
            <view class="value">
              {{ newAddress || '--' }}
            </view>
          </view>
        </view>
      </view>
    </view>

    <template #bottom>
      <view class="bottom-button-zaping">
        <uv-button
          type="primary"
          text="确定绑定"
          :loading="btnConfig.loading"
          :loading-text="btnConfig.loadingText"
          :custom-style="{
            backgroundImage: `linear-gradient(226deg, #3C9CFE 0%, #067AF2 100%)`,
            borderRadius: '28rpx',
            height: '100rpx',
          }"
          :custom-text-style="{
            fontSize: '32rpx',
            marginLeft: '8rpx',
          }"
          @click="handleChange"
        />
      </view>
    </template>
  </z-paging>
</template>

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

  .card_wrapper {
    background: #ffffff;
    padding: 40rpx 20rpx;
    width: calc(100% - 40rpx);
    border-radius: 24rpx;
    margin-bottom: 30rpx;

    .header {
      font-family: PingFangSC-Medium;
      font-size: 30rpx;
      color: #343434;
      letter-spacing: 0;
      font-weight: 500;
    }

    .row_long {
      width: 100%;
      display: flex;
      align-items: center;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      border-bottom: 1px solid rgba(228, 228, 228, 1);
      padding: 20rpx 0;
      margin-bottom: 33rpx;

      .label {
        width: 160rpx;
        font-size: 28rpx;
        color: #333333;
      }

      .value {
        width: calc(100% - 160rpx);
        font-size: 28rpx;
        color: #666666;
        word-break: break-all;
      }
    }

    .info_row {
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
      margin-bottom: 50rpx;

      .col {
        flex: 1;
        font-family: PingFangSC-Regular;
        font-weight: 400;
        display: flex;
        align-items: center;

        .key {
          width: 140rpx;
          font-size: 28rpx;
          color: #333333;
        }
        .value {
          width: calc(100% - 140rpx);
          font-size: 28rpx;
          color: #666666;
        }
      }
    }
  }
}

.custom_navbar {
  width: 100%;
  position: relative;
  background-color: #0f74ff;

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

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