import type { ITouchEvent } from '@tarojs/components'
import { View } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import ItemList from './components/itemList/index'
import Search from '@/components/search'
import NormalButton from '@/components/normalButton'
import InfiniteScroll from '@/components/infiniteScroll'
import { dataLoadingStatus, debounce, getFilterData } from '@/common/util'
import FilterButton from '@/components/filterButton'
import { alert, goLink } from '@/common/common'
import Empty from '@/components/empty'
import { COLOR_CARD_LIST_EMPTY_IMAGE } from '@/common/constant'
import { CancelCutSampleOrder, GetCutSampleOrderList } from '@/api/sampleCutting'
import SelectSampleCuttingStatus from '@/components/SelectSampleCuttingStatus'

const GetSampleCutting = () => {
  const { fetchData, state } = GetCutSampleOrderList()
  const getData = async() => {
    const res = await fetchData(getFilterData(searchField))
    if (!res.success) {
      return alert.error(res.msg)
    }
    setSampleCuttingList({ list: res.data.list, total: res.data.total })
    setRefresherTriggeredStatus(false)
  }

  // status 1 申请中  2 已完成
  // 页码和页数
  const [searchField, setSearchField] = useState<{ purchaser_and_sale_user?: string; mp_cut_sample_audit_status?: number; page: number; size: number }>({
    purchaser_and_sale_user: '',
    mp_cut_sample_audit_status: 0,
    page: 1,
    size: 10,
  })
  const [sampleCuttingList, setSampleCuttingList] = useState<{ list: any[]; total: number }>({ list: [], total: 0 })

  // 列表下拉刷新
  const [refresherTriggeredStatus, setRefresherTriggeredStatus] = useState(false)
  // 数据加载状态
  const statusMore = useMemo(() => {
    return dataLoadingStatus({ list: sampleCuttingList.list, total: sampleCuttingList.total, status: state.loading! })
  }, [sampleCuttingList, state.loading])
  // 筛选参数
  // 上拉加载数据
  const pageNum = useRef({ size: searchField.size, page: searchField.page })

  const getRefresherRefresh = async() => {
    pageNum.current.size = 1
    setRefresherTriggeredStatus(true)
    setSearchField(val => ({ ...val, size: 10 }))
  }
  const getScrollToLower = useCallback(() => {
    if (sampleCuttingList.list.length < sampleCuttingList.total) {
      pageNum.current.page++
      const size = pageNum.current.size * pageNum.current.page
      setSearchField({ ...searchField, size })
    }
  }, [sampleCuttingList])

  // 领取剪样
  const getSampleCutting = () => {
    goLink('/pages/sampleCutting/sampleCuttingList/index')
  }

  // 搜索
  const getSearchData = debounce((value: string) => {
    setSearchField(e => ({ ...e, purchaser_and_sale_user: value }))
  }, 300)

  const FilterOptions = [
    {
      key: 0,
      label: '全部记录',
    },
    {
      key: 5,
      label: '申请中',
    },
    {
      key: 6,
      label: '已完成',
    },
  ]

  const handleClickFilter = (value) => {
    if (searchField.mp_cut_sample_audit_status === value) { return }
    setSearchField(e => ({ ...e, mp_cut_sample_audit_status: value }))
  }

  useEffect(() => {
    getData()
  }, [searchField])

  const { fetchData: cancelOrderApi } = CancelCutSampleOrder()

  const cancelOrder = async(id: number) => {
    const res = await cancelOrderApi({ id })
    if (res.success) {
      getData()
    }
  }

  // 取消订单
  const handleCancel = (e: ITouchEvent, id: number) => {
    e.stopPropagation()
    Taro.showModal({
      content: '确定取消该订单？',
      confirmColor: '#337fff',
      confirmText: '确认',
      success: (res) => {
        if (res.confirm) {
          cancelOrder(id)
          console.log('用户点击确定')
        }
      },
    })
  }

  // 监听选择的类型
  // useEffect(() => {
  //   setSearchObj(search)
  //   if (search.goodsId) { getGoodList() }
  // }, [search])

  return <View className={styles.main}>
    <View className={styles.search}>
      <Search placeholder="请输入客户或业务员" showBtn={false} changeOnSearch={getSearchData} />
    </View>
    <SelectSampleCuttingStatus onChange={handleClickFilter} />
    <View className={styles.color_card_list}>
      <InfiniteScroll
        emptySlot={<Empty picUrl={COLOR_CARD_LIST_EMPTY_IMAGE} text="还没有领取过剪样" />}
        statusMore={statusMore}
        selfonScrollToLower={getScrollToLower}
        refresherEnabled
        refresherTriggered={refresherTriggeredStatus}
        selfOnRefresherRefresh={getRefresherRefresh}
        safeAreaInsetBottom={false}
      >
        {sampleCuttingList?.list?.map((item, index) => {
          return (
            <View key={item.order_id} className={styles.order_item}>
              <ItemList data={item} key={index} cancel={e => handleCancel(e, item.order_id)}></ItemList>
            </View>
          )
        })}
      </InfiniteScroll>
    </View>
    <View className={styles.bottomBar}>
      <NormalButton
        customClassName={styles.bottomBar__button}
        type="primary"
        round
        onClick={getSampleCutting}
      >
          领取剪样
      </NormalButton>
    </View>
  </View>
}

export default GetSampleCutting
