import { Button, Input, View } from '@tarojs/components'
import Taro, { faceVerifyForPay, useDidShow } from '@tarojs/taro'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import classnames from 'classnames'
import OrderStatusList from './components/orderStatusList'
import styles from './index.module.scss'
import ItemList from './components/itemList'
import OfflinePay from './components/offlinePay'
import PayPopup from './components/PayPopup'
import {
  GetPayCode, MpEnumSaleOrderStatus,
  MpSaleOrderCancel,
  MpShoppingCartProductColorList,
  OrderListApi,
  OrderPaymentOrderPaymentMethodInfo,
  OrderPaymentOrderPaymentSubmission,
  OrderPaymentPreCollectOrderOrderPaymentMethodInfo,
  OrderPaymentPreCollectOrderOrderPaymentSubmission,
} from '@/api/order'
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 IconFont from '@/components/iconfont/iconfont'
import { PAY_H5_CODE_URL } from '@/common/constant'

interface filterObj {
  purchaser_id?: string | number
  clientName?: string
  sale_user_id?: string | number
  saleuserName?: string
  order_no?: string | undefined
  sale_mode?: Number | undefined
  shipment_mode?: Number | undefined
}
const Order = () => {
  // 页码和页数
  const [searchField, setSearchField] = useState<{ status: number | unknown; page: number; size: number; order_no: string }>({
    status: -1,
    page: 1,
    size: 10,
    order_no: '',
  })

  // 获取订单列表
  const { fetchData: listFetchData, state: orderState } = OrderListApi()
  const [orderData, setOrderData] = useState<{ list: any[]; total: number }>({ list: [], total: 0 })
  // 筛选参数
  const [searchObj, setsearchObj] = useState<filterObj>({
    purchaser_id: '',
    clientName: '',
    sale_user_id: '',
    saleuserName: '',
    sale_mode: undefined,
    shipment_mode: undefined,
  })
  // 筛选内容展示
  const [showPopup, setshowPopup] = useState(false)
  // 上拉加载数据
  const pageNum = useRef({ size: searchField.size, page: searchField.page })
  // 列表下拉刷新
  const [refresherTriggeredStatus, setRefresherTriggeredStatus] = useState(false)
  const getOrderList = async() => {
    const res = await listFetchData({
      ...getFilterData(searchField),
      ...getFilterData(searchObj),
    })
    setOrderData(e => ({ ...e, list: res.data?.list, total: res.data?.total }))
    setshowPopup(false)
    setRefresherTriggeredStatus(() => false)
  }

  const getRefresherRefresh = async() => {
    pageNum.current.size = 1
    setRefresherTriggeredStatus(true)
    setSearchField(val => ({ ...val, size: 10 }))
  }
  // 数据加载状态
  const statusMore = useMemo(() => {
    console.log({ list: orderData.list, total: orderData.total, status: orderState.loading }, '{ list: orderData.list, total: orderData.total, status: orderState.loading }')
    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 { fetchData: orderStatusListFetchData } = MpEnumSaleOrderStatus()
  const [statusList, setStatusList] = useState<any[]>([{ id: -1, name: '全部' }])
  const getOrderStatusList = async() => {
    const res = await orderStatusListFetchData()
    setStatusList(e => [...e, ...res.data.list])
  }

  // 监听筛选条件变化
  useEffect(() => {
    if (searchField.status != null) { getOrderList() }
  }, [searchField])

  // //状态改变
  const changeStatus = useCallback((e) => {
    pageNum.current.page = 1
    setSearchField(value => ({ ...value, status: e, size: 10 }))
    setOrderData(() => ({ list: [], total: 0 }))
  }, [])

  // 输入了搜索关键字
  const getSearchData = useCallback((e) => {
    pageNum.current.page = 1
    setOrderData(() => ({ list: [], total: 0 }))
    setSearchField(val => ({ ...val, order_no: e, size: 10 }))
  }, [])
  const showSelctPopup = () => {
    setshowPopup(true)
  }
  // 关闭筛选内容展示
  const closePopup = () => {
    setshowPopup(false)
  }

  useDidShow(() => {
    // 获取选择的客户
    const pages = Taro.getCurrentPages()
    const currPage = pages[pages.length - 1] // 获取当前页面
    console.log(currPage.data, '8888')

    setsearchObj(e => ({
      ...e,
      purchaser_id: currPage.data?.clientId ? currPage.data?.clientId : '',
      clientName: currPage.data?.clientName ? currPage.data?.clientName : '',
      sale_user_id: currPage.data?.saleuserId ? currPage.data?.saleuserId : '',
      saleuserName: currPage.data?.saleuserName ? currPage.data?.saleuserName : '',
    }))
  })

  // 跳转选择客户
  const navTo = (index) => {
    if (index === 1) {
      Taro.navigateTo({
        url: `/pages/customerPage/index?clientId=${searchObj?.purchaser_id}`,
      })
    }
    else {
      Taro.navigateTo({
        url: `/pages/saleuserPage/index?saleuserId=${searchObj?.sale_user_id}`,
      })
    }
  }

  // 订单类型
  const [modeList, setModeList] = useState<any[]>([{ id: -1, 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])
    setsearchObj(e => ({ ...e, sale_mode: item.id }))
  }

  /// 发货方式类型
  const [deliveryList, setdeliveryList] = useState<any[]>([{ id: -1, name: '不限' }, { id: 1, name: '自提' }, { id: 2, name: '物流' }])
  // 选择发货方式类型
  const handCheckDelivery = (item) => {
    deliveryList.map((it) => {
      if (it.id === item.id) {
        it.checked = true
      }
      else {
        it.checked = false
      }
      return it
    })
    setdeliveryList([...deliveryList])
    setsearchObj(e => ({ ...e, shipment_mode: item.id }))
  }
  // 是否不允许确认筛选
  const isDisabled = useMemo(() => {
    if (searchObj.clientName !== ''
      || searchObj.saleuserName !== ''
      || searchObj.sale_mode !== undefined
      || searchObj.shipment_mode !== undefined
    ) {
      return false
    }
    else {
      return true
    }
  }, [searchObj])

  // 数组重置
  const resetArr = (arr) => {
    arr.map((it) => {
      it.checked = false
      return it
    })
    return arr
  }
  // 确认筛选
  const handSure = async() => {
    getOrderList()
  }
  // 重置
  const handReset = () => {
    pageNum.current.page = 1
    setsearchObj({
      purchaser_id: '',
      clientName: '',
      sale_user_id: '',
      saleuserName: '',
      sale_mode: undefined,
      shipment_mode: undefined,
    })
    setSearchField({ ...searchField, size: 10 })
    const arrOne = resetArr(modeList)
    setModeList([...arrOne])
    const arrTwo = resetArr(deliveryList)
    setdeliveryList([...arrTwo])
  }
  // 扫描
  const handScan = () => {
    Taro.scanCode({
      success(res) {
        setSearchField(val => ({ ...val, order_no: res.result }))
      },
      fail(res) {
        console.log(res)
      },
    })
  }

  useEffect(() => {
    getOrderStatusList()
  }, [])

  const { fetchData: cancelFetch } = MpSaleOrderCancel()
  // 取消订单
  const cancle = async(e, item) => {
    e.stopPropagation()
    Taro.showModal({
      content: '确定要取消吗？',
      confirmText: '确认',
      cancelText: '取消',
      async success(res) {
        if (res.confirm) {
          Taro.showLoading({
            title: '请稍等...',
            mask: true,
          })
          const res = await cancelFetch({ id: item.id })
          if (res.msg === 'success') {
            Taro.showToast({
              title: '取消成功',
            })
            Taro.hideLoading()
            getOrderList()
          }
          else {
            Taro.showToast({
              title: res.msg,
              icon: 'error',
            })
          }
        }
      },
    })
  }
  // 再次购买
  const { fetchData: buyFetch } = MpShoppingCartProductColorList()
  const nextBuy = async(e, item) => {
    e.stopPropagation()
    Taro.showLoading({
      title: '请稍等...',
      mask: true,
    })
    const arr: any = []
    item.product_list.forEach((item) => {
      item.product_colors.forEach((it) => {
        arr.push({
          length: it.length,
          roll: it.roll,
          product_color_id: it.id,
        })
      })
    })
    const query = {
      purchaser_id: item.purchaser_id,
      sale_mode: item.sale_mode,
      color_list: arr,
    }
    const res = await buyFetch(query)
    if (res.msg === 'success') {
      Taro.showToast({
        title: '加入购物车成功!',
      })
      Taro.hideLoading()
      getOrderList()
    }
    else {
      Taro.showToast({
        title: res.msg,
        icon: 'error',
      })
    }
  }
  // 去支付逻辑
  const { fetchData: infoOneFetch } = OrderPaymentOrderPaymentMethodInfo()
  const { fetchData: infoTwoFetch } = OrderPaymentPreCollectOrderOrderPaymentMethodInfo()
  const [itemObj, setItemObj] = useState<any>({})
  const [payList, setPayList] = useState<any[]>([
    {
      id: 2,
      iconfont: 'icon-yufukuan1',
      name: '预存款',
      fonts: '可用额度 ',
      money: '',
      isCheck: false,
    },
    {
      id: 5,
      iconfont: 'icon-xianxiahuizong',
      name: '货到付款',
      fonts: '发货后3天内付款',
      isCheck: false,
      money: '',
      color: '#ffffff',
    },
    {
      id: 3,
      iconfont: 'icon-xianxiahuizong',
      name: 'x天账期',
      fonts: '可用额度 ',
      money: '',
      isCheck: false,
      color: '#ffffff',
    },
    {
      iconfont: 'icon-yue',
      name: '线下汇款',
    },
    {
      iconfont: 'icon-saomiao',
      name: '扫码支付',
      color: '#ffffff',
    },
  ])

  // 显示支付
  const [showPay, setShowPay] = useState(false)

  // 显示线下汇款
  const [showOffline, setShowOffine] = useState(false)

  // 扫码支付
  const [showSide, setShowSide] = useState(true)
  const [title, setTitle] = useState('')
  const [picUrl, setPicUrl] = useState('')
  const { fetchData: payFetch } = GetPayCode()
  const handScanpay = async() => {
    const list: any = []
    itemObj.product_list.forEach((item) => {
      item.product_colors.forEach((it) => {
        list.push({
          product_code: item.code,
          product_name: item.name,
          product_color_code: it.product_color_code,
          product_color_name: it.product_color_name,
          num: it.roll.toString(),
          weight: formatWeightDiv(it.actual_weight).toString(),
          sale_price: (it.sale_price / 100).toString(),
          total_price:
            it.total_sale_price !== 0
              ? (it.total_sale_price / 100).toString()
              : (it.estimate_amount / 100).toString(),
          length: (it.length / 100).toString(),
          weight_error: formatWeightDiv(it.weight_error).toString(),
        })
      })
    })
    const query = {
      list,
      title: '面料销售电子确认单',
      show_qrcode: true,
      show_barcode: true,
      order_type: itemObj.sale_mode_name,
      shipment_mode: itemObj.shipment_mode_name,
      company: itemObj.title_purchaser_name,
      sale_user: itemObj.sale_user_name,
      order_created_time: formatDateTime(itemObj.create_time),
      order_no: itemObj.order_no,
      target_user_name: itemObj.target_user_name,
      target_address: itemObj.address_detail,
      target_description: itemObj.remark,
      pay_account: itemObj.transfer_remittance_account,
      bank_account_name: itemObj.account_name,
      bank_name: itemObj.bank_of_deposit,
      pay_type: itemObj.settle_mode_name,
      client: itemObj.purchaser_name,
      phone: itemObj.target_user_phone,
      order_total_length: (itemObj.total_number / 100).toString(),
      order_total_price: (
        itemObj.bill_total_sale_price / 100
      ).toString(),
      total_weight_error_discount: (
        itemObj.total_weight_error_discount / 100
      ).toString(),
      order_total_num: itemObj.total_number.toString(),
      qrcode: `${PAY_H5_CODE_URL}?sale_order_no=${itemObj.order_no}`,
      order_total_weight: (itemObj.total_weight / 1000).toString(),
      estimate_amount: (itemObj.estimate_amount / 100).toString(),
      total_sale_price: (itemObj.total_sale_price / 100).toString(),
      actual_amount: (itemObj.actual_amount / 100).toString(),
      wait_pay_amount: (itemObj.wait_pay_amount / 100).toString(),
      order_total_weight_error: (
        itemObj.total_weight_error / 1000
      ).toString(),
      show_sale_price: itemObj?.sale_mode == 0 && itemObj?.is_display_price ? true : !!((itemObj?.sale_mode === 1 || itemObj?.sale_mode === 2)),
      show_total_price: itemObj?.sale_mode == 0 && itemObj?.is_display_price ? true : !!((itemObj?.sale_mode === 1 || itemObj?.sale_mode === 2)),
      show_estimate_amount: itemObj?.sale_mode == 0 && itemObj?.is_display_price ? true : !!((itemObj?.sale_mode === 1 || itemObj?.sale_mode === 2)),
      show_total_sale_price: itemObj?.sale_mode == 0 && itemObj?.is_display_price ? true : !!((itemObj?.sale_mode === 1 || itemObj?.sale_mode === 2)),
      show_total_weight_error_discount: itemObj?.sale_mode == 0 && itemObj?.is_display_price ? true : !!((itemObj?.sale_mode === 1 || itemObj?.sale_mode === 2)),
      show_actual_amount: itemObj?.sale_mode == 0 && itemObj?.is_display_price ? true : !!((itemObj?.sale_mode === 1 || itemObj?.sale_mode === 2)),
      show_wait_pay_amount: itemObj?.sale_mode == 0 && itemObj?.is_display_price ? true : !!((itemObj?.sale_mode === 1 || itemObj?.sale_mode === 2)),
    }
    const res = await payFetch(query)
    if (res.data) {
      console.log(res.data.base64)
      setShowSide(false)
      setTitle('查看销售码单')
      setPicUrl(res.data.base64)
    }
  }
  // 选择支付方式
  const clickItem = (item) => {
    if (item.name === '扫码支付') { handScanpay() }
    if (item.name === '线下汇款') { setShowOffine(true) }
    payList.map((it) => {
      if (item.id === it.id) {
        it.checked = true
      }
      else {
        it.checked = false
      }
      return it
    })
    setPayList([...payList])
  }
  const toPay = async(e, item) => {
    e.stopPropagation()

    setItemObj(item)
    if (item.status !== 10) {
      const res = await infoOneFetch({ id: item.should_collect_order_id })
      payList.map((item) => {
        if (item.id === 3) {
          item.name = `${res.data.account_period}天账期`
          item.fonts = `可用额度${formatPriceDiv(
            res.data.account_period_credit_available_line,
          ).toLocaleString()}`
        }
        if (item.id === 2) {
          item.fonts = `可用额度${formatPriceDiv(
            res.data.advance_deposit_balance,
          ).toLocaleString()}`
        }
        return item
      })
      setPayList([...payList])
      if (item.is_shipper_picks_up) {
        const obj = payList.filter((item) => {
          return item.id === 6
        })
        console.log(obj, '456456')
        if (obj.length === 0) {
          payList.unshift({
            id: 6,
            iconfont: 'icon-xianxiahuizong',
            color: '#ffffff',
            name: '货主自提',
            fonts: '',
            money: '',
            isCheck: false,
          })
          setPayList([...payList])
        }
      }
    }
    else {
      const res = await infoTwoFetch({ id: item.pre_collect_order_id })
      const arr: any = []
      arr.push(
        {
          id: 2,
          iconfont: 'icon-yufukuan1',
          name: '预存款',
          fonts: `可用额度${formatPriceDiv(
            res.data.advance_deposit_balance,
          ).toLocaleString()}`,
          money: '',
          isCheck: false,
        },
        {
          iconfont: 'icon-yue',
          name: '线下汇款',
        },
        {
          iconfont: 'icon-saomiao',
          name: '扫码支付',
          color: '#ffffff',
        },

      )
      if (item.is_shipper_picks_up) {
        const obj = arr.filter((item) => {
          return item.id === 6
        })
        if (obj.length === 0) {
          arr.unshift({
            id: 6,
            iconfont: 'icon-xianxiahuizong',
            name: '货主自提',
            color: '#ffffff',
            fonts: '',
            money: '',
            isCheck: false,
          })
        }
      }
      setPayList([...arr])
    }
    setShowSide(true)
    setTitle('待支付款项')
    setShowPay(true)
  }
  // 确认交易
  const { fetchData: payOneFetch } = OrderPaymentOrderPaymentSubmission()
  const { fetchData: payTwoFetch } = OrderPaymentPreCollectOrderOrderPaymentSubmission()
  const handsurePay = (obj) => {
    let arr: any = []
    // if (obj.status !== 10) {
    arr = payList.filter((item) => {
      return item.checked
    })
    if (!arr.length) {
      Taro.showToast({
        title: '请选择后再提交',
        icon: 'error',
      })
      return false
    }

    Taro.showModal({
      content: '确定交易吗？',
      confirmText: '确认',
      cancelText: '取消',
      async success(res) {
        if (res.confirm) {
          Taro.showLoading({
            title: '请稍等...',
            mask: true,
          })
          const restult = await (obj.status !== 10 ? payOneFetch({ id: Number(obj.should_collect_order_id), payment_method: Number(arr[0]?.id) }) : payTwoFetch({ id: Number(obj.pre_collect_order_id), payment_method: Number(arr[0]?.id) }))
          if (restult?.msg === 'success') {
            Taro.showToast({
              title: '交易成功',
            })
            Taro.hideLoading()
            setShowPay(false)
            getOrderList()
          }
          else {
            Taro.showToast({
              title: restult?.msg,
              icon: 'error',
            })
          }
        }
      },
    })

    // }
  }

  return (
    <View>
      <View style={{ background: '#FFFFFF', paddingLeft: '20rpx', paddingBottom: '20rpx', position: 'sticky', top: '0', zIndex: '99' }}>
        <Search handScan={() => handScan()} defaultValue={searchField.order_no} showScan 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>
      <View style={{ background: '#FFFFFF' }}>
        <OrderStatusList list={statusList} onSelect={changeStatus} defaultId={-1} />
      </View>
      <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}
                  cancle={(e, item) => cancle(e, item)}
                  nextBuy={(e, item) => nextBuy(e, item)}
                  toPay={(e, item) => toPay(e, item)}
                ></ItemList>
              </View>
            )
          })}
        </InfiniteScroll>
        {/* <View className={styles.kongboxTwo}></View> */}
      </View>
      <Popup title="筛选订单" show={showPopup} onClose={() => closePopup()}>
        <View className={styles.popupBox}>
          <View className={styles.topBox}>
            <View className={styles.leftTop} onClick={() => navTo(1)}>
              <View className={styles.lefttopTitle}>客户信息</View>
              <View className={classnames(searchObj.clientName === '' ? styles.lefttopSelectBox : styles.activelefttopSelectBox)}>
                <View className={classnames(searchObj.clientName === '' ? styles.lefttopSelectNameactive : styles.lefttopSelectName)}>{searchObj.clientName === '' ? '请选择客户' : searchObj.clientName}</View>
                <View className={classnames('iconfont', 'icon-more', styles.icon_more)}></View>
              </View>
            </View>
            <View className={styles.leftTop} onClick={() => navTo(2)}>
              <View className={styles.lefttopTitle}>业务员</View>
              <View className={classnames(searchObj.saleuserName === '' ? styles.lefttopSelectBox : styles.activelefttopSelectBox)}>
                <View className={classnames(searchObj.saleuserName === '' ? styles.lefttopSelectNameactive : styles.lefttopSelectName)}>{searchObj.saleuserName === '' ? '请选择客户' : searchObj.saleuserName}</View>
                <View className={classnames('iconfont', 'icon-more', styles.icon_more)}></View>
              </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}>
              {deliveryList.map((item, index) => {
                return (
                  <View
                    onClick={() => {
                      handCheckDelivery(item)
                    }}
                    className={classnames(item.checked ? styles.activemodeBox : styles.modeBox)}
                    key={index}
                  >
                    {item.name}
                  </View>
                )
              })}
            </View>
          </View>
          <View>{isDisabled}</View>
          {/* <View style={{ height: '160rpx' }}></View> */}

          <View className={styles.bottomBox}>
            <Button
              className={styles.resetBox}
              onClick={() => {
                handReset()
              }}
            >
              {' '}
              重置
            </Button>
            <Button
              className={classnames(isDisabled ? styles.button : styles.activeButton)}
              disabled={isDisabled}
              onClick={() => {
                handSure?.()
              }}
            >
              {' '}
              确认
            </Button>
          </View>
          {/* <View className={styles.areaBox}></View> */}
        </View>
      </Popup>
      <PayPopup
        list={payList}
        obj={itemObj}
        showPopup={showPay}
        popupClose={() => setShowPay(false)}
        clickItem={item => clickItem(item)}
        handsurePay={obj => handsurePay(obj)}
        showSide={showSide}
        title={title}
        picUrl={picUrl}
      ></PayPopup>
      <OfflinePay show={showOffline} onClose={() => setShowOffine(false)} offlineInfo={itemObj}></OfflinePay>
    </View>
  )
}
export default Order
