<template>
  <view class="page-container">
    <scroll-view class="content-scroll" scroll-y="true">
      <!-- 设备信息卡片 -->
      <view class="device-info-card">
        <view class="device-number">
          <uv-icon name="car" size="24" color="#C6171E"></uv-icon>
          <text class="number-text">洗车机 No.{{ state.device?.shortId }}</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="control-card">
        <view class="control-wrapper">
          <view 
            class="control-button"
            :class="{ 'control-button--active': state.device?.state !== 'idle' }"
            @click="debounceStartStopDevice"
          >
            <view class="button-icon">
              <!-- 空闲状态显示播放图标 -->
              <view v-if="state.device?.state==='idle'" class="icon-play">
                <uv-icon name="play-circle-fill" size="48" color="#fff"></uv-icon>
              </view>
              <!-- 忙碌状态显示停止图标 -->
              <view v-else class="icon-stop">
                <uv-icon name="pause-circle-fill" size="48" color="#fff"></uv-icon>
              </view>
            </view>
            <text class="button-text" v-if="state.device?.state==='idle'">启动设备</text>
            <text class="button-text" v-else>停止设备</text>
            <text class="button-tip">{{ state.device?.state==='idle' ? '点击开始洗车' : '点击结束洗车' }}</text>
          </view>
        </view>
      </view>

      <!-- 操作指南卡片 -->
      <view class="guide-card">
        <view class="card-header">
          <view class="header-line"></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 {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";

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

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

const state = reactive(initState())

onHide(() => {
  Object.assign(state, initState());
})

onLoad((options: any) => {
  // uni.showModal({
  //   title:'onLoad,'+options?.shortId
  // })
  // onLoad
  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);
      state.balance = getApp<any>().globalData.user.balance
    }, 200)
  }).catch(e => {
    console.error("onLoad 校验登录失败，自动跳转登录页")
    // uni.navigateTo({
    //   url: `/pages-user/login/index?shortId=${state.deviceId}&redirectUrl=/pages-wash/device/index`
    // })
  })
});


onShow((options:any) => {
  addListener();
  // uni.showToast({
  //   title:'onShow,'
  // })
  checkLogin().then(() => {
    // uni.showToast({
    //   title:'onShow,loaded'
    // })
    if (!state.deviceId) {
      let deviceId = getApp<any>().globalData.deviceId;
      if (deviceId) {
        loadDeviceDetail(deviceId);
      }
    } else {
      loadDeviceDetail(state.deviceId);
    }
    state.isLogin =true;
    state.balance = getApp<any>().globalData.user.balance
  }).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);
      state.balance = getApp<any>().globalData.user.balance
    }
  })

  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;
    getApp<any>().globalData.deviceId = id;
  }).catch(e => {
    console.error(e)
  })
  // countTime();
}

const handleNavigateBack = () => {
  uni.navigateBack();
}

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'

          })
        }
      }
    }
  });

}

const countTime = () => {
  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 handleGotoRechage = () => {
  uni.navigateTo({
    url: `/pages-user/wallet/recharge?stationId=${state.device.stationId}`
  })
}

</script>

<style lang="scss" scoped>
.page-container {
  width: 100vw;
  height: 100vh;
  background: linear-gradient(180deg, #FFE8E8 0%, #FFF5F5 15%, $uni-bg-color-page 30%);
  display: flex;
  flex-direction: column;
}

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

// 设备信息卡片
.device-info-card {
  margin: 24rpx 30rpx;
  background: white;
  border-radius: 24rpx;
  padding: 32rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
  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: 600;
      color: #303133;
    }
  }
  
  .device-status {
    display: inline-flex;
    align-items: center;
    gap: 8rpx;
    padding: 8rpx 20rpx;
    border-radius: 20rpx;
    font-size: 24rpx;
    font-weight: 500;
    margin-bottom: 24rpx;
    
    .status-dot {
      width: 12rpx;
      height: 12rpx;
      border-radius: 50%;
      animation: pulse 2s infinite;
    }
    
    &.status-idle {
      background: #E8F8F0;
      color: #07C160;
      
      .status-dot {
        background: #07C160;
      }
    }
    
    &.status-busy {
      background: #FFF7E6;
      color: #FAAD14;
      
      .status-dot {
        background: #FAAD14;
      }
    }
    
    &.status-fault {
      background: #FEF0F0;
      color: #F56C6C;
      
      .status-dot {
        background: #F56C6C;
      }
    }
  }
  
  .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: linear-gradient(135deg, rgba(198, 23, 30, 0.08), rgba(232, 69, 69, 0.05));
      color: #C6171E;
      border-radius: 16rpx;
      font-size: 22rpx;
      font-weight: 500;
    }
  }
}

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

// 控制按钮卡片
.control-card {
  margin: 0 30rpx 24rpx;
  background: white;
  border-radius: 24rpx;
  padding: 60rpx 32rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
  
  .control-wrapper {
    display: flex;
    justify-content: center;
    align-items: center;
    
    .control-button {
      width: 240rpx;
      height: 240rpx;
      border-radius: 50%;
      background: linear-gradient(135deg, #C6171E 0%, #E84545 100%);
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      gap: 8rpx;
      box-shadow: 0 12rpx 32rpx rgba(198, 23, 30, 0.3);
      transition: all 0.15s ease;
      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.3s ease;
      }
      
      &:active {
        transform: scale(0.95);
        box-shadow: 0 6rpx 20rpx rgba(198, 23, 30, 0.3);
        
        &::before {
          transform: scale(1);
        }
      }
      
      .button-icon {
        margin-bottom: 4rpx;
        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: 32rpx;
        font-weight: 600;
        color: white;
      }
      
      .button-tip {
        font-size: 20rpx;
        color: rgba(255, 255, 255, 0.85);
      }
      
      &.control-button--active {
        background: linear-gradient(135deg, #E84545 0%, #FF6B6B 100%);
        box-shadow: 0 12rpx 32rpx rgba(232, 69, 69, 0.3);
        
        &:active {
          box-shadow: 0 6rpx 20rpx rgba(232, 69, 69, 0.3);
        }
      }
    }
  }
}

// 操作指南卡片
.guide-card {
  margin: 0 30rpx 24rpx;
  background: white;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
  overflow: hidden;
  
  .card-header {
    display: flex;
    align-items: center;
    gap: 12rpx;
    padding: 28rpx;
    border-bottom: 1rpx solid $uni-border-color-light;
    
    .header-line {
      width: 10rpx;
      height: 10rpx;
      background: $uni-color-primary;
      border-radius: 50%;
    }
    
    .header-title {
      font-size: 30rpx;
      font-weight: 600;
      color: #303133;
      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: linear-gradient(135deg, #C6171E, #E84545);
        color: white;
        font-size: 22rpx;
        font-weight: 600;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
        margin-top: 4rpx;
      }
      
      .step-text {
        flex: 1;
        font-size: 26rpx;
        color: #606266;
        line-height: 1.6;
        padding-top: 8rpx;
      }
    }
  }
}

// 余额充值卡片
.balance-card {
  margin: 0 30rpx 24rpx;
  background: white;
  border-radius: 24rpx;
  padding: 28rpx 32rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: all 0.15s ease;

  &:active {
    transform: scale(0.98);
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
  }
  
  .balance-left {
    display: flex;
    align-items: center;
    gap: 16rpx;
    flex: 1;
    
    .balance-icon {
      width: 56rpx;
      height: 56rpx;
      border-radius: 50%;
      background: linear-gradient(135deg, rgba(198, 23, 30, 0.1), rgba(232, 69, 69, 0.05));
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    .balance-info {
      display: flex;
      flex-direction: column;
      gap: 6rpx;
      
      .balance-label {
        font-size: 24rpx;
        color: #909399;
      }
      
      .balance-amount {
        display: flex;
        align-items: baseline;
        gap: 4rpx;
        
        .amount-symbol {
          font-size: 24rpx;
          color: #C6171E;
          font-weight: 500;
        }
        
        .amount-number {
          font-size: 32rpx;
          color: #C6171E;
          font-weight: 600;
        }
      }
    }
  }
  
  .balance-right {
    display: flex;
    align-items: center;
    gap: 8rpx;
    
    .recharge-text {
      font-size: 26rpx;
      color: #C6171E;
      font-weight: 500;
    }
  }
}
</style>
