<template>
  <view class="page-container">
    <uv-navbar title="洗车机" bgColor="#C6171E" leftIconColor="#FFFFFF" :titleStyle="{ color: '#FFFFFF' }" :placeholder="true" @leftClick="handleNavigateBack"></uv-navbar>
    <scroll-view class="content-scroll" scroll-y="true">
      <!-- 设备信息卡片 -->
      <view class="device-info-card">
        <view class="device-number">
          <text class="number-text">洗车机 No.{{ state.device?.shortId }}</text>
          <text v-if="state.device?.hasPa" class="pa-badge">PA</text>
        </view>

        <view class="device-status" :class="'status-' + (state.device?.state || 'idle')">
          <view class="status-dot"></view>
          <text>{{ fmtDictName('WashDevice.state',state.device?.state) }}</text>
        </view>

        <view class="device-functions">
          <view
            class="function-item"
            v-for="f in state.device?.functionList"
            :key="f"
          >
            <uv-icon name="checkbox-mark" size="14" color="#C6171E"></uv-icon>
            <text>{{ f }}</text>
          </view>
        </view>
      </view>

      <!-- 价格公示入口 -->
      <view class="price-entry" v-if="state.device?.price" @click="pricePopupRef?.open()">
        <view class="price-entry-left">
          <text class="price-icon">¥</text>
          <text class="price-text">收费标准</text>
        </view>
        <uv-icon name="arrow-right" size="16" color="#C0C4CC"></uv-icon>
      </view>

      <!-- 价格公示弹窗 -->
      <uv-popup ref="pricePopupRef" mode="center" :round="0" :closeable="false" customStyle="background:transparent;">
        <PriceTable :price="state.device?.price" @close="pricePopupRef?.close()" />
      </uv-popup>

      <!-- 停车费提示 -->
      <view class="parking-notice" v-if="state.parkingFee">
        <view class="parking-notice-left">
          <text class="parking-icon">P</text>
          <text class="parking-text">{{ state.parkingFee }}</text>
        </view>
      </view>

      <!-- 操作按钮卡片 -->
      <view class="control-card">
        <view class="control-wrapper">
          <view
            class="control-button"
            :class="{
              'control-button--active': state.device?.state === 'busy',
              'control-button--disabled': !isDeviceOperable
            }"
            @click="isDeviceOperable && debounceStartStopDevice()"
          >
            <view class="button-icon">
              <view v-if="state.device?.state==='idle'" class="icon-play">
                <uv-icon name="play-circle-fill" size="56" color="#FFFFFF"></uv-icon>
              </view>
              <view v-else-if="state.device?.state==='busy'" class="icon-stop">
                <uv-icon name="pause-circle-fill" size="56" color="#FFFFFF"></uv-icon>
              </view>
              <view v-else class="icon-disabled">
                <uv-icon name="error-circle-fill" size="56" color="#FFFFFF"></uv-icon>
              </view>
            </view>
            <text class="button-text" v-if="state.device?.state==='idle'">启动设备</text>
            <text class="button-text" v-else-if="state.device?.state==='busy'">停止设备</text>
            <text class="button-text" v-else>设备{{ fmtDictName('WashDevice.state', state.device?.state) }}</text>
            <text class="button-tip" v-if="state.device?.state==='idle'">点击开始洗车</text>
            <text class="button-tip" v-else-if="state.device?.state==='busy'">点击结束洗车</text>
            <text class="button-tip" v-else>当前无法操作</text>
          </view>
        </view>
      </view>

      <!-- 操作指南卡片 -->
      <view class="guide-card">
        <view class="card-header">
          <view class="header-dot"></view>
          <text class="header-title">操作指南</text>
          <uv-icon name="question-circle" size="18" color="#909399"></uv-icon>
        </view>

        <view class="guide-list">
          <view class="guide-step" v-for="(step, index) in guideSteps" :key="index">
            <view class="step-number">{{ index + 1 }}</view>
            <text class="step-text">{{ step }}</text>
          </view>
        </view>
      </view>

      <!-- 余额充值卡片 -->
      <view class="balance-card" v-if="state.isLogin" @click="handleGotoRechage">
        <view class="balance-left">
          <view class="balance-icon">
            <uv-icon name="bag" size="22" color="#C6171E"></uv-icon>
          </view>
          <view class="balance-info">
            <text class="balance-label">账户余额</text>
            <view class="balance-amount">
              <text class="amount-symbol">¥</text>
              <text class="amount-number">{{ fmtMoney(state.balance) }}</text>
            </view>
          </view>
        </view>
        <view class="balance-right">
          <text class="recharge-text">去充值</text>
          <uv-icon name="arrow-right" size="16" color="#C6171E"></uv-icon>
        </view>
      </view>

      <view style="height: 40rpx;"></view>
    </scroll-view>

    <login-bar class="w100 text-center"></login-bar>
  </view>
</template>

<script setup lang="ts">
import {onHide, onLoad, onShow} from "@dcloudio/uni-app";
import {computed, reactive, ref} from "vue";
import {debounce, fmtDictName} from "@/utils/common";
import {get, post} from "@/utils/https";
import {checkLogin, fetchToken, tryLogin} from "@/utils/auth";
import {fmtMoney} from "@/utils/common";
import LoginBar from "@/components/login-bar/index.vue";
import PriceTable from "@/components/price-table/index.vue";

const guideSteps = [
  '点击上方【启动设备】按钮启动设备',
  '设备启动后，在设备功能面板按下功能按键选择服务项目',
  '洗车过程中可按功能按键暂停，暂停期间停止计费',
  '洗车结束后，按结算按键或【停止设备】按钮结束计费',
  '请及时将车辆驶离工位，方便后续用户使用'
]

const initState = () => ({
  isLogin:false,
  balance:0,
  device: {
    functions: [],
    deviceName: '',
    state: '',
    stationId: ''
  },
  parkingFee: '',
  time: "00:00:00",
  start: new Date(),
  deviceId: null,
  stationId: null
})

const state = reactive(initState())
const timerId = ref<ReturnType<typeof setInterval> | null>(null)
const pricePopupRef = ref()

const isDeviceOperable = computed(() => {
  const s = state.device?.state
  return s === 'idle' || s === 'busy'
})

const loadBalance = () => {
  get('/account/balance').then((res: any) => {
    state.balance = res.balance
    const gd = getApp<any>().globalData
    gd.user = Object.assign({}, gd.user, { balance: res.balance })
  })
}

onHide(() => {
  if (timerId.value) {
    clearInterval(timerId.value);
    timerId.value = null;
  }
  Object.assign(state, initState());
})

onLoad((options: any) => {
  let id = options?.shortId;
  state.stationId = options?.stationId;
  if (!id) {
    let query = decodeURIComponent(options.q);
    let scanTime = options.scancode_time;
    if (query) {
      id = query.split("#")[1].split("?")[0]
      state.deviceId = id;
    } else {
      return;
    }
  }
  getApp<any>().globalData.deviceId = id;
  state.deviceId = id;
  state.device = getApp<any>().globalData.last.device;
  checkLogin().then((token) => {
    state.isLogin =true;
    setTimeout(() => {
      loadDeviceDetail(id);
      loadBalance()
    }, 200)
  }).catch(e => {
    console.error("onLoad 校验登录失败，自动跳转登录页")
  })
});


onShow((options:any) => {
  addListener();
  checkLogin().then(() => {
    if (!state.deviceId) {
      let deviceId = getApp<any>().globalData.deviceId;
      if (deviceId) {
        loadDeviceDetail(deviceId);
      }
    } else {
      loadDeviceDetail(state.deviceId);
    }
    state.isLogin =true;
    loadBalance()
  }).catch(e => {
    console.error("校验登录失败，自动跳转登录页")
    setTimeout(()=>{
      uni.navigateTo({
        url: `/pages-user/login/index?shortId=${!!state.deviceId?state.deviceId:''}&stationId=${!!state.stationId?state.stationId:''}&redirectUrl=/pages-wash/device/index`
      })
    },1000)

  })


})


const addListener = () => {
  uni.$on('login', function (data) {
    state.isLogin =true;
    if (state.deviceId && data.isLogin) {
      loadDeviceDetail(state.deviceId);
      loadBalance()
    }
  })

  uni.$on('logout', function (data) {
  })
}

const removeListener = () => {
  uni.$off('logout');
  uni.$off('login');
}


const  loadDeviceDetail = (id: any) => {
  state.deviceId = id;
  let ft = fetchToken();
  get(`/wash-device/queryDevice/${id}`).then((res: any) => {
    if (res.currentUserId && res.currentUserId != getApp<any>().globalData.user.id) {
      uni.showToast({
        title: '设备已被占用',
        icon: 'error'
      })
      setTimeout(() => {
        uni.switchTab({
          url: '/pages/index/index'
        })
      }, 2000)
    }
    res.functionList = res.functions?.split("|") || []
    state.device = res;
    loadParkingFee(res.stationId);
    getApp<any>().globalData.deviceId = id;
  }).catch(e => {
    console.error(e)
  })
}

const handleNavigateBack = () => {
  const pages = getCurrentPages()
  if (pages.length > 1) {
    uni.navigateBack()
  } else {
    uni.switchTab({ url: '/pages/index/index' })
  }
}

const debounceStartStopDevice = debounce(() => {
  handleClickDevice();
}, 600)

const handleClickDevice = () => {
  if(!state.isLogin){
    return;
  }
  uni.showModal({
    title: '提示',
    content: state.device?.state === 'idle' ? '确定启动设备开始洗车吗？' : '确定停止设备终止本次服务吗？',
    success: (res) => {
      if (res.confirm) {
        getApp<any>().globalData.refresh =true;
        if (state.device?.state === 'idle') {
          uni.showLoading({
            title: "启动中",
            mask: true,
          });
          post(`/wash-device/startDevice/${state.device?.shortId}`).then((res: any) => {
            uni.hideLoading();
            uni.showToast({
              title: '设备启动成功'
            })
            state.device.state = 'busy'
          })
        } else {
          uni.showLoading({
            title: "停止中",
            mask: true,
          });
          post(`/wash-device/stopDevice/${state.device?.shortId}`).then((res: any) => {
            uni.hideLoading();
            uni.showToast({
              title: '设备停机成功'
            })
            state.device.state = 'idle'
            loadBalance()

          })
        }
      }
    }
  });

}

const countTime = () => {
  if (timerId.value) {
    clearInterval(timerId.value);
  }
  timerId.value = setInterval(() => {
    let delta = new Date().getTime() - state.start.getTime();
    delta = delta / 1000;
    let hour = (delta / 3600).toFixed(0);
    let min = ((delta % 3600) / 60).toFixed(0);
    let second = ((delta % 3600) % 60).toFixed(0);
    state.time = [
      Number(hour) > 9 ? hour : `0${hour}`,
      Number(min) > 9 ? min : `0${min}`,
      Number(second) > 9 ? second : `0${second}`
    ].join(":")
  }, 1000)
}


const loadParkingFee = (stationId: string) => {
  if (!stationId) return
  post('/wash-station/listStation', { stationId, pageSize: 1 }).then((res: any) => {
    const list = res?.list || res?.records || []
    if (list.length > 0) {
      state.parkingFee = list[0].parkingFee || ''
    }
  })
}

const handleGotoRechage = () => {
  uni.navigateTo({
    url: `/pages-user/wallet/recharge?stationId=${state.device.stationId}`
  })
}

</script>

<style lang="scss" scoped>
.page-container {
  width: 100vw;
  height: 100vh;
  background: $uni-bg-color-page;
  display: flex;
  flex-direction: column;
}

.content-scroll {
  flex: 1;
  height: 100%;
  width: 100%;
}

// 设备信息卡片
.device-info-card {
  margin: 24rpx 30rpx;
  @include card-interactive(24rpx);
  padding: 32rpx;
  text-align: center;

  .device-number {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8rpx;
    margin-bottom: 20rpx;

    .number-text {
      font-size: 32rpx;
      font-weight: $uni-font-weight-semibold;
      color: $uni-text-color;
    }

    .pa-badge {
      display: inline-block;
      margin-left: 12rpx;
      padding: 4rpx 12rpx;
      background: #C6171E;
      color: #FFFFFF;
      border-radius: 6rpx;
      font-size: 22rpx;
      font-weight: 700;
      line-height: 1;
      vertical-align: middle;
    }
  }

  .device-status {
    display: inline-flex;
    align-items: center;
    gap: 8rpx;
    padding: 8rpx 20rpx;
    border-radius: 20rpx;
    font-size: 26rpx;
    font-weight: $uni-font-weight-medium;
    margin-bottom: 24rpx;

    .status-dot {
      width: 12rpx;
      height: 12rpx;
      border-radius: 50%;
      animation: pulse 2s infinite;
    }

    &.status-idle {
      background: rgba($uni-color-success, 0.1);
      color: $uni-color-success;

      .status-dot {
        background: $uni-color-success;
      }
    }

    &.status-busy {
      background: rgba($uni-color-warning, 0.1);
      color: $uni-color-warning;

      .status-dot {
        background: $uni-color-warning;
      }
    }

    &.status-fault {
      background: rgba($uni-color-error, 0.1);
      color: $uni-color-error;

      .status-dot {
        background: $uni-color-error;
      }
    }
  }

  .device-functions {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 12rpx;

    .function-item {
      display: flex;
      align-items: center;
      gap: 6rpx;
      padding: 6rpx 16rpx;
      background: rgba($uni-color-primary, 0.08);
      color: $uni-color-primary;
      border-radius: 16rpx;
      font-size: 24rpx;
      font-weight: $uni-font-weight-medium;
    }
  }
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

@keyframes idle-glow {
  0%, 100% {
    opacity: 0;
    transform: scale(1);
  }
  50% {
    opacity: 1;
    transform: scale(1.04);
  }
}

// 价格公示入口
.price-entry {
  margin: 0 30rpx 24rpx;
  padding: 20rpx 28rpx;
  background: rgba($uni-color-primary, 0.05);
  border: 1rpx solid rgba($uni-color-primary, 0.12);
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;

  &-left {
    display: flex;
    align-items: center;
    gap: 12rpx;
    flex: 1;
  }

  .price-icon {
    width: 36rpx;
    height: 36rpx;
    line-height: 36rpx;
    text-align: center;
    font-size: 20rpx;
    font-weight: $uni-font-weight-bold;
    color: #fff;
    background: $uni-color-primary;
    border-radius: 6rpx;
    flex-shrink: 0;
  }

  .price-text {
    font-size: 26rpx;
    color: $uni-text-color-secondary;
  }
}

// 停车费提示
.parking-notice {
  margin: 0 30rpx 24rpx;
  padding: 20rpx 28rpx;
  background: rgba($uni-color-primary, 0.05);
  border: 1rpx solid rgba($uni-color-primary, 0.12);
  border-radius: 16rpx;
  display: flex;
  align-items: center;

  &-left {
    display: flex;
    align-items: center;
    gap: 12rpx;
    flex: 1;
  }

  .parking-icon {
    width: 36rpx;
    height: 36rpx;
    line-height: 36rpx;
    text-align: center;
    font-size: 22rpx;
    font-weight: $uni-font-weight-bold;
    color: #fff;
    background: $uni-color-primary;
    border-radius: 6rpx;
    flex-shrink: 0;
  }

  .parking-text {
    font-size: 26rpx;
    color: $uni-text-color-secondary;
    line-height: 1.5;
    flex: 1;
  }
}

// 控制按钮卡片
.control-card {
  margin: 0 30rpx 24rpx;
  @include card-interactive(24rpx);
  padding: 48rpx 32rpx;

  .control-wrapper {
    display: flex;
    justify-content: center;
    align-items: center;

    .control-button {
      width: 300rpx;
      height: 300rpx;
      border-radius: 50%;
      background: linear-gradient(135deg, $uni-color-primary 0%, $uni-color-primary-light 100%);
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      gap: 6rpx;
      box-shadow: 0 16rpx 40rpx rgba(198, 23, 30, 0.35);
      transition: transform 0.2s cubic-bezier(0.4, 0, 0.2, 1), box-shadow 0.2s cubic-bezier(0.4, 0, 0.2, 1);
      position: relative;
      overflow: hidden;

      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(255, 255, 255, 0.1);
        border-radius: 50%;
        transform: scale(0);
        transition: transform 0.35s cubic-bezier(0.4, 0, 0.2, 1);
      }

      &::after {
        content: '';
        position: absolute;
        top: -8rpx;
        left: -8rpx;
        right: -8rpx;
        bottom: -8rpx;
        border-radius: 50%;
        border: 2rpx solid rgba(198, 23, 30, 0.15);
        opacity: 0;
        transition: opacity 2s ease;
      }

      &:not(.control-button--active)::after {
        animation: idle-glow 2.5s ease-in-out infinite;
      }

      &:active {
        transform: scale(0.95);
        box-shadow: 0 8rpx 24rpx rgba(198, 23, 30, 0.35);

        &::before {
          transform: scale(1);
        }
      }

      .button-icon {
        margin-bottom: 2rpx;
        display: flex;
        align-items: center;
        justify-content: center;

        .icon-play,
        .icon-stop {
          display: flex;
          align-items: center;
          justify-content: center;
          line-height: 1;
        }
      }

      .button-text {
        font-size: 34rpx;
        font-weight: $uni-font-weight-semibold;
        color: $uni-text-color-inverse;
        letter-spacing: 0.5rpx;
      }

      .button-tip {
        font-size: 24rpx;
        color: rgba(255, 255, 255, 0.75);
      }

      &.control-button--active {
        background: linear-gradient(135deg, $uni-color-primary-light 0%, #FF6B6B 100%);
        box-shadow: 0 16rpx 40rpx rgba(232, 69, 69, 0.35);

        &:active {
          box-shadow: 0 8rpx 24rpx rgba(232, 69, 69, 0.35);
        }
      }

      &.control-button--disabled {
        background: linear-gradient(135deg, #b0b0b0 0%, #909399 100%);
        box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
        cursor: not-allowed;

        &:active {
          transform: none;
          box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
        }

        &::after {
          display: none;
        }
      }
    }
  }
}

// 操作指南卡片
.guide-card {
  margin: 0 30rpx 24rpx;
  @include card-interactive(24rpx);
  overflow: hidden;

  .card-header {
    display: flex;
    align-items: center;
    gap: 12rpx;
    padding: 28rpx;
    border-bottom: 1rpx solid $uni-border-color-light;

    .header-dot {
      width: 10rpx;
      height: 10rpx;
      background: $uni-color-primary;
      border-radius: 50%;
    }

    .header-title {
      font-size: 30rpx;
      font-weight: $uni-font-weight-semibold;
      color: $uni-text-color;
      flex: 1;
    }
  }

  .guide-list {
    padding: 24rpx 28rpx;

    .guide-step {
      display: flex;
      align-items: flex-start;
      gap: 16rpx;
      margin-bottom: 20rpx;

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

      .step-number {
        width: 40rpx;
        height: 40rpx;
        border-radius: 50%;
        background: $uni-color-primary;
        color: $uni-text-color-inverse;
        font-size: 24rpx;
        font-weight: $uni-font-weight-semibold;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
        margin-top: 4rpx;
      }

      .step-text {
        flex: 1;
        font-size: 26rpx;
        color: $uni-text-color-secondary;
        line-height: 1.6;
        padding-top: 8rpx;
      }
    }
  }
}

// 余额充值卡片
.balance-card {
  margin: 0 30rpx 24rpx;
  @include card-interactive(24rpx);
  padding: 28rpx 32rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .balance-left {
    display: flex;
    align-items: center;
    gap: 16rpx;
    flex: 1;

    .balance-icon {
      width: 56rpx;
      height: 56rpx;
      border-radius: 50%;
      background: rgba($uni-color-primary, 0.08);
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .balance-info {
      display: flex;
      flex-direction: column;
      gap: 6rpx;

      .balance-label {
        font-size: 26rpx;
        color: $uni-text-color-hint;
      }

      .balance-amount {
        display: flex;
        align-items: baseline;
        gap: 4rpx;

        .amount-symbol {
          font-size: 26rpx;
          color: $uni-color-primary;
          font-weight: $uni-font-weight-medium;
        }

        .amount-number {
          font-size: 32rpx;
          color: $uni-color-primary;
          font-weight: $uni-font-weight-semibold;
        }
      }
    }
  }

  .balance-right {
    display: flex;
    align-items: center;
    gap: 8rpx;

    .recharge-text {
      font-size: 26rpx;
      color: $uni-color-primary;
      font-weight: $uni-font-weight-medium;
    }
  }
}
</style>
