import { Image, Text, View } from '@tarojs/components'
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import classnames from 'classnames'
import OrderStatusTag from '../orderStatusTag'
import styles from './index.module.scss'
import { GetSaleOrderListApi, ReturnRecordApi } from '@/api/salesAfterOrder'
import { goLink } from '@/common/common'
import { formatHashTag, formatPriceDiv } from '@/common/fotmat'
import { dataLoadingStatus, getFilterData } from '@/common/util'
import InfiniteScroll from '@/components/infiniteScroll'
import LabAndImg from '@/components/LabAndImg'
import Popup from '@/components/popup'
import { useSelector } from '@/reducers/hooks'
import { REFUND_STATUS_ORDER } from '@/common/enum'

interface Param {
  show?: true|false
  onClose?: () => void
  onSubmit?: () => void
  id?: number
}
const ReturnRecord = ({ show, onClose, onSubmit, id }: Param) => {
  // 搜索参数
  const searchField = useRef({
    page: 1,
    size: 10,
    sale_order_id: 0,
  })

  const userInfo = useSelector(state => state.userInfo)

  // 获取售后订单列表
  const { fetchData: listFetchData, state: orderState } = ReturnRecordApi()
  const [orderData, setOrderData] = useState<{ list: any[]; total: number }>({ list: [], total: 0 })
  const getOrderList = async() => {
    const res = await listFetchData(getFilterData(searchField.current))
    setOrderData({ list: res.data.list, total: res.data.total })
  }

  // 整理颜色
  const labAndRgbAndUrl = useCallback((item) => {
    return { lab: { ...item?.lab }, rgb: { ...item?.rgb }, texturl_url: item?.texturl_url }
  }, [orderData])

  const {
    ReturnApplyOrderTypeReturnForRefund, // 退货退款
  } = REFUND_STATUS_ORDER

  // 对应单价
  const standardPrice = useCallback((price, sale_mode) => {
    return `${formatPriceDiv(price).toLocaleString()}/${sale_mode == 1 ? 'm' : 'kg'}`
  }, [orderData])

  // 对应数量
  const formatCount = useCallback((item, sale_mode) => {
    return sale_mode == 0 ? `${item.roll}条` : `${Number(item.length / 100)}米`
  }, [orderData])

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

  const numText = useCallback((value) => {
    const total_number_new = value?.sale_mode == 0 ? value?.total_number : (value?.total_number / 100)
    return `${value?.total_fabrics}种面料，${value?.total_colors}种颜色，共${total_number_new}${value?.sale_mode == 0 ? '条' : '米'}`
  }, [orderData])

  // 监听滚动
  const [scrollStatus, setScrollStatus] = useState(false)
  const onscroll = useCallback((e) => {
    if (e.detail.scrollTop > 20) {
      setScrollStatus(true)
    }
    else {
      setScrollStatus(false)
    }
  }, [])
  useEffect(() => {
    if (show && id) {
      searchField.current.sale_order_id = id
      getOrderList()
    }
  }, [show, id])
  // 数据加载状态
  const statusMore = useMemo(() => {
    return dataLoadingStatus({ list: orderData.list, total: orderData.total, status: orderState.loading })
  }, [orderData, orderState])

  return (
    <>
      <Popup show={show} title="售后记录" onClose={onClose}>
        <View className={styles.returnRecord_main}>
          <InfiniteScroll
            selfonScrollToLower={getScrolltolower}
            selfOnScroll={onscroll}
            statusMore={statusMore}
          >
            <View className={styles.returnRecord_con}>
              {orderData?.list?.map(item => <View key={item.id} className={styles.order_item}>
                <View className={styles.header} onClick={() => goLink('/pages/salesAfter/index', { id: item?.id })}>
                  <View className={styles.user}>
                    <Image src={`${userInfo?.adminUserInfo?.avatar_url}`} />
                  </View>
                  <View className={styles.order_con}>
                    <Text className={styles.name}>{userInfo?.adminUserInfo?.user_name}</Text>
                    <View className={styles.order_num}>
                      <View className={styles.order_num_con}>
                        <Text className={styles.order_no}>售后单号：{item?.return_order_no}</Text>
                        <Text className={classnames(styles.miconfont, 'iconfont, icon-a-moreback')}></Text>
                      </View>
                      <OrderStatusTag status={item?.type} />
                    </View>
                  </View>
                </View>
                <View className={styles.product_con} onClick={() => goLink('/pages/salesAfter/index', { id: item?.id })}>
                  <View className={styles.product_title}>
                    <View className={styles.product_tag}>{item?.sale_mode_name}</View>
                    <View className={styles.product_name}>{formatHashTag(item?.product_list?.[0].code, item?.product_list?.[0].name)}</View>
                    <View className={styles.product_status}>{item?.stage_name}</View>
                  </View>
                  <View className={styles.product_list}>
                    <View className={styles.image}>
                      <LabAndImg value={labAndRgbAndUrl(item)} />
                      <View className={styles.color_num}>{item?.product_list?.[0].product_colors?.[0].code}</View>
                    </View>
                    <View className={styles.color_list}>
                      {item?.product_list?.[0].product_colors?.map((itemColor, index) => {
                        return (
                          (index <= 1) && <View key={itemColor.id} className={styles.color_item}>
                            <View className={styles.color_title}>{formatHashTag(itemColor.code, itemColor.name)}</View>
                            <View className={styles.color_price}>{standardPrice(itemColor.sale_price, item.sale_mode)}</View>
                            <View className={styles.color_num}>×{formatCount(itemColor, item.sale_mode)}</View>
                          </View>
                        )
                      })
                      }
                      {(item?.product_list?.[0].product_colors.length > 2) && <View className={styles.color_item}>
                        <View className={styles.color_more}>……</View>
                        <View className={styles.color_more}>……</View>
                        <View className={styles.color_more}>……</View>
                      </View>}
                    </View>
                  </View>
                  <View className={styles.color_count_num}>{numText(item)}</View>
                  <View className={styles.order_number}>
                    <Text>{item?.type == ReturnApplyOrderTypeReturnForRefund?.value ? '已申请退货' : '已申请退款'}</Text>
                    <Text>订单号：{item?.order_no}</Text>
                  </View>
                </View>
              </View>)}
            </View>
          </InfiniteScroll>
        </View>
      </Popup>
    </>
  )
}
export default memo(ReturnRecord)
