import { Text, View } from '@tarojs/components'
import Taro from '@tarojs/taro'
import classnames from 'classnames'
import { forwardRef, memo, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { GetAddressListApi } from '@/api/addressList'
import { addressListApi } from '@/api/addressManager'
import { EditSaleOrderAddressApi, EditSaleOrderShipmentModeApi } from '@/api/order'
import { alert, goLink } from '@/common/common'
import { ORDER_STATUS } from '@/common/enum'
import { debounce, throttle } from '@/common/util'
import AddressList from '@/components/AddressList'
import Popup from '@/components/popup'

interface Param {
  onSelect?: (val: any) => void // 选择地址
  disabled?: false | true // true禁用后只用于展示
  onChangeShipmentMode?: (val: number) => void // 返回收货方式
  onLogistics?: () => void // 查看物流
  status?: 1 | 2 // 1确认订单时使用， 2订单流程
  orderInfo?: {
    id?: number // 订单id
    shipment_mode?: 1 | 2 // 1自提 2物流
    status?: number // 订单状态
    province_name: string
    city_name: string
    district_name: string
    address_detail: string
    take_goods_address: string
    take_goods_phone: string
    target_user_name: string
    target_user_phone: string
  }
}

// 订单状态
const {
  SaleorderstatusWaitingPrePayment,
  SaleOrderStatusBooking,
  SaleOrderStatusArranging,
  SaleOrderStatusArranged,
  SaleOrderStatusWaitingPayment,
  SaleOrderStatusWaitingReceipt,
  SaleOrderStatusAlreadyReceipt,
  SaleOrderStatusComplete,
  SaleOrderStatusRefund,
  SaleOrderStatusCancel,
} = ORDER_STATUS
const AddressInfoDetail = ({ onSelect, onChangeShipmentMode, orderInfo, status = 2, disabled = false, onLogistics }: Param, ref) => {
  const [addressInfo, setAddressInfo] = useState<any>()
  const { fetchData: addressFetchData } = EditSaleOrderAddressApi()

  // 打开地址列表
  const [showAddressList, setShowAddressList] = useState(false)

  // 收货方法,1:自提，2物流
  const [receivingStatus, setReceivingStatus] = useState(2)

  // 当没有地址时获取地址列表中的第一个数据
  const { fetchData: addressListFetchData } = addressListApi()
  const getAddressListOne = async() => {
    if (orderInfo?.address_detail) { return true }
    const res = await addressListFetchData()
    if (res.data.list && res.data.list?.length > 0) {
      const info = res.data.list[0]
      await addressFetchData({ id: orderInfo?.id, address_id: info.id })
      setAddressInfo(e => ({ ...e, ...info, target_user_name: info.name, target_user_phone: info.phone }))
      return true
    }
    else {
      Taro.showModal({
        content: '您还没有地址，请前去新增地址',
        success(res) {
          if (res.confirm) {
            goLink('/pages/addressManager/index')
          }
          else if (res.cancel) {
            console.log('用户点击取消')
          }
        },
      })
      return false
    }
  }
  const { fetchData: shipmentModeFetchData } = EditSaleOrderShipmentModeApi()

  const changeReceivingStatus = debounce(async(value) => {
    if (!orderInfo || value == receivingStatus) { return false }
    if (status == 1) {
      onChangeShipmentMode?.(value)
      setReceivingStatus(value)
      return false
    }
    if (value == 2) {
      const res = await getAddressListOne()
      if (!res) { return false }
    }
    alert.loading('正在修改')
    const res = await shipmentModeFetchData({ id: orderInfo.id, shipment_mode: value })
    if (res.success) {
      alert.success('收货方式修改成功')
      onChangeShipmentMode?.(value)
      setReceivingStatus(() => value)
    }
    else {
      alert.none(res.msg)
    }
  }, 300)

  // 修改地址
  const [addressId, setAddressId] = useState(0)
  const getAddress = async(value) => {
    if (!orderInfo) { return false }
    if (status == 1) {
      setShowAddressList(() => false)
      setAddressId(value.id)
      setAddressInfo(e => ({ ...e, ...value, target_user_name: value.name, target_user_phone: value.phone }))
      onSelect?.(value)
      return false
    }
    alert.loading('正在修改')
    const res = await addressFetchData({ id: orderInfo.id, address_id: value.id })
    if (res.success) {
      alert.success('地址修改成功')
      onSelect?.(value)
      setShowAddressList(() => false)
      setAddressId(value.id)
      setAddressInfo(e => ({ ...e, ...value, target_user_name: value.name, target_user_phone: value.phone }))
    }
    else {
      alert.none(res.msg)
    }
  }

  // 根据订单状态判断是否可修改
  const limitEdit = () => {
    const res = [
      SaleorderstatusWaitingPrePayment.value,
      SaleOrderStatusBooking.value,
      SaleOrderStatusArranging.value,
      SaleOrderStatusArranged.value,
      SaleOrderStatusWaitingPayment.value,
    ].includes(orderInfo?.status as number)
    if (!res && status != 1) { alert.none('该订单状态不能修改地址！') }
    return status == 1 ? true : res
  }
  const onReceivingStatus = async(value, e) => {
    e.stopPropagation()
    if (limitEdit()) { changeReceivingStatus(value) }
  }
  // 根据订单状态判断是否显示物流
  const logisticsShowList = [
    SaleOrderStatusWaitingReceipt.value,
    SaleOrderStatusAlreadyReceipt.value,
    SaleOrderStatusComplete.value,
    SaleOrderStatusRefund.value,
  ]
  const logisticsShow = useMemo(() => {
    return logisticsShowList.includes(orderInfo?.status as number)
  }, [orderInfo])
  const changeShow = () => {
    if (receivingStatus == 2 && !logisticsShow && limitEdit()) { setShowAddressList(() => true) }
  }
  // 地址格式
  const formatAddress = useMemo(() => {
    if (receivingStatus == 2) {
      return addressInfo?.address_detail ? addressInfo.province_name + addressInfo.city_name + addressInfo.district_name + addressInfo.address_detail : ''
    }
    else {
      return addressInfo?.take_goods_address
    }
  }, [receivingStatus, addressInfo])
  useEffect(() => {
    if (orderInfo) {
      setReceivingStatus(() => orderInfo.shipment_mode || 2)
      setAddressInfo(() => orderInfo)
    }
  }, [orderInfo])
  // 把内部方法提供给外部
  useImperativeHandle(ref, () => ({
    changeShow,
  }))
  return (
    <View>
      <View className={styles.order_address} onClick={() => changeShow()}>
        <View className={classnames(styles.order_address_icon, 'iconfont', receivingStatus == 2 ? 'icon-daohang' : 'icon-fahuo')}></View>
        <View className={styles.order_address_text_con}>
          <View className={styles.order_address_text_title}>
            <Text className={classnames(styles.address_text, styles.address_text_no)}>{formatAddress || '请选择收货地址及信息'}</Text>
            {receivingStatus == 2 && !logisticsShow && <Text className={classnames(styles.moreIconfont, 'iconfont icon-a-moreback')}></Text>}
          </View>
          <View className={styles.order_address_text_name}>
            <Text>{receivingStatus == 1 ? '谭先生' : addressInfo?.target_user_name}</Text>
            <Text>{receivingStatus == 1 ? addressInfo?.take_goods_phone : addressInfo?.target_user_phone}</Text>
          </View>
        </View>
        {(!logisticsShow && (
          <View className={styles.updateBtn}>
            <View className={styles.updateBtn_list}>
              <View
                className={classnames(styles.updateBtn_item, receivingStatus == 1 && styles.updateBtn_item_select)}
                onClick={e => onReceivingStatus(1, e)}
              >
                  自提
              </View>
              <View
                className={classnames(styles.updateBtn_item, receivingStatus == 2 && styles.updateBtn_item_select)}
                onClick={e => onReceivingStatus(2, e)}
              >
                  物流
              </View>
            </View>
            <View style={{ transform: receivingStatus == 1 ? 'translateX(0)' : 'translateX(100%)' }} className={classnames(styles.updateBtn_select)}></View>
          </View>
        ))
            || (orderInfo?.status != SaleOrderStatusRefund.value && (
              <View className={styles.logisticsBtn} onClick={onLogistics}>
                查看物流
              </View>
            ))}
      </View>
      <Popup show={showAddressList} showTitle={false} onClose={() => setShowAddressList(false)}>
        <View className={styles.order_address_list}>
          <View className={styles.order_address_title}>请选择收货地址</View>
          <View className={styles.addressList_con}>
            <AddressList onSelect={getAddress} id={addressId} />
          </View>
        </View>
      </Popup>
    </View>
  )
}
export default memo(
  forwardRef(AddressInfoDetail),
)
