import { Text, View } from '@tarojs/components'
import { memo, useCallback, useMemo, useState } from 'react'
import styles from './index.module.scss'
import { ORDER_STATUS } from '@/common/enum'
import { formatHashTag, formatPriceDiv, formatWeightDiv } from '@/common/fotmat'
import EstimatedAmount from '@/components/estimatedAmount'
import LabAndImg from '@/components/LabAndImg'

interface OrderParam {
  estimate_amount: number // 预估金额
  list: any[]
  sale_mode: number
  sale_mode_name: string
  unit: string
  total_colors: number
  total_fabrics: number
  total_number: number
  status: number // 订单状态
  total_sale_price: number // 合计金额
  total_weight_error_discount: number // 空差优惠
  the_previous_status: number // 取消订单时的订单状态
  actual_amount: number // 实付金额
  wait_pay_amount: number // 待付金额
}

interface Param {
  order: OrderParam
  comfirm?: boolean // 是否是确认订单页面使用
}

export default memo(({ order, comfirm = false }: Param) => {
  const {
    SaleOrderStatusBooking, // 待接单
    SaleOrderStatusArranging, // 配布中
    SaleOrderStatusArranged, // 已配布
    SaleOrderStatusWaitingPayment, // 待付款
    SaleOrderStatusWaitingDelivery, // 待发货
    SaleOrderStatusWaitingReceipt, // 待收货
    SaleOrderStatusAlreadyReceipt, // 已收货
    SaleOrderStatusComplete, // 已完成
    SaleOrderStatusRefund, // 已退款
    SaleOrderStatusCancel, // 已取消
    SaleorderstatusWaitingPrePayment, // 预付款
    SaleOrderStatusTaking, // 提货
  } = ORDER_STATUS

  // 注册金额
  interface orderPriceListParams { id: number; label: string; field: string; message: string; validatarFunc: (val: typeof order) => any }
  const priceList: orderPriceListParams[] = [
    {
      id: 1,
      label: '预估金额',
      field: 'estimate_amount',
      message: '预估金额按生产商定义的标准匹重计算，仅供参考。详细交易金额以出单为准！',
      validatarFunc: (order) => {
        return order.estimate_amount > 0 && order.total_sale_price <= 0
      },

    },
    {
      id: 2,
      label: '合计金额',
      field: 'total_sale_price',
      message: '包含空差的货款金额',
      validatarFunc: (order) => {
        return order.total_sale_price > 0
      },
    },
    {
      id: 3,
      label: '空差优惠',
      field: 'total_weight_error_discount',
      message: '扣除空差金额',
      validatarFunc: (order) => {
        return order.total_weight_error_discount > 0
      },
    },
    {
      id: 5,
      label: '实付金额',
      field: 'actual_amount',
      message: '本单实付总金额',
      validatarFunc: (order) => {
        const value = [SaleOrderStatusWaitingPayment.value, SaleOrderStatusTaking.value, SaleOrderStatusWaitingDelivery.value, SaleOrderStatusWaitingReceipt.value, SaleOrderStatusAlreadyReceipt.value, SaleOrderStatusComplete.value, SaleOrderStatusRefund.value]
        return value.includes(order.status)
      },
    },
    {
      id: 4,
      label: '待付金额',
      field: 'wait_pay_amount',
      message: '扣除空差后的货款金额',
      validatarFunc: (order) => {
        const value = [SaleOrderStatusWaitingPayment.value, SaleOrderStatusTaking.value, SaleOrderStatusWaitingDelivery.value, SaleOrderStatusWaitingReceipt.value, SaleOrderStatusAlreadyReceipt.value, SaleOrderStatusComplete.value, SaleOrderStatusRefund.value]
        return value.includes(order.status)
      },
    },

  ]

  // 订单流程金额展示
  const priceConDom = useMemo(() => {
    if (!order) { return }
    return (
      <>
        {
          priceList.map((item) => {
            return <>{item.validatarFunc(order) && <EstimatedAmount key={item.id} number={order[item.field]} title={item.label} messageTitle={item.message} />}</>
          })
        }
      </>
    )
  }, [order])

  // 对应数量
  const formatCount = useCallback((item) => {
    return order?.sale_mode == 0 ? item.roll : Number(item.length / 100)
  }, [order])
  // 对应单价
  const standardPrice = useCallback((price) => {
    return `${formatPriceDiv(price, 100, true)}/${order?.sale_mode == 1 ? 'm' : 'kg'}`
  }, [order])

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

  // 确认订单金额展示
  const comfirmPriceConDom = useMemo(() => {
    if (!order) { return }
    const item = order.sale_mode == 1 ? priceList[1] : priceList[0]
    return <EstimatedAmount key={item.id} number={order[item.field]} title={item.label} messageTitle={item.message} />
  }, [order])

  // 确认金额展示
  const showPriceConDom = useMemo(() => {
    return comfirm ? comfirmPriceConDom : priceConDom
  }, [order])

  // 颜色金额小计
  const colorPrice = useCallback((item) => {
    const res = item.total_sale_price || item.estimate_amount
    return formatPriceDiv(res, 100, true)
  }, [order])

  // 散剪大约重量
  const aboutWeight = useCallback((weight) => {
    if (order.sale_mode == 2) {
      const showWeight = [SaleorderstatusWaitingPrePayment.value, SaleOrderStatusBooking.value, SaleOrderStatusArranging.value].includes(order.status)
      return showWeight ? <View className={styles.order_list_item_price_dg}>; <Text>≈{formatWeightDiv(weight)}kg</Text></View> : <></>
    }
    return <></>
  }, [order])

  return (
    <>
      <View className={styles.orders_list_title}>{numText}</View>
      <View className={styles.orders_list_con}>
        {
          order?.list?.map((item) => {
            return <View key={item.product_code} className={styles.order_list}>
              <View className={styles.order_list_title}>
                <View className={styles.tag}>{order.sale_mode_name}</View>
                <View className={styles.title}>{formatHashTag(item.code, item.name)}</View>
                <View className={styles.num}>共{item?.product_colors.length}种</View>
              </View>
              <View className={styles.order_list_scroll}>
                {item?.product_colors?.map((colorItem) => {
                  return <View key={colorItem.id} className={styles.order_list_item}>
                    <View className={styles.order_list_item_img}>
                      <LabAndImg value={{ lab: item.lab, rgb: item.rgb, texture_url: item.texture_url }} />
                    </View>
                    <View className={styles.order_list_item_con}>
                      <View className={styles.order_list_item_des}>
                        <View className={styles.order_list_item_title}>
                          {`${colorItem.code} ${colorItem.name}`}
                          {(colorItem?.return_roll > 0) && <Text>{`已退${colorItem?.return_roll}条`}</Text>}
                          {(colorItem?.apply_return_roll > 0) && <Text>{`待退${colorItem?.apply_return_roll}条`}</Text>}
                        </View>
                        <View className={styles.order_list_item_price}>
                                                    ¥{standardPrice(colorItem.sale_price)}
                          {aboutWeight(colorItem.estimate_weight)}
                        </View>
                      </View>
                      <View className={styles.order_list_item_count}>
                        <View className={styles.count_num}>×{formatCount(colorItem)}<text>{order.unit}</text></View>
                        <View className={styles.count_price}><text>¥</text>{colorPrice(colorItem)}</View>
                      </View>
                    </View>
                  </View>
                })}
              </View>
            </View>
          })
        }
        <View className={styles.order_estimated_amount}>
          {showPriceConDom}
        </View>
      </View>
    </>
  )
})
