
import { Button, Navigator, ScrollView, Text, View } from '@tarojs/components'
import Taro, { showModal } from '@tarojs/taro'
import { memo, useEffect, useState } from 'react'
import './index.scss'
import { addressDeleteApi, addressListApi } from '@/api/addressManager'
import { alert } from '@/common/common'

interface Params{
  refresherEnabled?: boolean// 是否开启刷新
  onSelect?: (item: any, index: number) => void// 列表选择
  addButtonEnabled?: boolean // 是否显示添加按钮
  focusBorderEnabled?: boolean // 焦点显示蓝色边框
  id?: number // 默认选择值
}

// 地址列表
const AddressList = (props: Params) => {
  const { addButtonEnabled = true, focusBorderEnabled = false } = props
  const { fetchData, state } = addressListApi()

  // 焦点
  const [focusId, setFocusId] = useState()
  // 获取数据
  const getData = async() => {
    const result = await fetchData()
    if (props.id) {
      setFocusId(props.id as any)
    }
    else {
      result.data.list?.every((item) => {
        if (item.is_default) {
          setFocusId(item.id)
          return false
        }
        return true
      })
    }
  }
  useEffect(() => {
    getData()
    // 监听刷新
    Taro.eventCenter.on('addressList:refresh', getData)
    return () => {
      Taro.eventCenter.off('addressList:refresh', getData)
    }
  }, [])
  // 处理刷新
  const [refreshState, setRefreshState] = useState(false)
  const handleRefresh = async() => {
    setRefreshState(true)
    await getData()
    setRefreshState(false)
  }
  const data = Array.from({ length: 15 })
  // 列表选择
  const handleSelect = (item: any, index: number) => {
    props.onSelect && props.onSelect(item, index)
    if (focusBorderEnabled) {
      setFocusId(item?.id)
    }
  }
  // 删除地址
  const { fetchData: deleteFetch } = addressDeleteApi()
  const handleDelete = (item: any) => {
    showModal(({
      title: '提示',
      content: '是否删除地址？',
      async success(ev) {
        if (ev.confirm) {
          const result = await deleteFetch({ id: item.id })
          if (result.success) {
            alert.success('删除成功')
            getData()
          }
          else {
            alert.success(result.msg)
          }
        }
      },
    }))
  }

  return (
    <View className="address-scroll-view">
      <ScrollView scrollY refresherEnabled={props.refresherEnabled} enhanced refresherTriggered={refreshState} onRefresherRefresh={handleRefresh}>
        <View className="address-scroll-view-content">
          {
            state?.data?.list?.length > 0
              ? state?.data?.list?.map((item, index) => {
                // data.length>0?
                // data.map((item,index)=>{
                return (
                  <View key={item.id} onLongPress={() => handleDelete(item)} onClick={() => handleSelect(item, index)} className={`address-list ${focusId == item.id && 'address-active'}`}>
                    <View className="address-user">
                      {item.name}
                      {
                        item.is_default
                          ? <Text className="address-list-default">默认</Text>
                          : <Text className="address-list-phone">{item.phone.replace(item.phone.substring(3, 7), '****')}</Text>
                      }
                    </View>
                    <View className="address-list-bottom">
                      <View className="address-list-info">
                        <View>{item.province_name + item.city_name + item.district_name}
                          {/* {item.address_detail} */}
                        </View>
                        {
                          item.is_default && <Text className="address-list-phone">{item.phone.replace(item.phone.substring(3, 7), '****')}</Text>
                        }
                      </View>
                      <Navigator onClick={e => e.stopPropagation()} url={`/pages/addressAdd/index?type=edit&id=${item.id}`} hoverClass="none" className="address-edit">
                        <Text className="iconfont icon-bianji"></Text>
                      </Navigator>
                    </View>
                  </View>
                )
              })
              : <View className="address-no-data">暂未添加地址</View>
          }
        </View>
      </ScrollView>
      {addButtonEnabled && <Navigator url="/pages/addressAdd/index?type=add" hoverClass="none" className="add-address">添加收货地址</Navigator>}
    </View>
  )
}

export default memo(AddressList)
