import { Button, Input, ScrollView, View } from '@tarojs/components'
import Taro, { faceVerifyForPay, useDidShow } from '@tarojs/taro'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import classnames from 'classnames'
import dayjs from 'dayjs'
import styles from './index.module.scss'
import ItemList from './components/itemList'
import Tabs from './components/tabs'
import Search from '@/components/search'
import { dataLoadingStatus, getFilterData } from '@/common/util'
import Popup from '@/components/popup'
import InfiniteScroll from '@/components/infiniteScroll'
import { formatDateTime, formatHashTag, formatImgUrl, formatPriceDiv, formatWeightDiv } from '@/common/format'
import {
  MpEnumReturnStage,
  MpEnumReturnType,
  MpReturnApplyOrderList,
} from '@/api/refound'
import TimePickerPopup from '@/components/timePickerPopup'
import IconFont from '@/components/iconfont/iconfont'
import RefundCodelist from '@/components/RefundCodelist'

const RefundPage = () => {
  // 页码和页数

  const [searchField, setSearchField] = useState<
  {
    status: number | unknown
    page: number
    size: number
    name: string
    sale_mode: number | string
    stage: number | string
    return_type: number | string
    sale_start_time: number | string
    sale_end_time: number | string
  }>({
    status: 1,
    page: 1,
    size: 10,
    name: '',
    sale_mode: '不限',
    stage: '不限',
    return_type: '不限',
    sale_start_time: '',
    sale_end_time: '',
  })
  const pageNum = useRef({ size: searchField.size, page: searchField.page })

  // 获取订单列表
  const { fetchData: listFetchData, state: orderState } = MpReturnApplyOrderList()
  const [orderData, setOrderData] = useState<{ list: any[]; total: number }>({ list: [], total: 0 })

  // 输入了搜索关键字
  const getSearchData = useCallback((e) => {
    pageNum.current.page = 1
    setOrderData(() => ({ list: [], total: 0 }))
    setSearchField(val => ({ ...val, name: e, size: 10 }))
  }, [])

  // 列表下拉刷新
  const [refresherTriggeredStatus, setRefresherTriggeredStatus] = useState(false)

  // 数据加载状态
  const statusMore = useMemo(() => {
    return dataLoadingStatus({ list: orderData.list, total: orderData.total, status: orderState.loading! })
  }, [orderData, orderState])

  // 上拉加载数据
  const getScrolltolower = useCallback(() => {
    if (orderData.list.length < orderData.total) {
      pageNum.current.page++
      const size = pageNum.current.size * pageNum.current.page
      setSearchField({ ...searchField, size })
    }
  }, [orderData])

  // 顶部栏
  const [TarBarList, setTarBarList] = useState<any[]>([{ id: 1, name: '售后申请', showBorder: true }, { id: 2, name: '申请记录', showBorder: false }])
  const handChose = (item) => {
    if (item.id === searchField.status) { return }
    TarBarList.forEach((it) => {
      if (it.id === item.id) {
        it.showBorder = true
      }
      else {
        it.showBorder = false
      }
      setTarBarList([...TarBarList])
      pageNum.current.page = 1
      setOrderData(() => ({ list: [], total: 0 }))
      setSearchField(val => ({ ...val, size: 10, status: item.id }))
      // getOrderList()
    })
  }

  // 筛选内容展示
  const [showPopup, setshowPopup] = useState(false)
  const showSelctPopup = () => {
    setshowPopup(true)
  }

  // 关闭筛选内容展示
  const closePopup = () => {
    setshowPopup(false)
  }

  // 订单类型
  const [modeList, setModeList] = useState<any[]>([{ id: '', name: '不限' }, { id: 0, name: '大货' }, { id: 1, name: '剪版' }, { id: 2, name: '散剪' }])
  // 选择订单类型
  const handCheckMode = (item) => {
    modeList.map((it) => {
      if (it.id === item.id) {
        it.checked = true
      }
      else {
        it.checked = false
      }
      return it
    })
    setModeList([...modeList])
    setSearchField(e => ({ ...e, sale_mode: item.id }))
  }

  // 售后状态
  const [stageList, setStageList] = useState<any[]>([])
  const { fetchData: stageFetch } = MpEnumReturnStage()
  const getStagelist = async() => {
    const res = await stageFetch()
    if (res.data) {
      res.data.list.unshift({ id: '', name: '不限', checked: false })
      res.data.list.map((it) => {
        it.checked = false
        return it
      })
      setStageList([...res.data.list])
    }
  }

  // 选择售后状态
  const handCheckStange = (item) => {
    stageList.map((it) => {
      if (it.id === item.id) {
        it.checked = true
      }
      else {
        it.checked = false
      }
      return it
    })
    setStageList([...stageList])
    setSearchField(val => ({ ...val, stage: item.id }))
  }

  // 退款类型
  const [typeList, setTypeList] = useState<any[]>([])
  const { fetchData: typeFetch } = MpEnumReturnType()
  const getTypeList = async() => {
    const res = await typeFetch()
    if (res.data) {
      res.data.list.unshift({ id: '', name: '不限', checked: false })
      res.data.list.map((it) => {
        it.checked = false
        return it
      })
      setTypeList([...res.data.list])
    }
  }

  // 选择售后类型
  const handType = (item) => {
    typeList.map((it) => {
      if (it.id === item.id) {
        it.checked = true
      }
      else {
        it.checked = false
      }
      return it
    })
    setTypeList([...typeList])
    setSearchField(val => ({ ...val, return_type: item.id }))
  }

  // 是否不允许确认筛选
  const isDisabled = useMemo(() => {
    if (searchField.stage !== '不限'
            || searchField.sale_mode !== '不限'
            || searchField.return_type !== '不限'
            || searchField.sale_start_time !== ''
            || searchField.sale_end_time !== ''
    ) {
      return false
    }
    else {
      return true
    }
  }, [searchField])

  // 数组重置
  const resetArr = (arr) => {
    arr.map((it) => {
      it.checked = false
      return it
    })
    return arr
  }

  // 展示时间筛选
  const [showTime, setShowTime] = useState(false)
  // 关闭时间筛选
  const handClose = () => {
    setShowTime(false)
  }
  const myDate = new Date()
  const [start, setStart] = useState<any>(myDate.toLocaleDateString())
  const [end, setEnd] = useState<any>('')
  // 选择时间
  const handTime = (eq) => {
    // 直接进来点确定的时候做处理
    if (Object.keys(eq).length === 0) {
      const obj = {
        start: '',
        end: '',
      }
      obj.start = `${dayjs(new Date(`${myDate?.toLocaleDateString()} ` + '00:00:00')).format('YYYY-MM-DD')} 00:00:00`
      obj.end = `${dayjs(new Date(obj?.start)).add(1, 'day').format('YYYY-MM-DD')} 00:00:00`
      eq.value = obj
    }
    setSearchField(val => ({ ...val, sale_start_time: eq?.value?.start, sale_end_time: eq?.value?.end, size: 10 }))
    setStart(eq?.value?.start)
    setEnd(eq?.value?.end)
    setShowTime(false)
  }
  const getOrderList = async() => {
    const res = await listFetchData({
      ...searchField,
      // ...getFilterData(searchField),
      // ...getFilterData(searchObj)
    })
    setOrderData(e => ({ ...e, list: res.data?.list, total: res.data?.total }))
    // setshowPopup(false)
    setRefresherTriggeredStatus(false)
  }
  const timeArea = useMemo(() => {
    if (end !== '') {
      return `${start}   ` + '-' + `  ${end}`
    }
    else {
      return '自定义起始时间'
    }
  }, [end])
  // 重置
  const handReset = () => {
    const arrOne = resetArr(modeList)
    setModeList([...arrOne])
    const arrTwo = resetArr(typeList)
    setTypeList([...arrTwo])
    const arrThree = resetArr(stageList)
    setStageList([...arrThree])
    setSearchField(e => ({
      ...e,
      sale_mode: '不限',
      stage: '不限',
      return_type: '不限',
      sale_start_time: '',
      sale_end_time: '',
    }))
    setStart(myDate.toLocaleDateString())
    getOrderList()
    setEnd('')
  }
  const handSure = () => {
    pageNum.current.page = 1
    setSearchField(val => ({ ...val, size: 10 }))
    setshowPopup?.(false)
    getOrderList()
  }
  const getRefresherRefresh = async() => {
    pageNum.current.size = 1
    setRefresherTriggeredStatus(true)
    setSearchField(val => ({ ...val, size: 10 }))
    getOrderList()
  }
  useEffect(() => {
    setSearchField(searchField)
  }, [searchField])

  const [ShowCode, setShowCode] = useState(false)
  const [ItemInfo, setItemInfo] = useState<any>({})
  const handSee = (e, item) => {
    e.stopPropagation()
    setItemInfo(item)
    setShowCode(true)
  }
  useEffect(() => {
    getStagelist()
    getTypeList()
  }, [])
  // 监听筛选条件变化
  useEffect(() => {
    getOrderList()
  }, [searchField.size, searchField.name, searchField.status])
  return (
    <>
      <View style={{ background: '#FFFFFF', paddingLeft: '20rpx', paddingBottom: '20rpx', position: 'sticky', top: '0', zIndex: '99' }}>
        <Search placeholder="搜索商品/名称/颜色/订单号" showBtn={false} changeOnSearch={getSearchData} >
          <View className={styles.flexBox} onClick={() => showSelctPopup()}>
            <IconFont name="icon-shaixuan" size={35} color={!isDisabled ? '#0D7CFF' : ''} customClassName={styles.activeshaixuan} />
            {/* <View className={classnames('iconfont', 'icon-shaixuan', !isDisabled ? styles.icon_shaixuan : styles.activeshaixuan)}></View> */}
            <View className={classnames(isDisabled ? styles.shaixuan : styles.activeshai)}>筛选</View>
          </View>
        </Search>
      </View>
      <Tabs list={TarBarList} handChose={item => handChose?.(item)}></Tabs>
      <View className={styles.order_list}>
        <InfiniteScroll
          statusMore={statusMore}
          selfonScrollToLower={getScrolltolower}
          refresherEnabled
          refresherTriggered={refresherTriggeredStatus}
          selfOnRefresherRefresh={getRefresherRefresh}
        >
          {orderData?.list?.map((item, index) => {
            return (
              <View key={item.id} className={styles.order_item_con}>
                <ItemList
                  obj={item}
                  key={index}
                  handSee={e => handSee(e, item)}
                ></ItemList>
              </View>
            )
          })}
        </InfiniteScroll>
        <View className={styles.kongboxTwo}></View>
      </View>
      <Popup title="筛选订单" show={showPopup} onClose={() => closePopup()}>
        <View className={styles.popupBox}>
          <ScrollView className={styles.scrllStyle} scrollY>
            <View className={styles.thirdBox}>
              <View className={styles.thirdTopfont}>售后状态</View>
              <View className={styles.flexModebox}>
                {
                  stageList.map((item, index) => {
                    return (
                      <View onClick={() => { handCheckStange(item) }} className={classnames(item.checked ? styles.activemodeBox : styles.modeBox)} key={index}>{item.name}</View>
                    )
                  })
                }
              </View>
            </View>
            <View className={styles.thirdBox}>
              <View className={styles.thirdTopfont}>订单类型</View>
              <View className={styles.flexModebox}>
                {
                  modeList.map((item, index) => {
                    return (
                      <View onClick={() => { handCheckMode(item) }} className={classnames(item.checked ? styles.activemodeBox : styles.modeBox)} key={index}>{item.name}</View>
                    )
                  })
                }
              </View>
            </View>
            <View className={styles.thirdBox}>
              <View className={styles.thirdTopfont}>退款类型</View>
              <View className={styles.flexModebox}>
                {
                  typeList.map((item, index) => {
                    return (
                      <View onClick={() => { handType(item) }} className={classnames(item.checked ? styles.activemodeBox : styles.modeBox)} key={index}>{item.name}</View>
                    )
                  })
                }
              </View>
            </View>
            <View className={styles.thirdBox}>
              <View className={styles.thirdTopfont}>售后时间</View>
              <View className={styles.timeBox2} onClick={() => { setShowTime(true) }}>{timeArea}
                <View className={styles.more}>
                  {
                    timeArea == '自定义起始时间'
                                        && <IconFont name="icon-chakanquanbukehu" color="#000000" size={40} customClassName={styles.more}></IconFont>
                  }
                </View>
              </View>
            </View>
            <View className={styles.safeBox}></View>
          </ScrollView>
          <View className={styles.bottomBox}>

            <Button className={styles.resetBox} onClick={() => { handReset() }}> 重置</Button >
            <Button className={classnames(isDisabled ? styles.button2 : styles.activeButton)} disabled={isDisabled} onClick={() => handSure()}> 确认</Button >
          </View>
          {/* <View className={styles.areaBox}></View> */}
        </View>
      </Popup>
      <TimePickerPopup
        start={start}
        end={end}
        showTime={showTime}
        closePopup={handClose}
        onSelectDate={e => handTime(e)}
      ></TimePickerPopup>
      <RefundCodelist
        obj={ItemInfo}
        // picUrl={PicUrl}
        showPopup={ShowCode}
        popupClose={() => setShowCode(false)}
      ></RefundCodelist>
    </>
  )
}

export default RefundPage
