<script lang="ts" setup>
import { bindEbikeAPI } from '@/api/operator'
import { useAppStore, useOperatorStore } from '@/store'
import { systemInfo } from '@/utils/systemInfo'
import { scanCode } from '@/utils/tools'

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

const isSubmit = ref(false)
const appStore = useAppStore()
const operatorStore = useOperatorStore()
const ecuBrandList = ref([])// 中控品牌列表
const operatorAllList = ref<any>([])
const form = ref<any>(null)
const formData = reactive<any>({
  operatorId: '',
  remarks: '',
  bikeCode: '',
  ecuCode: '',
  batteryCode: '',
  hasHelme: false,
})
const radiolist = ref([
  { name: true, label: '是' },
  { name: false, label: '否' },
])
const labelStyle = ref({
  'font-size': '28rpx',
  'color': '#333',
})
const rules = {
  // 中控已经有了运营商的信息，不需要再绑定
  // operatorId: {
  //   type: 'string',
  //   required: true,
  //   message: '请选择运营商',
  //   trigger: ['change', 'blur'],
  // },
  bikeCode: {
    type: 'string',
    required: true,
    message: '请输入车辆编号',
    trigger: ['change', 'blur'],
  },
  ecuCode: {
    type: 'string',
    required: true,
    message: '请输入中控SN',
    trigger: ['change', 'blur'],
  },
  // batteryCode: {
  //   type: 'string',
  //   required: true,
  //   message: '请输入电池编号',
  //   trigger: ['change', 'blur'],
  // },
  hasHelme: {
    type: 'boolean',
    required: true,
    message: '请选择是否包含头盔',
    trigger: ['change', 'blur'],
  },
}

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

// 扫码获取车辆编号
function codeScan(type: string) {
  scanCode({
    isSN: type === 'ecuCode',
    success: (res: any) => {
      switch (type) {
        case 'bikeCode':
          formData.bikeCode = res.code
          break
        case 'ecuCode':
          formData.ecuCode = res.SN
          break
        case 'batteryCode':
          formData.batteryCode = res.code
          break
        default:
          break
      }
    },
    fail: () => {
      uni.showToast({
        title: '扫码失败',
        icon: 'none',
      })
    },
  })
}

// 获取运营商列表
async function getOperatorList() {
  operatorAllList.value = await operatorStore.getOperatorList(true)
}
// 获取中控品牌列表
async function getEcuBrandList() {
  const dic = appStore.getDictByCode('ecuBrandCode')
  ecuBrandList.value = dic.map((item: any) => ({
    text: item.dicValueName,
    value: item.dicValue,
  }))
}

// 初始化表单数据
function initForm() {
  formData.operatorId = ''
  formData.bikeCode = ''
  formData.ecuCode = ''
  formData.batteryCode = ''
  formData.hasHelme = false
  formData.remarks = ''
  form.value?.resetFields()
}

async function submit() {
  try {
    isSubmit.value = true
    const status = await form.value.validate()

    if (status) {
      const res = await bindEbikeAPI({
        operatorId: formData.operatorId,
        bikeCode: formData.bikeCode,
        ecuCode: formData.ecuCode,
        batteryCode: formData.batteryCode,
        hasHelme: formData.hasHelme,
        remarks: formData.remarks,
      })

      uni.showToast({
        title: '绑定成功',
        icon: 'success',
      })

      initForm()
      isSubmit.value = false
    }
  }
  catch (err) {
    console.log(err)
    isSubmit.value = false
  }
}

getEcuBrandList()
getOperatorList()
</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="inner">
        <uv-form
          ref="form"
          label-position="left"
          :model="formData"
          :rules="rules"
          label-width="80"
          :label-style="labelStyle"
        >
          <view class="module">
            <view class="header_bar">
              绑定内容
            </view>
            <view class="form_bar">
              <uv-form-item label="车辆编号" prop="bikeCode" required>
                <uv-input v-model="formData.bikeCode" placeholder="请扫描或输入车辆编号" border="surround">
                  <template #suffix>
                    <uv-icon name="scan" color="#cbcad0" size="28" @click="codeScan('bikeCode')" />
                  </template>
                </uv-input>
              </uv-form-item>
              <uv-form-item label="中控SN" prop="ecuCode" required>
                <uv-input v-model="formData.ecuCode" placeholder="请扫描或输入中控SN" border="surround">
                  <template #suffix>
                    <uv-icon name="scan" color="#cbcad0" size="28" @click="codeScan('ecuCode')" />
                  </template>
                </uv-input>
              </uv-form-item>
              <!-- <uv-form-item label="运营商" prop="operatorId" required>
                <uni-data-select
                  v-model="formData.operatorId"
                  :localdata="operatorAllList"
                  placeholder="请选择运营商"
                  clear
                />
              </uv-form-item> -->
              <uv-form-item label="电池" prop="batteryCode">
                <uv-input v-model="formData.batteryCode" placeholder="请扫描或输入电池" border="surround">
                  <template #suffix>
                    <uv-icon name="scan" color="#cbcad0" size="28" @click="codeScan('batteryCode')" />
                  </template>
                </uv-input>
              </uv-form-item>
            </view>
          </view>

          <view class="module">
            <view class="header_bar">
              其他
            </view>
            <view class="form_bar">
              <uv-form-item label="包含头盔" prop="remarks" required>
                <uv-radio-group v-model="formData.hasHelme">
                  <uv-radio
                    v-for="(item, index) in radiolist"
                    :key="index"
                    :custom-style="{ margin: '8px' }"
                    :label="item.label"
                    :name="item.name"
                  />
                </uv-radio-group>
              </uv-form-item>
            </view>
          </view>

          <view class="module">
            <view class="header_bar">
              备注
            </view>
            <view class="form_bar">
              <uv-textarea v-model="formData.remarks" placeholder="请输入内容" border="none" />
            </view>
          </view>
        </uv-form>
      </view>
    </view>

    <template #bottom>
      <view class="bottom-button-zaping">
        <uv-button
          type="primary"
          :loading="isSubmit"
          :custom-style="{
            backgroundImage: `linear-gradient(135deg, #1089FF 0%, #0F5BFF 100%)`,
            borderRadius: '28rpx',
            height: '100rpx',
          }"
          :custom-text-style="{
            fontSize: '32rpx',
            marginLeft: '8rpx',
          }"
          text="绑定入库"
          loading-text="提交中..."
          @click="submit"
        />
      </view>
    </template>
  </z-paging>
</template>

<style lang="scss" scoped>
.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;
    }
  }
}

.container {
  padding: 20rpx;
  width: calc(100% - 40rpx);

  .module {
    padding: 20rpx 30rpx;
    background-color: white;
    width: calc(100% - 60rpx);
    border-radius: 20rpx;
    margin-bottom: 30rpx;

    &:last-child {
      margin-bottom: 0;
    }

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

    .form_bar {
      margin-top: 20rpx;
    }
  }
}

::v-deep .uni-select {
  min-height: 80rpx;
}

::v-deep .uni-select__input-placeholder {
  font-size: 28rpx;
  color: #c1c5cd;
}
</style>
