<template>
  <ay-container v-show="store.user.isLogined">
    <div class="chunk">
      <div class="center justify-between top">
        <div class="center" @click="methods.goPerson">
          <image class="personal" :src="store.user.userInfo.head_url" mode="scaleToFill" />
          <div>
            <div>{{ store.user.userInfo.user_name }}</div>
            <div class="mobile">{{ store.user.userInfo.mobileDes }}</div>
          </div>
        </div>
        <div class="text-center" @click="methods.scanCode">
          <image src="@img/icons/scan_icon.png" mode="scaleToFill" class="scan mt-spacd4" />
          <div class="p-color s-fz mt-spacd2">扫一扫</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"
          :lineWidth="4"
          :loading="store.webapi.strategy.get_user_qrcode.ing"
        >
          <div class="qrcode">
            <image
              src="@img/qr@3x.png"
              class="image"
              mode="aspectFit"
              v-if="data.hasnopayfordriver || data.qrcode.expire"
              @click="methods.getQrcode"
            />
            <image :src="data.qrcode.img" class="image" mode="aspectFit" v-else />
          </div>
        </ay-flowLine>
      </div>
      <div class="center qrcode-text">
        <template v-if="!data.firstUnload">
          <template v-if="data.hasnopayfordriver">存在未支付完成订单</template>
          <template v-else-if="data.qrcode.expire">
            二维码已失效
            <ay-refresh
              :iconSize="36"
              :loading="store.webapi.strategy.get_user_qrcode.ing"
              @refresh="methods.getQrcode"
            ></ay-refresh>
          </template>
          <template v-else>
            有效时间：
            <ay-countdown :seconds="data.qrcode.seconds" @ender="data.qrcode.expire = true" />
          </template>
        </template>
      </div>
    </div>
    <div class="flex">
      <ay-flowLine class="flex-1 mr-spac" :loading="store.webapi.strategy.get_driver_balance.ing">
        <div class="chunk m0 h-100% s-fz money-bg" @click="methods.goAccount">
          <div class="mb-spacd4">
            可用余额
            <div class="inline yellow-color ss-fz ml-spacd4" v-if="data.accountInfo.flag === 0">
              [余额不足]
            </div>
          </div>
          <ay-numer :value="data.accountInfo.showBalance" :unit="data.accountInfo.unit" />
        </div>
      </ay-flowLine>
      <ay-flowLine class="flex-1" :loading="store.webapi.strategy.get_truck_info.ing">
        <div class="chunk m0 h-100% s-fz cars" @click="methods.truckManage">
          <div>
            <div class="mb-spacd4" v-show="showcm">车辆管理</div>
            <div v-show="store.webapi.strategy.get_truck_info.firstSuccess">
              <div class="p-color mt-spac" v-if="data.truckInfo.length === 0">添加车辆</div>
              <div v-else>
                <span class="font-bold b-fz">{{ data.truckInfo.length }}</span>
                辆
              </div>
            </div>
          </div>
        </div>
      </ay-flowLine>
    </div>
    <div class="center justify-around mt-spacm2">
      <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">
      <ay-sticky :top="topHeightPX" relativeTo="#stations" targetSelector="#stationTop">
        <div
          class="center justify-between sticky"
          id="stationTop"
          :class="{ stickyed: data.station.stickyed }"
          @click="methods.hiddenDoora"
        >
          <div class="title" @click.stop="methods.hiddenDoorb">附近加气站</div>
          <div v-if="data.userLocation" @click="methods.drawerOpen">
            {{ data.station.curCity }}
            <uni-icons type="down" size="12" />
          </div>
        </div>
      </ay-sticky>
      <div v-show="data.userLocation" id="stations">
        <ay-flowLine :minLoadTime="400" :loading="store.webapi.strategy.list_mini.ing">
          <div style="height: 2rpx"></div>
        </ay-flowLine>
        <ayb-station
          v-for="(la, i) in data.station.listApp"
          :key="i"
          :stationInfo="la"
        ></ayb-station>
        <!-- <div v-if="store.webapi.strategy.list_mini.fail" class="center">
          加载失败
          <ay-refresh
            :iconSize="36"
            :loading="store.webapi.strategy.list_mini.ing"
            text="重试"
            @refresh="methods.getListApp"
          ></ay-refresh>
        </div> -->
      </div>
      <div
        class="center p-color"
        v-show="!data.firstUnload && !data.userLocation"
        @click="methods.getListApp({ activation: true })"
      >
        查看附近加气站
      </div>
    </div>
    <uni-popup ref="inputDialog" type="dialog">
      <uni-popup-dialog
        mode="input"
        title="邀请通知"
        confirmText="加入"
        cancelText="拒绝"
        :beforeClose="true"
        @confirm="methods.agree"
        @close="methods.disagree"
      >
        <div class="text-center w-100%">
          <div class="mb-spacd2 text-center">
            【{{ data.invite?.org?.orgName }}】邀请您加入成为其司机
            <span class="p-color" @click="methods.phone(data.invite?.org?.mobile)">
              <uni-icons type="phone" color="" class="mr-spacd4" size="none"></uni-icons>
              <span>{{ data.invite?.org?.mobile }}</span>
            </span>
          </div>
        </div>
      </uni-popup-dialog>
    </uni-popup>

    <ay-drawer
      ref="drawer"
      mode="right"
      :maskClick="true"
      :width="320"
      :top="topHeightPX"
      @change="methods.drawerChange"
    >
      <uni-indexed-list
        :options="data.station.cityList"
        :show-select="false"
        @click="methods.changeCity"
        ref="indexedList"
        v-if="data.station.indexedListShow"
      />
    </ay-drawer>
    <ayb-carNumber ref="carNumber" />
  </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 indexedList = ref()
const carNumber = ref()
const inputDialog = ref()
const staticData = {
  /** 选择的城市 缓存key名 */
  cctkn: 'chooseCity',
  /** 默认选择城市 */
  defCity: '全部',
  /** websocket 实例 */
  client: null,
  // entranceArgs: null as AyContainerEntryArgs,
  /** 临时记录位置信息 */
  location: { longitude: '', latitude: '' } as any,
  indexedListShowed: false,
  /** 索引组件数据监听器 */
  indexedListWatcher: null,
  /** 页面滚动距离 */
  scrollTop: 0,
}

const data = ay.initData({
  loading: false,
  /** 未load */
  firstUnload: true,
  /** 存在未支付完成订单 */
  hasnopayfordriver: true,
  invite: {} as 预添加司机详情,
  truckInfo: [] as PersonDriver对象[],
  accountInfo: {} as IAccountInfo,
  /** 用户已授权定位 */
  userLocation: false,
  /** 二维码相关 */
  qrcode: {
    /** 有效时长 m */
    seconds: 300,
    /** 二维码 */
    img: null,
    /** 已过期 */
    expire: true,
  },
  /** 菜单列表 */
  menus: [
    {
      id: 0,
      icon: perpay,
      name: '待支付订单',
    },
    {
      id: 1,
      name: '加气订单',
      icon: payhistory,
    },
    {
      id: 2,
      name: '所属物流',
      icon: firm,
    },
    {
      id: 3,
      name: '优惠卡/券',
      icon: card,
    },
  ],
  station: {
    /** 头部已吸顶 */
    stickyed: false,
    cityList: [] /** 附近加气站列表 */,
    curCity: staticData.defCity,
    listApp: [],
    indexedListShow: false,
  },
  hiddenDoor: [],
})
const topHeight = computed(() => config.common.safeAreaTopHeight)
const topHeightPX = computed(() => `${topHeight.value}px`)
const showcm = computed(() => {
  return (
    !store.webapi.strategy.get_truck_info.firstSuccess ||
    (store.webapi.strategy.get_truck_info.firstSuccess && data.truckInfo.length)
  )
})
const methods = ay.initMethods(
  {
    hiddenDoorb() {
      data.hiddenDoor[data.hiddenDoor.length - 1]++
    },
    hiddenDoora() {
      if (
        data.hiddenDoor[0] === 3 &&
        data.hiddenDoor[1] === 1 &&
        data.hiddenDoor[2] === 2 &&
        data.hiddenDoor[3] === 4
      ) {
        data.hiddenDoor = []
        uni.setClipboardData({
          data: JSON.stringify({ userInfo: store.user.userInfo }),
        })
      } else {
        data.hiddenDoor.push(0)
      }
    },
    phone(num) {
      uni.makePhoneCall({
        phoneNumber: num,
      })
    },

    getTruckInfo() {
      webapi.strategy.get_truck_info({}).then((res) => {
        data.truckInfo = aop.request.AR.truckInfo(res)
      })
    },
    truckManage() {
      if (store.common.data.mockScenes === config.common.mockScenes.examine) {
        return
      }

      if (data.truckInfo.length) {
        ay.goPage(config.pages.truckInfo_index)
      } else {
        carNumber.value.open().then((cn) => {
          if (store.webapi.strategy.bind_person_truck.ing) {
            return
          }
          webapi.strategy
            .bind_person_truck<{ userId: string }>({
              userId: store.user.userInfo.user_id,
              newCarNumber: cn,
            })
            .then((res) => {
              if (res) {
                func.native.showToast('添加成功')
                methods.getTruckInfo()
              }
            })
        })
      }
    },
    goPerson() {
      if (store.common.data.mockScenes === config.common.mockScenes.examine) {
        return
      }
      ay.goPage(config.pages.personCenter_index)
    },
    goPage(menu) {
      const maps = {
        0() {
          methods.checkNopayfordriver(1)
        },
        1() {
          ay.goPage(config.pages.order_index)
        },
        2() {
          ay.goPage(config.pages.org_index)
        },
        3() {
          ay.goPage(config.pages.cards_index)
        },
      }
      maps[menu.id]()
    },
    drawerOpen() {
      methods.getCityList()
      drawer.value.open()
      data.station.indexedListShow = true
      // 解决uni-indexed-list 组件滑动失效问题
      // 问题原因： 因为嵌套于uni-drawer内，造成uni-indexed-list的winOffsetY值获取有误
      // 解决方法：通过阅读组件源码发现uni-indexed-list在初始化时会设置winOffsetY,再给他设置正确的值。
      // 小程序于h5环境设置时机不同；
      // 组件内部：小程序仅首次渲染完毕会设置winOffsetY，h5环境每次打开组件都会重新设置winOffsetY
      // 通过监听$data.loaded的变化，重新设置winOffsetY为页面滚动距离，以及小程序环境-每次呈现组件后重新设置winOffsetY

      nextTick(() => {
        // 小程序环境-每次呈现组件后重新设置winOffsetY
        // #ifdef MP
        if (indexedList.value) {
          indexedList.value.$data.winOffsetY = staticData.scrollTop + topHeight.value
        }
        // #endif
        if (!staticData.indexedListWatcher) {
          staticData.indexedListWatcher = watch(
            () => indexedList.value?.$data.loaded,
            (nv) => {
              // 小程序环境仅首次呈现监听到， h5环境每次呈现都会监听到
              if (indexedList.value) {
                indexedList.value.$data.winOffsetY = staticData.scrollTop + topHeight.value
              }
            },
            {
              // deep: true,
            },
          )
          // 调用可释放监听
          // staticData.indexedListWatcher()
        }
      })
    },
    drawerChange(isopen) {},
    changeCity(args) {
      drawer.value.close()
      data.station.curCity = args.item.name
      uni.setStorageSync(staticData.cctkn, args.item.name)
      methods.getListApp()
    },
    goAccount() {
      ay.goPage(config.pages.account_index)
    },
    /** 初始化ws */
    initWS() {
      stompSocket
        .init(
          ay.getWebsocketUrl('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.order_prePay, { 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' }),
      )
    },
    /** 检查未支付
     * type 0:仅检查 1：点击待支付订单 2：点击扫码
     * */
    async checkNopayfordriver(type: 0 | 1 | 2 = 0) {
      const nopayfordriver = await webapi.pay.find_unpayfordriver()
      // 存在 未支付（待支付、支付中、支付异常）
      if (nopayfordriver) {
        if (type === 1) {
          if (nopayfordriver.settleStatus === 1) {
            // 跳未支付
            ay.goPage(config.pages.order_prePay, { params: { orderId: nopayfordriver.orderId } })
          }
        }
        if (type === 2) {
          func.native
            .showModal({
              title: '温馨提示',
              content: '存在未支付完成订单',
              showCancel: true,
            })
            .then((res) => {
              if (res.confirm) {
                if (nopayfordriver.settleStatus === 1) {
                  ay.goPage(config.pages.order_prePay, {
                    params: { orderId: nopayfordriver.orderId },
                  })
                } else {
                  ay.goPage(config.pages.order_orderDetail, {
                    params: { orderId: nopayfordriver.orderId },
                  })
                }
              }
            })
        }
        return true
      } else {
        if (type === 1) {
          func.native.showToast('暂无待支付订单！')
        }
        return false
      }
    },
    async scanCode() {
      if (await methods.checkNopayfordriver(2)) {
        return
      }

      const ret: { gasstationId?: string; cashierId?: string } = await func.native.scan()
      if (!(ret.gasstationId && ret.cashierId)) {
        func.native.showToast('二维码无效')
        return
      }

      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:
              price.qrcode === 2
                ? '加气站收款码已禁用，请选择收银员收款码扫码。'
                : '收银员收款码已禁用，请选择加气站收款码扫码。',
          })
        } else {
          const gasJudge = await webapi.strategy.driver_gas_judge({
            driverId: user.user.userId,
            gasstationId: ret.gasstationId,
          })
          if (gasJudge === 1) {
            // 创建订单
            ay.goPage(config.pages.order_createOrder, { params: ret })
          } else if (gasJudge === 2) {
            func.native.showModal({
              title: '温馨提示',
              content: `该加气站未及时补充平台气源，已无法通过大象平台为您提供优质气源，给您带来的不便深感其歉意，如有疑问可以与加气站沟通，亦可拨打大象加气平台客服电话："${store.common.data.phone}"`,
            })
          }
        }
      } else {
        func.native.showModal({
          title: '温馨提示',
          content: '当前收银员所属企业和二维码对应的企业不一致，请联系加气站管理员。',
        })
      }
    },
    /** 同意加入 */
    agree() {
      webapi.user.agree({ id: data.invite.driverWhiteList.id }).then((res) => {
        if (res) {
          func.native.showToast('加入成功，请重新登录').then(() => {})
          inputDialog.value.close()
        }
      })
    },
    /** 拒绝加入 */
    disagree() {
      webapi.user.disagree({ id: data.invite.driverWhiteList.id }).then((res) => {
        if (res) {
          func.native.showToast('已拒绝')
          inputDialog.value.close()
        }
      })
    },
    /** 获取邀请信息 */
    getInvite() {
      webapi.user
        .find_by_driver_mobile({ driverMobile: store.user.userInfo.mobile })
        .then((res) => {
          if (res.driverWhiteList && res.org) {
            data.invite = res
            inputDialog.value.open()
          }
        })
    },
    getCityList() {
      return webapi.strategy.city_list().then((res) => {
        res.unshift({ text: staticData.defCity, children: [{ text: staticData.defCity }] })
        data.station.cityList = res.map((m) => {
          return {
            letter: m.text,
            data: m.children.map((cm) => cm.text),
          }
        })
      })
    },
    async getListApp({
      cras = store.curPage.getDefAyContainerRefreshArgs(),
      activation = false,
      // checkScope = false,
    } = {}) {
      // 非激活 && 未授权
      if (!activation && !data.userLocation) {
        // 取消加载中效果
        ay.containerLoaded({
          reqState: enums.ReqState.cancel,
        })
        return
      }
      let location = staticData.location
      // 上拉不重新获取位置
      if (!cras.isAdd) {
        location = await func.native.getLocation(false)
        if (!location) return
        staticData.location = location
      }
      data.userLocation = true
      webapi.strategy
        .list_mini(
          {
            page: cras.page,
            size: cras.size,
            param: {
              city: data.station.curCity === staticData.defCity ? '' : data.station.curCity,
              longitude: location.longitude.toString(),
              latitude: location.latitude.toString(),
            },
          },
          // { showLoading: activation }, // || !cras.isAdd },
        )
        .then((res) => {
          if (cras.isAdd) {
            data.station.listApp.push(...res.records)
          } else {
            data.station.listApp = res.records
          }
        })
    },

    getQrcode() {
      if (data.hasnopayfordriver || store.webapi.strategy.get_user_qrcode.ing) {
        return
      }
      return webapi.strategy.get_user_qrcode({}, { minRTime: 1e3 }).then(async (res) => {
        data.qrcode.img = res
        data.qrcode.expire = false
      })
    },
  },
  {
    scanCode: { showLoading: true },
  },
)
ay.entrance(
  async (args) => {
    // staticData.entranceArgs = args
    const init = async () => {
      webapi.strategy.get_driver_balance({}).then((res) => {
        data.accountInfo = {
          ...res,
          ...aop.request.AR.getAccountInfo(res),
        }
      })

      data.hasnopayfordriver = await methods.checkNopayfordriver()
      methods.getTruckInfo()
    }
    if (args.loadType === enums.LoadType.onLoad) {
      // data.title = store.curPage?.pageConfig?.title
      // #ifdef MP
      // 用户是否授权了获取地理位置
      await uni
        .getSetting()
        .then((res) => {
          if (res.authSetting['scope.userLocation']) {
            data.userLocation = true
          }
        })
        .catch()

      // #endif
      methods.initWS()
      methods.getCityList()
      data.station.curCity = uni.getStorageSync(staticData.cctkn) || staticData.defCity
      methods.getListApp({ cras: args.cras })
      await init()
      // 无未支付订单
      if (!data.hasnopayfordriver) {
        await methods.getQrcode()
      }
      data.firstUnload = false
      // 小程序环境：时机过早会inputDialog.value为null
      // h5环境：当页面data内的值改变时，弹框会消失
      // 所有先放这里吧
      methods.getInvite()
    }

    if (args.loadType === enums.LoadType.refresh) {
      methods.getListApp({ cras: args.cras })
      // if (!args.cras.isAdd) {
      //   init()
      // }
    }
    if (args.loadType === enums.LoadType.onShow) {
      init()
    }
  },
  {
    addLoadTypes: [enums.LoadType.onShow],
  },
)

onPageScroll((res) => {
  staticData.scrollTop = res.scrollTop
})
</script>

<style lang="scss" scoped>
.center-item {
  min-height: 136rpx;
}
.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;
  }
}
.qrcode-text {
  height: $p-fz;
}
.truck {
  width: 152rpx;
  height: 116rpx;
}
#stationTop {
  padding: $p-spac 0;
}
.unit {
  margin: 0 $p-spacd2;
}
$bgc: rgba($p-color, 0.4);
.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;
  .title {
    font-size: $p-fz * 1.2;
    font-weight: bold;
  }
}
// 为了让左侧索引中文竖排
::v-deep .uni-indexed-list__menu-item {
  width: 20px;
}
::v-deep .uni-popup__info {
  @apply: font-bold;
  font-size: $bs-fz;
  color: unset;
}
.scan {
  width: 50rpx;
  height: 50rpx;
}
</style>
