<script lang="ts" setup>
import { executeCommandAPI } from '@/api/centerControl'
import { useCenterControlStore } from '@/store'

// 列表数据
const props = defineProps(['code', 'type'])
const emits = defineEmits(['complete'])
const centerStore = useCenterControlStore()
const oneTestDisabled = ref(false)
const list_item_style = computed(() => {
  return {
    padding: '20rpx 0',
    borderBottom: '2rpx solid #cccccc',
    fontSize: '28rpx',
    color: '#6a6a6a',
  }
})

const list_item_btn_style = computed(() => {
  return {
    height: '35px',
    fontSize: '24rpx',
  }
})

// 测试项列表
const list = reactive({
  findBike: {
    msg: '',
    name: '寻车铃',
    key: 'FIND_BIKE',
    status: 'none', // none,loading,success,fail
    tip: '',
    btnText: '执行',
    btnLoadingText: '执行中',
    btnLoading: false,
  },
  gps: {
    msg: '',
    name: 'gps测试',
    key: 'GPS',
    status: 'none',
    tip: '',
    btnText: '执行',
    btnLoadingText: '执行中',
    btnLoading: false,
  },
  openLock: {
    msg: '',
    name: '打开电池锁',
    key: 'OPEN_BATTERY_LOCK',
    status: 'none',
    tip: '',
    btnText: '执行',
    btnLoadingText: '执行中',
    btnLoading: false,
  },
  resetBattery: {
    msg: '',
    name: '复位电池仓锁',
    key: 'CLOSE_BATTERY_LOCK',
    status: 'none',
    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,
  },
  openHelmet: {
    msg: '',
    name: '打开头盔锁',
    key: 'OPEN_HELMET',
    status: 'none',
    tip: '',
    btnText: '执行',
    btnLoadingText: '执行中',
    btnLoading: false,
  },
  offPower: {
    msg: '',
    name: '断电',
    key: 'POWER_OFF',
    status: 'none',
    tip: '',
    btnText: '执行',
    btnLoadingText: '执行中',
    btnLoading: false,
  },
})

// 初始化单个列表数据
function initListItem(key: string) {
  list[key].status = 'none'
  list[key].msg = ''
}

// 执行按钮点击
async function handleBtnClick(value: any, key: string, index: number) {
  initListItem(key)
  list[key].btnLoading = true
  list[key].status = 'loading'

  try {
    const result: boolean = await executeCommandAPI({
      ecuSn: centerStore.queryByBike.ecuSn,
      bikeCode: centerStore.queryByBike.bikeCode,
      commandCode: value.key,
    })
    if (result) {
      list[key].btnLoading = false
      list[key].status = 'success'
      list[key].msg = '执行成功'
    }
    else {
      list[key].status = 'fail'
      list[key].msg = '执行失败'
      list[key].btnLoading = false
    }
  }
  catch (e) {
    console.error('中控测试报错------>', e)
    list[key].status = 'fail'
    list[key].msg = e.message
    list[key].btnLoading = false
  }
}

// 初始化所有列表数据并执行一键操作
async function initAllTest() {
  // 重置状态
  oneTestDisabled.value = true

  for (const key in list) {
    list[key].status = 'none'
    list[key].msg = ''
    list[key].btnLoading = false
  }

  const keys = Object.keys(list)

  // 逐条串行执行
  for (const key of keys) {
    console.log(`➡️ 正在执行: ${key}`)
    await executeCommandAsync(key)
  }
  onComplete()
}

// 封装单个命令执行逻辑
async function executeCommandAsync(key: string) {
  list[key].btnLoading = true
  list[key].status = 'loading'

  try {
    const result = await executeCommandAPI({
      ecuSn: centerStore.queryByBike.ecuSn,
      bikeCode: centerStore.queryByBike.bikeCode,
      commandCode: list[key].key,
    })

    if (result) {
      list[key].status = 'success'
      list[key].msg = '执行成功'
    }
    else {
      list[key].status = 'fail'
      list[key].msg = '执行失败'
    }
  }
  catch (e) {
    console.error(`中控测试报错 -----> ${key}`, e)
    list[key].status = 'fail'
    list[key].msg = e.message || '执行失败'
  }
  finally {
    list[key].btnLoading = false
  }
}

// 循环执行命令
function loopExecuteCommand() {
  initAllTest()
}

// 回调函数：所有命令执行完毕后触发
function onComplete() {
  console.log('✅ 所有测试项执行完成！')
  oneTestDisabled.value = false
  emits('complete')
}

defineExpose({
  loopExecuteCommand,
})
</script>

<template>
  <view class="list-main">
    <uv-list>
      <uv-list-item
        v-for="(value, key, index) in list"
        :key="key"
        :custom-style="list_item_style"
      >
        <view class="list-item">
          <view class="text_bar">
            <view>{{ value.name }} </view>
            <view class="result">
              <uv-transition
                :custom-style="{
                  display: 'flex',
                  alignItems: 'center',
                }"
                :duration="200"
                :show="value.status === 'fail'"
              >
                <uv-icon name="info-circle" color="red" />
                <text style="color: red;">{{ value.msg }}</text>
              </uv-transition>

              <uv-transition
                :custom-style="{
                  display: 'flex',
                  alignItems: 'center',
                }"
                :duration="200"
                :show="value.status === 'success'"
              >
                <uv-icon name="checkmark-circle" color="#07c160" />
                <text style="color: #07c160;">{{ value.msg }}</text>
              </uv-transition>
            </view>
          </view>
          <view class="btn_bar">
            <uv-button
              :loading="value.btnLoading"
              :loading-text="value.btnLoadingText"
              type="primary"
              :text="value.btnText"
              :disabled="centerStore.isOnline !== 1 || oneTestDisabled"
              :custom-style="list_item_btn_style"
              @click="handleBtnClick(value, key, index)"
            />
          </view>
        </view>
      </uv-list-item>
    </uv-list>
  </view>
</template>

<style lang="scss" scoped>
.list-main {
  margin-top: 20rpx;
  width: calc(100% - 40rpx);
  padding: 20rpx;
  background-color: white;
  border-radius: 10rpx;
  box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.1);

  .list-item {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .text_bar {
      font-size: 28rpx;
      display: flex;
      align-items: center;

      .result {
        margin-left: 30rpx;
      }
    }

    .btn_bar {
    }
  }
}

.transition {
  display: flex;
  align-items: center;
}
</style>
