<template>
  <view class="uni-app">
    <view class="status-bar" />
    <view class="main-container">
      <wk-nav-bar title="附近的客户" />

      <view class="list-view">
        <view class="list-wrapper">
          <view class="filter-group">
            <wk-base-filter :tabs="options" @filter="handleFilter" />
          </view>

          <wk-scroll-view
            :status="listStatus"
            class="list-scroll"
            @refresh="getList({}, true)">
            <nearby-customer-item
              v-for="(item, index) in listData"
              :key="item.customerId"
              :index="index"
              :item-data="item" />
          </wk-scroll-view>
        </view>
      </view>
    </view>

    <uni-popup ref="popup" type="dialog">
      <uni-popup-dialog
        v-model="userRadius"
        :check-func="inputCheckFunc"
        required-text="请输入数字"
        title="自定义距离(千米)"
        placeholder="'请输入距离'"
        mode="input"
        @confirm="handleDialogConfirm" />
    </uni-popup>
  </view>
</template>

<script>
  import { NearbyCustomer } from 'API/crm/customer'
  import { AdminQueryUserList } from 'API/admin'

  import NearbyCustomerItem from './components/nearbyCustomerItem'
  // import NearbyMap from './components/nearbyMap.vue'

  import { mapGetters } from 'vuex'
  import {
    bMapTransQQMap,
    qqMapTransBMap,
    getLocation
  } from '@/utils/map.js'

  export default {
    name: 'NearbyCustomerIndex',
    components: {
      // OptionsFilter,
      NearbyCustomerItem
    },
    data() {
      return {
        GetListFn: NearbyCustomer, // 获取列表数据接口

        options: [
          {
            label: '距离',
            field: 'radius',
            value: 3000,
            valueData: 1,
            options: [
              {label: '1公里以内', value: 1000},
              {label: '3公里以内', value: 3 * 1000},
              {label: '5公里以内', value: 5 * 1000},
              {label: '10公里以内', value: 10 * 1000},
              {label: '20公里以内', value: 20 * 1000},
              {label: '30公里以内', value: 30 * 1000},
              {label: '50公里以内', value: 50 * 1000},
              {label: '自定义', value: '__defined__'},
            ]
          },
          // {
          //   label: '负责人',
          //   field: 'ownerUserId',
          //   options: []
          // },
          {
            label: '所属模块',
            field: 'type',
            value: '',
            valueData: 0,
            options: [
              {label: '全部', value: ''},
              {label: '客户', value: 2},
              {label: '公海', value: 9}
            ]
          },
        ],

        filterData: {
          radius: 3000,
          type: ''
        },
        userRadius: 3,
        listData: [],
        listStatus: 'noMore',

        devicePoint: {
        // lat: 34.762279,
        // lng: 113.77765
        }
      }
    },
    computed: {
    ...mapGetters({
      userInfo: 'user/userInfo'
    })
    },
    onBackPress(evt) {
      if (this.showMap) {
        this.showMap = !this.showMap
        return true // 返回值为 true 时，表示不执行默认的返回
      }
      return false
    },
    mounted() {
      // this.getUserList()
      // this.getLocation()

      // this.devicePoint = {
      //   latitude: 34.762279,
      // 	longitude: 113.77765
      // }
      // this.getList()

      // #ifdef MP-WEIXIN
      this.getUserLocationAuth()
      // #endif
      // #ifndef MP-WEIXIN
      this.getLocation()
    // #endif
    },
    methods: {
      getUserList() {
        AdminQueryUserList({
          pageType: 0
        }).then(res => {
          this.options[1].options = res.list.map(item => {
            return {
              label: item.realname,
              value: item.userId
            }
          })
          this.$set(this.options, 1, this.options[1])
        }).catch()
      },

      getUserLocationAuth() {
        const that = this
        uni.getSetting({
          success: (data) => {
            console.log('setting: ', data)
            const flag = data.authSetting['scope.userLocation']
            if (!flag) {
              uni.authorize({
                scope: 'scope.userLocation',
                success: () => {
                  that.getLocation()
                },
                fail: () => {
                  that.$toast('定位失败')
                }
              })
            } else {
              that.getLocation()
            }
          },
          fail: () => {
            that.$toast('定位失败')
          }
        })
      },

      getLocation() {
        getLocation(false).then(res => {
          this.devicePoint = qqMapTransBMap(res.longitude, res.latitude)
          this.getList()
        }).then().catch(() => {
          this.$toast('定位失败')
        })
      },

      /**
       * 获取附近的客户
       */
      getList() {
        if (this.listStatus === 'loading') return
        this.showMap = false
        if (!this.devicePoint.longitude || !this.devicePoint.latitude) {
          this.$toast('定位失败')
          return
        }
        this.listStatus = 'loading'
        NearbyCustomer({
          lng: this.devicePoint.longitude,
          lat: this.devicePoint.latitude,
          type: this.filterData.type || '',
          radius: this.filterData.radius === '__defined__' ? Number((this.userRadius * 1000).toFixed()) : this.filterData.radius,
          ownerUserId: this.filterData.ownerUserId || ''
        }).then(res => {
          console.log('NearbyCustomer list:', res)
          this.listData = res || []
          this.listStatus = 'noMore'
        }).catch(() => {
          this.listStatus = 'noMore'
        })
      },

      handleDropdownChange(index) {
        // 记录点击的是第几个tab
        this.activeTabIndex = index
      },
      handleFilter(item) {
        console.log('item: ', item)
        this.filterData[item.field] = item.value
        if (item.field === 'radius' && item.value === '__defined__') {
          // delete this.filterData.status

          this.$refs.popup.open()
        } else {
          this.getList()
        }
      },
      inputCheckFunc(val) {
        return !isNaN(Number(val))
      },
      handleDialogConfirm(next, val) {
        this.userRadius = val
        this.getList()
        next()
      },

      handleToSearch() {},

      handleToggleMap() {
        this.showMap = !this.showMap
      }
    }
  }
</script>

<style scoped lang="scss">
	.main-container {
		display: flex;
		flex-direction: column;
		// padding-bottom: $tabbar-height;
		overflow-y: hidden;

		.search-btn {
			margin-right: 28rpx;
			.icon {
				font-weight: 400;
				font-size: 40rpx;
				color: white;
			}
		}

		.img-icon__map {
			width: 44rpx;
			height: 44rpx;
			vertical-align: middle;
		}

		.list-view {
			flex: 1;
			overflow-y: hidden;

			.list-wrapper {
				width: 100%;
				height: 100%;
				display: flex;
				flex-direction: column;
				overflow: hidden;

				.list-scroll {
					flex: 1;
					overflow: hidden;
				}
			}
		}

		.map-view {
			flex: 1;
			overflow: hidden;
		}
	}
</style>
