
import { Button, Navigator, ScrollView, Text, View } from '@tarojs/components'
import Taro, { getCurrentPages, showModal } from '@tarojs/taro'
import { memo, useEffect, useState } from 'react'
import CompanyItem from './components/companyItem'
import { weightDeleteApi, weightListApi } from '@/api/weightList'
import './index.scss'
import { alert } from '@/common/common'

const weightListManager = () => {
  return (
    <View className="weight-list-manager">
      <WeightList />
    </View>
  )
}
interface Params{
  refresherEnabled?: boolean// 是否开启刷新

}
// 码单列表
const WeightList = (props: Params) => {
  const { fetchData, state } = weightListApi()
  const getData = () => {
    fetchData()
  }
  useEffect(() => {
    Taro.eventCenter.on('weightList:refresh', getData)
    getData()
    return () => {
      Taro.eventCenter.off('weightList:refresh', getData)
    }
  }, [])
  // 处理刷新
  const [refreshState, setRefreshState] = useState(false)
  const handleRefresh = async() => {
    setRefreshState(true)
    await fetchData()
    setRefreshState(false)
  }
  const data = Array.from({ length: 0 })
  // 删除码单
  const { fetchData: deleteFetch } = weightDeleteApi()
  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)
          }
        }
      },
    }))
  }
  const onSelect = (item) => {
    const pages = getCurrentPages()
    const current = pages[pages.length - 1]
    const eventChannel = current.getOpenerEventChannel()
    eventChannel.emit('getSelectCompanyEvent', item)
    Taro.navigateBack()
  }

  return (
    <View className="weight-list-scroll-view">
      <ScrollView scrollY refresherEnabled enhanced refresherTriggered={refreshState} onRefresherRefresh={handleRefresh}>
        {
          state?.data?.list?.length > 0
            ? state?.data?.list?.map((item) => {
              return (
                <View key={item.id} className="weight-list-con" >
                  <CompanyItem value={item} onClick={onSelect} />
                </View>
              )
            })
            : <View className="weight-list-no-data">
              <View>您末添加任何码单信息</View>
            正在使用平台默认码单信息
            </View>
        }
      </ScrollView>
      <Navigator url="/pages/weightListAdd/index?type=add" hoverClass="none" className="add-weight-list">新建抬头</Navigator>
    </View>
  )
}

export default weightListManager
