<template>
  <ay-container>
    <div class="chunk">
      <div class="center justify-between top">
        <div class="center" @click="methods.goPerson">
          <image
            class="personal"
            v-if="store.user.userInfo.head_url"
            :src="store.user.userInfo.head_url"
            mode="scaleToFill"
          />
          <image
            class="personal"
            v-else
            src="@img/icons/turnk_number_head.png"
            mode="scaleToFill"
          />
          <!-- <uni-icons type="contact" size="50" class="personal"></uni-icons> -->
          <div>
            <div>{{ store.user.userInfo.user_name }}</div>
            <div class="mobile">{{ store.user.userInfo.mobile }}</div>
          </div>
        </div>
        <uni-icons
          type="scan"
          color=""
          class="p-color"
          size="40"
          @click="methods.scanCode"
        ></uni-icons>
      </div>
      <div class="center">
        <ay-flowLine class="mt-spac mb-spac">
          <div class="qrcode">
            <image
              src="@img/qr@3x.png"
              class="image"
              mode="aspectFit"
              v-if="data.qrcode.expire"
              @click="methods.getQrcode"
            />
            <image :src="data.qrcode.img" class="image" mode="aspectFit" v-else />
          </div>
        </ay-flowLine>
      </div>
      <div class="center">
        <template v-if="data.qrcode.expire">
          二维码已失效
          <div class="center p-color" @click="methods.getQrcode">
            <uni-icons type="refresh" color="" size="24"></uni-icons>
            刷新
          </div>
        </template>
        <template v-else>有效时间：{{ data.qrcode.countdown }}</template>
      </div>
    </div>
    <div class="flex">
      <div class="chunk flex-1 s-fz mr-spac account" @click="methods.goAccount">
        <div class="mb-spacd4">可用余额</div>
        <div class="">
          <span class="font-bold b-fz">{{ data.accountInfo.showBalance.balance }}</span>
          <span class="font-bold">{{ data.accountInfo.showBalance.suffix }}</span>
          <span class="unit">{{ data.accountInfo.unit }}</span>
        </div>
      </div>

      <div class="chunk flex-1 center justify-start s-fz cars" @click="">
        <div class="p-color" v-if="false">添加车辆</div>
        <div v-else>
          <div class="mb-spacd4">车辆管理</div>
          <div>
            <span class="font-bold b-fz">1</span>
            辆
          </div>
        </div>
      </div>
    </div>
    <div class="center justify-around mt-spac">
      <div
        class="text-center menu"
        v-for="(m, i) in data.menus"
        :key="i"
        @click="methods.goPage(m)"
      >
        <img class="icon" :src="m.icon" />
        <div>{{ m.name }}</div>
      </div>
    </div>
    <div class="chuck list-app">
      <div class="center justify-between mb-spac">
        <div class="title">附近加气站</div>
        <div v-if="data.userLocation" @click="methods.drawerOpen">
          {{ data.station.curCity }}
          <uni-icons type="down" size="12" />
        </div>
      </div>
      <template v-if="data.userLocation">
        <ayb-station
          v-for="(la, i) in data.station.listApp"
          :key="i"
          :stationInfo="la"
        ></ayb-station>
      </template>
      <div class="center p-color" v-else @click="methods.getListApp({ first: true })">
        查看附近加气站
      </div>
    </div>

    <uni-drawer ref="drawer" mode="right" :maskClick="true" :width="320">
      <uni-indexed-list
        :options="data.station.cityList"
        :show-select="false"
        @click="methods.bindClick"
        v-if="data.station.showIndexedList"
      />
    </uni-drawer>
  </ay-container>
</template>

<script lang="ts" setup>
import stompSocket from '@/utils/api/socket/stomp'
import perpay from '@img/icons/perpay.png'
import payhistory from '@img/icons/payhistory.png'
import firm from '@img/icons/firm.png'
import card from '@img/icons/card.png'
const drawer = ref()
const staticData = {
  client: null,
  entranceArgs: null as AyContainerEntryArgs,
  location: { longitude: '', latitude: '' } as any,
}
const data = reactive({
  accountInfo: { showBalance: { balance: '', suffix: '' } } as IAccountInfo,
  /** 用户已授权定位 */
  userLocation: false,
  /** 二维码相关 */
  qrcode: {
    /** 二维码过期倒计时 */
    countdown: '',
    /** 二维码 */
    img: null,
    /** 已过期 */
    expire: false,
  },
  /** 菜单列表 */
  menus: [
    {
      id: 0,
      icon: perpay,
      name: '待支付订单',
    },
    {
      id: 1,
      name: '加气订单',
      icon: payhistory,
    },
    {
      id: 2,
      name: '所属物流',
      icon: firm,
    },
    {
      id: 3,
      name: '优惠卡/券',
      icon: card,
    },
  ],
  station: {
    /** 首次呈现，解决索引滑动失效问题 */
    showIndexedList: false,
    cityList: [] /** 附近加气站列表 */,
    curCity: '全部',
    listApp: [],
  },
})
const methods = ay.initMethods(
  {
    goPerson() {
      ay.goPage(config.pages.personCenter_index)
    },
    goPage(menu) {
      const maps = {
        0() {
          methods.goPrePay()
        },
        1() {
          ay.goPage(config.pages.orderList_index)
        },
      }
      maps[menu.id]()
    },
    drawerOpen() {
      drawer.value.open()
      data.station.showIndexedList = true
    },
    bindClick(args) {
      drawer.value.close()
      data.station.curCity = args.item.name
      methods.getListApp()
    },
    goAccount() {
      ay.goPage(config.pages.account_index)
    },
    /** 初始化ws */
    initWS() {
      stompSocket
        .init(
          'wss://dwx.auyen.com/websocket/sockjs',
          // 传参
          {
            access_token: store.user.userInfo.token,
            identifier: store.user.userInfo.Identifier,
          },
          // ws断开回调
          () => {
            methods.initWS()
          },
        )
        .then((client) => {
          staticData.client = client
          // 订阅
          const subscription = client.subscribe(
            // 路径
            '/user/' + store.user.userInfo.user_id + '/msg',
            // 接收到的数据
            (res) => {
              const body = JSON.parse(res.body)
              if (body.type === 1) {
                ay.goPage(config.pages.prePay_index, { params: JSON.parse(body.content) })
              } else if (body.type === 0) {
                const content = JSON.parse(body.content)
                uni
                  .showModal({
                    title: content.data,
                    message: content.message,
                  })
                  .then(() => {})
              }
            },
          )
        })
    },
    // 直接调用发送即可
    send() {
      staticData.client.send(
        // 路径
        '/user/' + store.user.userInfo.user_id + '/msg',
        {},
        // 发送文本
        JSON.stringify({ content: '1212' }),
      )
    },
    async goPrePay() {
      const nopayfordriver = await webapi.pay.find_unpayfordriver()
      if (nopayfordriver) {
        // 跳未支付
        ay.goPage(config.pages.prePay_index, { params: { orderId: nopayfordriver.orderId } })
        return true
      } else {
        func.native.showToast('暂无待支付订单！')
        return false
      }
    },
    async scanCode() {
      if (await methods.goPrePay()) {
        return
      }
      const reqStr = await uni
        .scanCode({
          scanType: ['qrcode'],
        })
        .catch((err) => {
          func.native.showToast('二维码无效')
          return Promise.reject(err)
        })
      let ret = { gasstationId: '', cashierId: '' }
      try {
        ret = JSON.parse(reqStr.result)
      } catch {
        func.native.showToast('二维码无效')
        return
      }
      // const ret = {
      //   cashierId: '710613333157822464',
      //   gasstationId: '710613333157822464',
      // }
      const user = await webapi.user.find_6({ userId: ret.cashierId })
      if (ret.gasstationId === user.user.orgId) {
        const price = await webapi.strategy.find_price({
          gasstationId: ret.gasstationId,
          driverId: user.user.userId,
        })
        if (
          ((price.qrcode === 0 || price.qrcode === 1) && ret.gasstationId !== ret.cashierId) || // 设置的加气站收款码
          (price.qrcode === 2 && ret.gasstationId === ret.cashierId) // 设置的收银员
        ) {
          func.native.showModal({
            title: '错误提示',
            content: '加气站收款码已禁用，请选择收银员收款码扫码。',
          })
        } else {
          const gasJudge = await webapi.strategy.driver_gas_judge({
            driverId: user.user.userId,
            gasstationId: ret.gasstationId,
          })
          if (gasJudge === 1) {
            // 创建订单
            ay.goPage(config.pages.createOrder_index, { params: ret })
          } else if (gasJudge === 2) {
            func.native.showModal({
              title: '错误提示',
              content:
                '该加气站未及时补充平台气源，已无法通过大象平台为您提供优质气源，给您带来的不便深感其歉意，如有疑问可以与加气站沟通，亦可拨打大象加气平台客服电话："400-0165388"',
            })
          }
        }
      } else {
        func.native.showModal({
          title: '错误提示',
          content: '当前收银员所属企业和二维码对应的企业不一致，请联系加气站管理员。',
        })
      }
    },
    sdfsdf() {
      webapi.strategy.get_truck_info().then((res) => {})
    },
    getCityList() {
      webapi.strategy.city_list().then((res) => {
        res.unshift({ text: '全部', children: [{ text: '全部' }] })
        data.station.cityList = res.map((m) => {
          return {
            letter: m.text,
            data: m.children.map((cm) => cm.text),
          }
        })
      })
    },
    async getListApp({ cras = config.common.defAyContainerRefreshArgs, first = false } = {}) {
      // 非首次 && 未授权
      if (!first && !data.userLocation) {
        // 取消加载中效果
        ay.containerLoaded({
          reqState: enums.ReqState.cancel,
        })
        return
      }
      let location = staticData.location
      // 上拉不重新获取位置
      if (!cras.isAdd) {
        location = await uni.getLocation()
        staticData.location = location
      }
      data.userLocation = true
      webapi.strategy
        .list_mini(
          {
            page: cras.page,
            size: cras.size,
            param: {
              city: data.station.curCity === '全部' ? '' : data.station.curCity,
              longitude: location.longitude.toString(),
              latitude: location.latitude.toString(),
            },
          },
          { showLoading: first || !cras.isAdd },
        )
        .then((res) => {
          if (cras.isAdd) {
            data.station.listApp.push(...res.records)
          } else {
            data.station.listApp = res.records
          }
        })
    },

    /** 时长处理 */
    duration(times) {
      if (times) {
        let m: number | string = Math.floor(Number(times) / 60)
        let s: number | string = Math.floor(Number(times) % 60)
        if (s < 10) {
          s = `0${s}`
        }
        if (m < 10) {
          m = `0${m}`
        }
        return `${m}:${s}`
      }
    },
    getQrcode() {
      return webapi.strategy.get_user_qrcode().then(async (res) => {
        // await func.awaiter()
        data.qrcode.img = res
        data.qrcode.expire = false
        func.timer({
          seconds: 300,
          ticker(tick) {
            data.qrcode.countdown = methods.duration(tick)
          },
          ender() {
            data.qrcode.expire = true
          },
        })
      })
    },
  },
  {
    scanCode: { showLoading: true },
  },
)
ay.entrance(
  (args) => {
    staticData.entranceArgs = args
    // webapi.strategy.getCarNumber<null, { truckId: string }>().then((res) => {
    //   webapi.strategy.getQrcode({}, { appendUrl: '/' + res.truckId }).then((resq) => {
    //     data.qrcode = resq
    //   })
    // })
    const init = async () => {
      // #ifdef MP
      await uni
        .getSetting()
        .then((res) => {
          if (res.authSetting['scope.userLocation']) {
            data.userLocation = true
          }
        })
        .catch()
      // #endif
      methods.getListApp({ cras: args.cras })
      webapi.strategy.get_driver_balance().then((res) => {
        data.accountInfo = {
          ...res,
          ...aop.request.AR.getAccountInfo(res),
        }
      })
    }
    if (args.loadType === enums.LoadType.onLoad) {
      methods.initWS()
      methods.getQrcode()
      methods.getCityList()
      init()
    }

    if (args.loadType === enums.LoadType.refresh) {
      if (args.cras.isAdd) {
        methods.getListApp({ cras: args.cras })
      } else {
        init()
      }
    }
  },
  {
    // addLoadTypes: [enums.LoadType.onLoad],
  },
)
</script>

<style lang="scss">
.top {
  padding-bottom: $p-spac;
  border-bottom: 1px dashed;
  .personal {
    width: 100rpx;
    height: 100rpx;
    margin-right: $p-spac;
    border-radius: $p-spac;
  }
  .mobile {
    margin-top: $p-spacd2;
    font-size: $s-fz;
  }
}
.qrcode {
  width: 400rpx;
  height: 400rpx;
  overflow: hidden;
  border-radius: $p-spacd2;
  .image {
    width: 480rpx;
    height: 480rpx;
    margin: -40rpx;
  }
}
.truck {
  width: 152rpx;
  height: 116rpx;
}

.unit {
  margin: 0 $p-spacd2;
}
$bgc: rgba($p-color, 0.4);
.account {
  background-color: rgba($p-price-color, 0.1);
}
.cars {
  position: relative;
  overflow: hidden;
  &::after {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    content: '';
    background-image: linear-gradient($bgc, $bgc), url('@img/truck.svg');
    background-repeat: no-repeat;
    background-position: right;
    background-size: contain;
    opacity: 0.2;
  }
}
.menu {
  font-size: $s-fz;
  .icon {
    width: 80rpx;
    height: 80rpx;
    margin-bottom: $p-spacd2;
    border-radius: 50%;
  }
}
.list-app {
  margin-top: $p-spac * 2;
  .title {
    font-size: $p-fz * 1.2;
    font-weight: bold;
  }
}
// 为了让左侧索引中文竖排
::v-deep .uni-indexed-list__menu-item {
  width: 20px;
}
</style>
