import { View } from '@tarojs/components'
import Taro, { useDidShow, usePullDownRefresh } from '@tarojs/taro'
import classnames from 'classnames'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import KindList from './components/kindList'
import Remark from './components/remark'
import styles from './comfirm.module.scss'
import SubmitOrderBtn from './components/submitOrderBtn'
import AddressInfoDetail from './components/addressInfoDetail'
import { getParam } from '@/common/system'
import { alert, goLink } from '@/common/common'
import Popup from '@/components/popup'
import { formatPriceDiv } from '@/common/fotmat'
import { SaleOrderApi, SaleOrderPreViewApi } from '@/api/order'
import { SubscriptionMessageApi } from '@/api/user'
import { SUBSCRIPTION_MESSAGE_SCENE } from '@/common/enum'
import { UseSubscriptionMessage } from '@/use/useCommon'
import { throttle } from '@/common/util'
import MoveBtn from '@/components/moveBtn'

const Comfirm = () => {
  const [showDesc, setShowDesc] = useState(false)
  // 下单信息
  interface OrderParams { address_id?: number; remark?: string; sale_mode?: number; shipment_mode?: number; list?: any[] }
  const [submitOrderData, setSubmitOrderData] = useState<OrderParams>()

  // 获取购物车传过来的id
  interface orderPreParam {
    shopping_cart_product_color_list: { shopping_cart_product_color_id: number }[]
    sale_mode: number
  }
  const param = getParam()
  const idsAndSaleModel = useRef<orderPreParam>({ shopping_cart_product_color_list: [], sale_mode: 0 })
  // 获取销售预览订单
  const [preViewOrder, setPreViewOrder] = useState<any>() // 获取到的原始数据
  const { fetchData } = SaleOrderPreViewApi()
  const getSaleOrderPreView = async() => {
    if (idsAndSaleModel.current.shopping_cart_product_color_list?.length > 0) {
      const res = await fetchData(idsAndSaleModel.current)
      setPreViewOrder(res.data)
    }
  }
  useDidShow(async() => {
    idsAndSaleModel.current = { shopping_cart_product_color_list: [], sale_mode: 0 } // 初始化
    idsAndSaleModel.current.sale_mode = Number(param?.sale_mode)
    param?.ids?.split('-')?.map((item) => {
      return idsAndSaleModel.current.shopping_cart_product_color_list?.push({
        shopping_cart_product_color_id: Number(item),
      })
    })
    getSaleOrderPreView()
    setSubmitOrderData(val => ({ ...val, sale_mode: param?.sale_mode }))
  })

  // 格式化数据格式
  const [formatPreViewOrder, setFormatPreViewOrder] = useState<any>() // 格式化后的数据
  const formatData = () => {
    setFormatPreViewOrder({
      estimate_amount: preViewOrder.estimate_amount, // 预估金额
      sale_mode: preViewOrder.sale_mode,
      sale_mode_name: preViewOrder.sale_mode_name,
      total_colors: preViewOrder.total_colors, // 总颜色数量
      total_number: preViewOrder.total_number, // 总数量
      total_fabrics: preViewOrder.total_fabrics, // 面料数量
      unit: preViewOrder.sale_mode == 0 ? '条' : 'm', // 单位
      list: preViewOrder.product_list,
      total_should_collect_money: preViewOrder.total_should_collect_money, // 应收金额
      total_sale_price: preViewOrder.total_sale_price, // 合计金额
    })
  }
  const formatPreViewOrderMemo = useMemo(() => {
    return formatPreViewOrder
  }, [formatPreViewOrder])

  // 格式化初始地址
  const defaultAddress = useMemo(() => {
    const address = preViewOrder?.default_address
    return {
      province_name: address?.province_name,
      city_name: address?.city_name,
      district_name: address?.district_name,
      address_detail: address?.address_detail,
      id: address?.id,
      target_user_name: address?.name,
      target_user_phone: address?.phone,
      shipment_mode: address?.shipment_mode,
      take_goods_address: preViewOrder?.take_goods_address,
      take_goods_phone: preViewOrder?.take_goods_phone,
    }
  }, [preViewOrder])

  // 获取提交格式数据列表
  const getDataList = () => {
    const list: { shopping_cart_product_color_id: number }[] = []
    preViewOrder.product_list?.forEach((item) => {
      item.product_colors?.forEach((colorItem) => {
        list.push({ shopping_cart_product_color_id: colorItem.id })
      })
    })
    setSubmitOrderData(val => ({ ...val, list }))
  }

  // 获取地址
  const getAddress = (e) => {
    setSubmitOrderData(val => ({ ...val, address_id: e.id }))
  }

  const selectShipmentMode = useCallback((value) => {
    setSubmitOrderData(val => ({ ...val, shipment_mode: value }))
  }, [])

  // 获取备注
  const getRemark = useCallback((e) => {
    setSubmitOrderData(val => ({ ...val, remark: e }))
    setShowDesc(() => false)
  }, [])

  // 提交按钮是否可用
  const btnStatus = useMemo(() => {
    return submitOrderData?.shipment_mode == 1 || (submitOrderData?.shipment_mode == 2 && submitOrderData?.address_id)
  }, [submitOrderData])

  // 数量格式
  const numText = useMemo(() => {
    if (formatPreViewOrder) {
      const total_number = formatPreViewOrder?.sale_mode == 0 ? formatPreViewOrder?.total_number : formatPreViewOrder?.total_number / 100
      return `${formatPreViewOrder?.total_fabrics} 种面料，${formatPreViewOrder?.total_colors} 种颜色，共 ${total_number} ${formatPreViewOrder?.unit}`
    }
  }, [formatPreViewOrder])

  // 订阅消息
  const { SubmitOrder } = SUBSCRIPTION_MESSAGE_SCENE
  const { openSubscriptionMessage } = UseSubscriptionMessage()

  // 提交订单
  const { fetchData: saleOrderFetchData } = SaleOrderApi()
  const submitOrderEven = throttle(async() => {
    if (!submitOrderData?.shipment_mode) {
      alert.error('请选择收货方式')
      return false
    }
    if (!submitOrderData?.address_id && submitOrderData?.shipment_mode == 2) {
      alert.error('请选择地址')
      return false
    }
    const showModalRes = await Taro.showModal({
      title: '确定提交订单?',
      content: `发货方式为${submitOrderData?.shipment_mode == 1 ? '自提' : '物流'}`,
      confirmText: '确定',
      cancelText: '取消',
    })
    if (showModalRes.confirm) {
      await openSubscriptionMessage({ scenes: SubmitOrder.value })
      Taro.showLoading({
        title: '订单提交中...',
        mask: true,
      })
      const res = await saleOrderFetchData(submitOrderData)
      Taro.hideLoading()
      if (res.success) {
        goLink('/pages/order/index', { id: res.data.id }, 'redirectTo')
      }
      else {
        alert.none(res.msg)
      }
    }
  }, 800)

  // 页面下拉刷新
  usePullDownRefresh(() => {
    getSaleOrderPreView()
  })
  // 监听获取到的数据
  useEffect(() => {
    if (preViewOrder) {
      formatData()
      getDataList()
      setSubmitOrderData(val => ({
        ...val,
        address_id: preViewOrder.default_address.id,
        shipment_mode: preViewOrder.shipment_mode || 2,
      }))
    }
  }, [preViewOrder])
  return (
    <MoveBtn showList={['customer']}>
      <View className={styles.order_main}>
        {
          preViewOrder?.notice !== '' && <View className={styles.topBox}>
            <View className={styles.flexBox}>
              <View className={styles.gan}>!</View>
              <View className={styles.ganFont}>{preViewOrder?.notice}</View>
            </View>
          </View>
        }
        <AddressInfoDetail orderInfo={defaultAddress} onSelect={getAddress} onChangeShipmentMode={selectShipmentMode} status={1} />
        <KindList order={formatPreViewOrderMemo} comfirm />
        <View className={styles.order_desc} onClick={() => setShowDesc(true)}>
          <View className={styles.order_desc_con}>订单备注</View>
          {(submitOrderData?.remark && <View className={styles.order_desc_text}>{submitOrderData?.remark}</View>) || <View className={styles.order_desc_text_hint}>填写备注</View>}
          <View className={classnames(styles.miconfont, 'iconfont icon-a-moreback')}></View>
        </View>
        <View className={styles.submit_order}>
          <View className={styles.submit_order_number}>
            <SubmitOrderBtn
              style={{ color: '#007AFF' }}
              number={(preViewOrder?.sale_mode == 1 ? formatPreViewOrder?.total_should_collect_money : formatPreViewOrder?.estimate_amount) / 100}
              priceTitle={preViewOrder?.sale_mode == 1 ? '合计金额' : '预估金额'}
            />
            <View className={styles.order_number_desc}>{numText}</View>
          </View>
          <View className={classnames(styles.order_btn, btnStatus && styles.ok_order_btn)} onClick={() => submitOrderEven()}>
          提交订单
          </View>
        </View>
        <Popup show={showDesc} showTitle={false} onClose={() => setShowDesc(false)}>
          <Remark defaultValue={submitOrderData?.remark} onSave={e => getRemark(e)} />
        </Popup>
        <View className="common_safe_area_y"></View>
      </View>
    </MoveBtn>
  )
}

export default Comfirm
