<script setup>
import {
  getElevatorUserListApi,
  postElevatorUserConcernApi
} from '@/api/elevator'
import { usePaging } from '@/composables/use-paging'

const uNotifyRef = ref(null)
const change = async (checked, item) => {
  const message = checked ? '添加成功' : '取消成功'
  const { elevatorId } = item
  const { userId } = uni.getStorageSync('userInfo')
  await postElevatorUserConcernApi({
    isConcern: checked ? 1 : 0,
    userId,
    elevatorList: [elevatorId]
  })
  uNotifyRef.value.show({
    message
  })
}

const query = ref({
  elevatorName: '',
  userId: ''
})
const { paging, dataList, queryHandler, clearHandler, enterHandler } =
  usePaging({
    apiFn: getElevatorUserListApi,
    query,
    formatResult: (rows) => {
      return rows.map((item) => {
        return {
          ...item,
          checked: item.isConcern === 1 ? true : false
        }
      })
    }
  })

const options = ref({})
onLoad(async (e) => {
  options.value = e

  const { userId } = uni.getStorageSync('userInfo')
  query.value.userId = userId
})
</script>

<template>
  <view w-full h-100vh f-s-c flex-col>
    <view f-s-c px-20 mt-12 w-full flex-none h-100>
      <up-input
        v-model="query.elevatorName"
        placeholder="请输入搜素电梯名称/地址"
        prefix-icon="search"
        prefix-icon-style="font-size: 22px;color: #909399"
        clearable
        @clear="
          () => {
            query.elevatorName = ''
            clearHandler()
          }
        "
        @confirm="enterHandler"
      />
    </view>

    <view w-full flex-auto overflow-hidden mt-8 bg-white>
      <z-paging
        ref="paging"
        v-model="dataList"
        :fixed="false"
        @query="queryHandler"
      >
        <up-cell-group>
          <up-cell
            v-for="(item, index) in dataList"
            :key="index"
            :title="item.elevatorName"
            :label="item.elevatorAddress"
          >
            <template #icon>
              <up-checkbox
                v-model:checked="item.checked"
                :name="`CHECKED_${index}`"
                used-alone
                @change="change($event, item)"
              />
            </template>
          </up-cell>
        </up-cell-group>
      </z-paging>
    </view>

    <!-- 通知提示 -->
    <up-notify ref="uNotifyRef" />
  </view>
</template>
