import Taro, { showModal, useDidShow, useRouter } from '@tarojs/taro'
import { Button, Navigator, ScrollView, Text, View } from '@tarojs/components'
import { forwardRef, memo, useEffect, useImperativeHandle, useState } from 'react'
import './index.scss'
import Tag from '../tag'
import { MpPurchaserAddressList } from '@/api/addressList'
import { alert } from '@/common/common'
import IconFont from '@/components/iconfont/iconfont'
import { MpSaleOrderAddress } from '@/api/order'

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

// 地址列表
const AddressList = (props: Params, AddressListRef) => {
  const pages = Taro.getCurrentPages() // 获取当前的页面栈
  const prevPage = pages[pages.length - 2]

  // 焦点
  const [focusId, setFocusId] = useState()
  const { addButtonEnabled = true, focusBorderEnabled = false } = props
  const { fetchData, state } = MpPurchaserAddressList()
  // 获取数据
  const getData = async() => {
    const result = await fetchData({ purchaser_id: props.purchaser_id })
    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
      })
    }
    const itemList: any[] = []
    result?.data?.list?.forEach((item) => {
      itemList.push(item?.id)
    })
    prevPage.setData({ // 设置上一个页面的值
      ids: itemList,
    })
  }
  useDidShow(() => {
    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 router = useRouter()
  const [addressObj, setAddressObj] = useState<any>({})
  // 列表选择
  const { fetchData: selectFetch } = MpSaleOrderAddress()
  const handleSelect = async(item: any, index: number) => {
    if (router.params.orderId && router.params.orderId != '-100') {
      console.log(typeof (router.params.orderId) != 'undefined', 'router.params.orderId')
      Taro.showLoading({
        title: '请稍等...',
        mask: true,
      })
      const res = await selectFetch({ address_id: item.id, id: Number(router.params.orderId), shipment_mode: 2 })
      if (res.msg === 'success') {
        Taro.hideLoading()
        Taro.showToast({
          title: '成功',
          icon: 'success',
        })
        Taro.navigateBack({
          delta: 1,
        })
      }
      else {
        Taro.hideLoading()
        Taro.showToast({
          title: res.msg,
          icon: 'error',
        })
      }
    }
    else {
      prevPage.setData({ // 设置上一个页面的值
        addressObj: item,
        // ids: itemList
      })
      Taro.navigateBack({
        delta: 1,
      })
    }

    props.onSelect && props.onSelect(item, index)
    if (focusBorderEnabled) {
      setFocusId(item?.id)
    }
  }

  useImperativeHandle(AddressListRef, () => ({
    getData,
  }))

  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={index} onClick={() => handleSelect(item, index)} className={`address-list ${focusId == item.id && 'address-active'}`}>
                    <View className="address-container">
                      <View>
                        <View className="address-user">
                          {item.name}
                          <Text className="address-list-phone">{item.phone}</Text>
                          {
                            item.is_default
                            && <Tag type="primary" size="small" circle plain customClassName="address-list-default">
                                默认
                            </Tag>
                          }
                        </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>
                          </View>
                        </View>
                      </View>
                      <View>
                        <Navigator onClick={e => e.stopPropagation()} url={`/pages/addAddress/index?type=edit&id=${item.id}&&purchaser_id=${Number(props.purchaser_id)}`} hoverClass="none" className="address-edit">
                          <IconFont name="icon-bianji" size={40} color="#717171"></IconFont>
                        </Navigator>
                      </View>
                    </View>
                    {
                      item.factory !== '' && <>
                        <View className="line"></View>
                        <View className="bottom-font">加工厂：{item.factory}</View></>
                    }

                  </View>
                )
              })
              : <View className="address-no-data">暂未添加地址</View>
          }
        </View>
      </ScrollView>
      {addButtonEnabled && <Navigator url={`/pages/addAddress/index?type=add&purchaser_id=${Number(props.purchaser_id)}`} hoverClass="none" className="add-address">添加收货地址</Navigator>}
    </View>
  )
}

export default memo(forwardRef(AddressList))
