import { MovableArea, Text, View } from '@tarojs/components'
import Taro, { useDidShow, usePullDownRefresh, useRouter } from '@tarojs/taro'
import classnames from 'classnames'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import AddressInfoDetail from './components/addressInfoDetail'
import AdvanceOrderState from './components/advanceOrderState'
import ApplyRefund from './components/applyRefund'
import KindList from './components/kindList'
import MovableAreaBtn from './components/movableAreaBtn'
import OrderState from './components/orderState'
import Payment from './components/payment'
import Remark from './components/remark'
import ReturnRecord from './components/returnRecord'
import ScanPayCheck from './components/scanPayCheck'
import styles from './index.module.scss'
import useLogin from '@/use/useLogin'
import ShopCart from '@/components/shopCart'
import SearchInput from '@/components/searchInput'
import Popup from '@/components/popup'
import OrderBtns from '@/components/orderBtns'
import { formatDateTime, formatImgUrl } from '@/common/fotmat'
import { ORDER_STATUS } from '@/common/enum'
import { alert, goLink } from '@/common/common'
import { SubscriptionMessageApi } from '@/api/user'
import { AddShoppingCartApi } from '@/api/shopCart'
import { EditSaleOrderRemarkApi, GetSaleOrderDetailApi } from '@/api/order'
import MoveBtn from '@/components/moveBtn'
import { IMG_CND_Prefix } from '@/common/constant'

const Order = () => {
  useLogin()
  const [showDesc, setShowDesc] = useState(false)
  const router = useRouter()
  const orderId = useRef<number>(Number(router.params.id))

  // 订单状态枚举
  const {
    SaleOrderStatusTaking,
    SaleOrderStatusWaitingDelivery,
    SaleOrderStatusWaitingReceipt, // 待收货
    SaleOrderStatusAlreadyReceipt, // 已收货
    SaleOrderStatusComplete, // 已完成
    SaleOrderStatusRefund, // 已退款
    SaleOrderStatusCancel, // 已取消
    SaleorderstatusWaitingPrePayment, // 预付款
  } = ORDER_STATUS

  // 获取订单详情
  const firstOpen = useRef(true)
  const [orderDetail, setOrderDetail] = useState<any>() // 获取到的原始数据
  const { fetchData: getOrderFetchData } = GetSaleOrderDetailApi()
  const [orderRemark, setOrderRemark] = useState('')

  // 去付款
  const [payMentShow, setPayMentShow] = useState(false)
  const toPay = () => {
    setPayMentShow(true)
  }
  const getSaleOrderPreView = async() => {
    if (orderId.current) {
      const res = await getOrderFetchData({ id: orderId.current })
      res.data.picUrl = res.data.delivery_appendix_url?.map((item) => {
        item = IMG_CND_Prefix + item
        return item
      })
      res.data.logistics_details?.map((item) => {
        if (item.status == '待收货') {
          item.delivery_appendix_url = res.data.delivery_appendix_url?.map((item) => {
            item = IMG_CND_Prefix + item
            return item
          })
        }
        return item
      })
      setOrderDetail(res.data)
      setOrderRemark(res.data.remark)
      // 预付款自动打开支付
      if (firstOpen.current && SaleorderstatusWaitingPrePayment.value == res.data.status) {
        firstOpen.current = false
        toPay()
      }
    }
    Taro.stopPullDownRefresh()
    // Taro.hideToast()
  }

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

  // 复制功能
  const clipboardData = () => {
    Taro.setClipboardData({
      data: orderDetail?.order_no || '',
      success(res) {
        Taro.showToast({
          icon: 'none',
          title: '复制成功',
        })
      },
    })
  }

  // 初始地址数据
  const defaultAddress = useMemo(() => {
    return {
      province_name: orderDetail?.province_name,
      city_name: orderDetail?.city_name,
      district_name: orderDetail?.district_name,
      address_detail: orderDetail?.address_detail,
      target_user_name: orderDetail?.target_user_name,
      target_user_phone: orderDetail?.target_user_phone,
      shipment_mode: orderDetail?.shipment_mode,
      id: orderDetail?.id,
      sale_mode: orderDetail?.sale_mode,
      status: orderDetail?.status,
      take_goods_address: orderDetail?.take_goods_address,
      take_goods_phone: orderDetail?.take_goods_phone,
    }
  }, [orderDetail])

  // 订单备注
  const { fetchData: remarkFetchData } = EditSaleOrderRemarkApi()
  const getRemark = useCallback(async(e) => {
    setOrderRemark(() => e)
    const res = await remarkFetchData({ remark: e, id: orderId.current })
    if (res.success) {
      getSaleOrderPreView()
      alert.success('提交成功')
    }
    else {
      alert.error(res.msg)
    }
    setShowDesc(() => false)
  }, [])
  const noCanOpenDescList = useRef([
    SaleOrderStatusTaking.value, // 提货中
    SaleOrderStatusWaitingDelivery.value, // 待发货
    SaleOrderStatusWaitingReceipt.value, // 待收货
    SaleOrderStatusAlreadyReceipt.value, // 已收货
    SaleOrderStatusComplete.value, // 已完成
    SaleOrderStatusRefund.value, // 已退款
    SaleOrderStatusCancel.value, // 已取消
  ])
  const descOpen = () => {
    if (noCanOpenDescList.current.includes(orderDetail?.status)) { return alert.none('该订单状态不能修改备注') }
    setShowDesc(() => true)
  }

  // 打开地址修改
  const addressRef = useRef<any>(null)

  // 修改收货方式
  const getShipmentMode = useCallback(() => {
    getSaleOrderPreView()
  }, [orderDetail])

  // 修改地址
  const getAddress = useCallback(() => {
    getSaleOrderPreView()
  }, [orderDetail])

  // 页面下拉刷新
  usePullDownRefresh(() => {
    getSaleOrderPreView()
  })

  useDidShow(() => {
    getSaleOrderPreView()
  })
  // 关闭支付弹窗
  const closePayShow = useCallback(() => {
    setPayMentShow(() => false)
  }, [orderDetail])
  // 支付成功
  const onPaySuccess = useCallback(() => {
    alert.success('支付成功')
    getSaleOrderPreView()
    closePayShow()
  }, [orderDetail])
  // 按钮所需数据
  const orderInfo = useMemo(() => {
    return {
      orderId: orderDetail?.id,
      ...orderDetail,
    }
  }, [orderDetail])

  // 刷新页面
  const refresh = useCallback(() => {
    alert.loading('刷新中')
    getSaleOrderPreView()
  }, [orderDetail])

  // 退款申请
  const [refundShow, setRefundShow] = useState(false)
  const applyRefundClose = useCallback(() => {
    setRefundShow(false)
  }, [])
  const applyRefundSuccess = useCallback(() => {
    getSaleOrderPreView()
  }, [])

  // 查看物流
  const getLogistics = useCallback(() => {
    if (orderDetail?.delivery_appendix_url) {
      const list = orderDetail?.delivery_appendix_url?.map((item) => {
        return formatImgUrl(item, '!w800')
      })
      if (list?.length <= 0) { return alert.error('暂无图片') }
      Taro.previewImage({
        current: list[0], // 当前显示
        urls: list, // 需要预览的图片http链接列表
      })
    }
  }, [orderDetail])

  // 添加购物车
  const [showCart, setShowCart] = useState(false)
  const { fetchData: addFetchData } = AddShoppingCartApi()
  const addShopCart = async() => {
    const color_list: { product_color_id: number; roll?: number; length?: number }[] = []
    orderDetail?.product_list.forEach((pitem) => {
      pitem?.product_colors.map((citem) => {
        if (orderDetail?.sale_mode == 0) {
          return color_list.push({ product_color_id: citem.id, roll: citem.roll })
        }
        else {
          return color_list.push({ product_color_id: citem.id, length: citem.length })
        }
      })
    })
    const state = await addFetchData({
      sale_mode: orderDetail?.sale_mode,
      color_list,
    })
    if (state.success) {
      Taro.showToast({
        title: '已加入购物车',
      })
      setShowCart(true)
    }
    else {
      Taro.showToast({
        icon: 'none',
        title: state.msg,
      })
    }
  }
  // 监听获取到的数据
  useEffect(() => {
    if (orderDetail) { formatData() }
  }, [orderDetail])
  // 显示售后记录
  const [returnRecordShow, setReturnRecordShow] = useState(false)
  const onReturnRecordShow = useCallback(() => {
    setReturnRecordShow(true)
  }, [])
  const closeReturnRecord = useCallback(() => {
    setReturnRecordShow(false)
  }, [])

  // 显示
  const [showScanPayCheck, setShowScanPayCheck] = useState(false)
  // 获取底部按钮点击, 获取按钮状态
  const orderStateClick = useCallback(
    (val) => {
      if (val == 1 || val == 6 || val == 8) {
        getSaleOrderPreView()
      }
      else if (val == 2) {
        // 待付款
        toPay()
      }
      else if (val == 3) {
        // 申请退款
        if (!orderDetail?.av_return_roll) { return alert.none('该订单已申请过退款') }
        setRefundShow(true)
      }
      else if (val == 7) {
        // 再购
        addShopCart()
      }
      else if (val == 9) {
        // 售后记录
        onReturnRecordShow()
      }
      else if (val == 10) {
        setShowScanPayCheck(true)
      }
    },
    [orderDetail],
  )
  return (
    <MoveBtn orderObj={orderDetail} showList={['order']} messageTitle={orderDetail?.order_no} messagePath={`/pages/order/index?id=${orderDetail?.id}`} showCart>
      <View className={styles.order_main}>
        {(orderDetail?.status != SaleorderstatusWaitingPrePayment.value && <OrderState picUrl={orderDetail?.picUrl} orderInfo={orderDetail} />) || (
          <AdvanceOrderState orderInfo={orderDetail} onRefresh={refresh} />
        )}
        <View>
          <AddressInfoDetail
            orderInfo={defaultAddress}
            onLogistics={getLogistics}
            onSelect={getAddress}
            onChangeShipmentMode={getShipmentMode}
            ref={addressRef}
          />
        </View>
        <KindList order={formatPreViewOrderMemo} />
        <View className={styles.order_info}>
          <View className={styles.order_info_title}>订单信息</View>
          <SearchInput showBorder={false} title="单号" height="50rpx">
            <View className={styles.order_num}>
              <Text>{orderDetail?.order_no}</Text>
              <View className={styles.order_num_btn} onClick={() => clipboardData()}>
                复制
              </View>
            </View>
          </SearchInput>
          <SearchInput showBorder={false} title="下单时间" height="50rpx">
            <Text>{formatDateTime(orderDetail?.create_time)}</Text>
          </SearchInput>
          {orderDetail?.payment_time && (
            <SearchInput showBorder={false} title="付款时间" height="50rpx">
              <Text>{formatDateTime(orderDetail?.payment_time)}</Text>
            </SearchInput>
          )}
        </View>
        <View className={styles.order_desc} onClick={descOpen}>
          <View className={styles.order_desc_con}>订单备注</View>
          {(orderRemark && <View className={styles.order_desc_text}>{orderDetail?.remark}</View>) || (
            <View className={styles.order_desc_text_hint}>填写备注</View>
          )}
          <View className={classnames(styles.miconfont, 'iconfont icon-a-moreback')}></View>
        </View>
        {orderDetail?.status != SaleOrderStatusCancel.value && (
          <View className={styles.submit_order_con}>
            <OrderBtns orderInfo={orderInfo} onClick={orderStateClick} />
            <View className="common_safe_area_y"></View>
          </View>
        )}
        <Popup show={showDesc} showTitle={false} onClose={() => setShowDesc(false)}>
          <Remark onSave={e => getRemark(e)} defaultValue={orderDetail?.remark} />
        </Popup>
        <Payment onSubmitSuccess={onPaySuccess} show={payMentShow} onClose={closePayShow} orderInfo={orderDetail} />
        <ScanPayCheck show={showScanPayCheck} onClose={() => setShowScanPayCheck(false)} orderInfo={orderDetail} />
        <ApplyRefund show={refundShow} onSuccess={applyRefundSuccess} onClose={applyRefundClose} orderId={orderDetail?.id} />
        <ShopCart intoStatus="again" show={showCart} onClose={() => setShowCart(false)} />
        <ReturnRecord show={returnRecordShow} onClose={closeReturnRecord} id={orderDetail?.id} />
        <View className="common_safe_area_y"></View>
      </View>
    </MoveBtn>
  )
}
export default Order
