import { ScrollView, Text, View } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { memo, useCallback, useEffect, useMemo, useState } from 'react'
import styles from './index.module.scss'
import { SaleOrderOrderDetailApi } from '@/api/salesAfterOrder'
import { formatHashTag, formatPriceDiv, formatWeightDiv } from '@/common/fotmat'
import LabAndImg from '@/components/LabAndImg'
import Popup from '@/components/popup'

interface Param {
  show?: true | false
  onClose?: () => void
  onSubmit?: () => void
  id?: number
}
export default memo(({ show, onClose, onSubmit, id }: Param) => {
  useEffect(() => {
    if (show && id) { getSaleOrderPreView() }
    if (!show) { setFormatDetailOrder(() => null) }
  }, [show, id])

  // 获取订单详情
  const [orderDetail, setOrderDetail] = useState<any>(null) // 获取到的原始数据
  const { fetchData: saleOrderOrderDetailData } = SaleOrderOrderDetailApi()
  const getSaleOrderPreView = async() => {
    if (id) {
      const res = await saleOrderOrderDetailData({ id })
      setOrderDetail(res.data)
    }
    Taro.stopPullDownRefresh()
  }
  // 格式化数据格式
  const [formatDetailOrder, setFormatDetailOrder] = useState<any>() // 格式化后的数据
  const formatData = () => {
    setFormatDetailOrder({
      estimate_amount: orderDetail.estimate_amount, // 预估金额
      sale_mode: orderDetail.sale_mode,
      sale_mode_name: orderDetail.sale_mode_name,
      total_colors: orderDetail.total_colors, // 总颜色数量
      total_number: orderDetail.total_number, // 总数量
      total_fabrics: orderDetail.total_fabrics, // 面料数量
      unit: orderDetail.sale_mode == 0 ? '条' : 'm', // 单位
      list: orderDetail.product_list,
      stage: orderDetail.stage, // 订单状态
      type: orderDetail.type, // 退货or退款
      total_sale_price: orderDetail.total_sale_price, // 销售金额
      total_should_collect_money: orderDetail.total_should_collect_money, // 应收金额
      total_weight_error_discount: orderDetail.total_weight_error_discount, // 空差优惠
      actual_amount: orderDetail.actual_amount, // 实付金额
      the_previous_status: orderDetail.the_previous_status, // 取消订单时的订单状态
    })
  }

  // 监听获取到的数据
  useEffect(() => {
    if (orderDetail) { formatData() }
  }, [orderDetail])

  // 对应数量
  const formatCount = useCallback(
    (item) => {
      return formatDetailOrder?.sale_mode == 0 ? item.roll : Number(item.length / 100)
    },
    [formatDetailOrder],
  )

  // 对应单价
  const standardPrice = useCallback(
    (price) => {
      return `${formatPriceDiv(price).toLocaleString()}/${formatDetailOrder?.sale_mode == 1 ? 'm' : 'kg'}`
    },
    [formatDetailOrder],
  )

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

  // 整理颜色
  const labAndRgbAndUrl = useCallback((item) => {
    return { lab: { ...item?.lab }, rgb: { ...item?.rgb }, texturl_url: item?.texturl_url }
  }, [])

  return (
    <>
      <Popup show={show} title="申请记录" onClose={onClose}>
        <View className={styles.apply_record_main}>
          {formatDetailOrder && (
            <>
              <View className={styles.kind_number}>
                <Text>{numText}</Text>
              </View>
              <ScrollView scrollY className={styles.apply_record_scroll}>
                <View className={styles.orders_list_con}>
                  {formatDetailOrder?.list?.map((item) => {
                    return (
                      <View key={item.product_code} className={styles.order_list}>
                        <View className={styles.order_list_title}>
                          <View className={styles.tag}>{formatDetailOrder.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={labAndRgbAndUrl(colorItem)} />
                                </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}`}</View>
                                    <View className={styles.order_list_item_price}>
                                      <Text>¥{standardPrice(colorItem.sale_price)}</Text>
                                      {/* <Text>总重{formatWeightDiv(colorItem.estimate_weight)}kg</Text> */}
                                    </View>
                                  </View>
                                  <View className={styles.order_list_item_count}>
                                    {/* <View className={styles.count_num}>
                                      ×{formatCount(colorItem)}
                                      <text>{formatDetailOrder.unit}</text>
                                    </View> */}
                                    {/* <View className={styles.count_price}>
                                      <text>¥</text>
                                      {formatPriceDiv(colorItem.estimate_amount, 100, true)}
                                    </View> */}
                                  </View>
                                </View>
                              </View>
                            )
                          })}
                        </View>
                      </View>
                    )
                  })}
                </View>
              </ScrollView>
            </>
          )}
        </View>
      </Popup>
    </>
  )
})
