import { Image, Text, Textarea, View } from '@tarojs/components'
import Taro, { useDidShow, usePullDownRefresh, useRouter } from '@tarojs/taro'
import classnames from 'classnames'
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import AddressInfoDetail from './components/addressInfoDetail'
import ApplyRecord from './components/applyRecord'
import ContentBox from './components/contentBox'
import KindList from './components/kindList'
import OrderState from './components/orderState'
import ReturnLogistics from './components/returnLogistics'
import ReturnPayCheck from './components/returnPayCheck'
import styles from './index.module.scss'
import useLogin from '@/use/useLogin'
import SearchInput from '@/components/searchInput'
import AfterOrderBtns from '@/components/afterOrderBtns'
import { formatDateTime, formatImgUrl } from '@/common/fotmat'
import { AFTER_ORDER_STATUS } from '@/common/enum'
import { SaleOrderOrderDetailApi } from '@/api/salesAfterOrder'

const OrderDes = ({ orderInfo }: { orderInfo?: any }) => {
  // 复制功能
  const clipboardData = (val) => {
    Taro.setClipboardData({
      data: val,
      success(res) {
        Taro.showToast({
          icon: 'none',
          title: '复制成功',
        })
      },
    })
  }
  return (
    <View className={styles.order_info}>
      <View className={styles.order_info_title}>订单信息</View>
      <SearchInput showBorder={false} title="售后单号" height="50rpx">
        <View className={styles.order_num}>
          <Text>{orderInfo?.return_order_no}</Text>
          <View className={styles.order_num_btn} onClick={() => clipboardData(orderInfo?.return_order_no)}>
            复制
          </View>
        </View>
      </SearchInput>
      <SearchInput showBorder={false} title="订单号" height="50rpx">
        <View className={styles.order_num}>
          <Text>{orderInfo?.order_no}</Text>
          <View className={styles.order_num_btn} onClick={() => clipboardData(orderInfo?.order_no)}>
            复制
          </View>
        </View>
      </SearchInput>
      <SearchInput showBorder={false} title="退货原因" height="50rpx">
        <Text>{orderInfo?.return_reason_name}</Text>
      </SearchInput>
      <SearchInput showBorder={false} title="退货说明" height="50rpx">
        <Text>{orderInfo?.return_explain_name}</Text>
      </SearchInput>
      <SearchInput showBorder={false} title="货物状况" height="50rpx">
        <Text>{orderInfo?.goods_status_name}</Text>
      </SearchInput>
      <SearchInput showBorder={false} title="申请时间" height="50rpx">
        <Text>{formatDateTime(orderInfo?.apply_time)}</Text>
      </SearchInput>
      <SearchInput showBorder={false} title="其它说明" height="auto">
        <Text>{orderInfo?.reason_describe}</Text>
      </SearchInput>
    </View>
  )
}
const OrderDesWithMemo = memo(OrderDes)
const AfterSalePricture = ({ urls = [] }: { urls: string[] }) => {
  const showList = useMemo(() => {
    const res = urls.map((item) => {
      return formatImgUrl(item, '!w800')
    })
    return res
  }, [urls])

  // 预览图片
  const showImage = () => {
    Taro.previewImage({
      current: showList[0], // 当前显示
      urls: showList, // 需要预览的图片http链接列表
    })
  }
  return (
    <ContentBox title="售后图片">
      <View className={styles.after_sale_picture_list}>
        {urls?.map((item, key) => (
          <View key={key} className={styles.after_sale_picture_item} onClick={showImage}>
            <Image src={formatImgUrl(item)} />
          </View>
        ))}
      </View>
    </ContentBox>
  )
}

const AfterSalePrictureWithMemo = memo(AfterSalePricture)
const SalesAfter = () => {
  useLogin()
  const router = useRouter()
  const orderId = useRef<number>(Number(router.params.id))

  // 获取订单详情
  const [orderDetail, setOrderDetail] = useState<any>() // 获取到的原始数据
  const { fetchData: saleOrderOrderDetailData } = SaleOrderOrderDetailApi()
  const getSaleOrderPreView = async() => {
    if (orderId.current) {
      const res = await saleOrderOrderDetailData({ id: orderId.current })
      setOrderDetail(res.data)
    }
    Taro.stopPullDownRefresh()
  }

  // 格式化数据格式
  const [formatDetailOrder, setFormatDetailOrder] = useState<any>() // 格式化后的数据
  const formatData = () => {
    setFormatDetailOrder({
      ...orderDetail,
      unit: orderDetail.sale_mode == 0 ? '条' : 'm', // 单位
    })
  }
  const formatPreViewOrderMemo = useMemo(() => {
    return formatDetailOrder
  }, [formatDetailOrder])

  // 页面下拉刷新
  usePullDownRefresh(() => {
    getSaleOrderPreView()
  })
  useDidShow(() => {
    getSaleOrderPreView()
  })
  // 按钮所需数据
  const orderInfo = useMemo(() => {
    return {
      ...orderDetail,
    }
  }, [orderDetail])

  // 售后订单状态枚举
  const { } = AFTER_ORDER_STATUS

  // 物流显示
  const [logisticsShow, setLogisticsShow] = useState(false)
  const [logistics, setLogistics] = useState(false)
  const onShowLogistics = useCallback((val) => {
    setLogisticsShow(true)
    if (val != 1) { setLogistics(true) }
  }, [])
  const onCloseLogistics = useCallback(() => {
    setLogisticsShow(false)
  }, [])
  // 物流成功上传
  const logisticsSuccess = useCallback(() => {
    setLogisticsShow(false)
    getSaleOrderPreView()
  }, [])

  // 显示记录
  const [applyRecord, setApplyRecord] = useState(false)

  // 显示码单
  const [returnCodeShow, setReturnCodeShow] = useState(false)
  // 获取底部按钮点击, 获取按钮状态
  const orderStateClick = useCallback(
    (val) => {
      if (val == 1 || val == 6) {
        getSaleOrderPreView()
      }
      else if (val == 8) {
        // 申请记录
        setApplyRecord(true)
      }
      else if (val == 5) {
        onShowLogistics(1)
      }
      else if (val == 7) {
        setReturnCodeShow(true)
      }
    },
    [orderDetail],
  )
  // 监听获取到的数据
  useEffect(() => {
    if (orderDetail) { formatData() }
  }, [orderDetail])
  return (
    <View className={styles.order_main}>
      <OrderState orderInfo={orderDetail} />
      <AddressInfoDetail orderInfo={orderDetail} onLogistics={onShowLogistics} />
      <KindList order={formatPreViewOrderMemo} />
      <OrderDesWithMemo orderInfo={orderDetail} />
      <AfterOrderBtns orderInfo={orderInfo} onClick={orderStateClick} />
      <AfterSalePrictureWithMemo urls={orderDetail?.fabric_piece_accessory_url} />
      <ReturnLogistics
        onlyRead={logistics}
        images={orderDetail?.accessory_url}
        descValue={orderDetail?.take_goods_remark}
        show={logisticsShow}
        id={orderDetail?.return_apply_order_id}
        onClose={onCloseLogistics}
        onSubmit={logisticsSuccess}
      />
      <ApplyRecord show={applyRecord} id={orderDetail?.id} onClose={() => setApplyRecord(false)} />
      <ReturnPayCheck orderInfo={orderDetail} show={returnCodeShow} onClose={() => setReturnCodeShow(false)} />
      <View className="common_safe_area_y"></View>
    </View>
  )
}
export default SalesAfter
