import { View } from '@tarojs/components'
import Taro, { useDidShow, usePullDownRefresh, useRouter } from '@tarojs/taro'
import type { ReactNode } from 'react'
import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import classnames from 'classnames'
import AddressDetailBox from '../orderDetails/components/addressDetailBox'
import Remark from '../orderDetails/components//remark'
import styles from './index.module.scss'
import Popup from '@/components/popup'
import { debounce } from '@/common/util'
import {
  MpSaleOrderPost,
  MpSaleOrderPreview,
} from '@/api/order'
import { alert } from '@/common/common'
import { formatDateTime, formatPriceDiv, formatWeightDiv } from '@/common/format'
import IconFont from '@/components/iconfont/iconfont'

// 卡片盒子元素
interface Obs {
  title?: string
  modeName?: string
  showMode?: boolean
  children?: ReactNode
  clickNode?: () => void
}

const DefaultBox = (props: Obs) => {
  const {
    title = '标题',
    modeName = '大货',
    showMode = false,
    children,
    clickNode,
  } = props

  return (
    <View className={styles.defaltBox}>
      <View className={styles.titleBox}>
        <View className={styles.title}>{title}</View>
        {
          showMode && <View className={styles.modeName} onClick={() => clickNode?.()}>{modeName}</View>
        }
      </View>
      <View className={styles.modeLine}></View>
      {children}
    </View>
  )
}
const DefaultBoxWithMemo = memo(DefaultBox)

// 产品商品元素
interface PropGoods {
  // item?: {
  //     code?: string | number
  // }
  list: any[]
  obj: {
    sale_mode?: number | string
  }
}
const GoodsItem = (porps: PropGoods) => {
  const { list = [], obj = {} } = porps
  return (
    <>
      {
        list.map((item, index) => {
          return (
            <View className={styles.goodsBox} key={index}>
              <View className={styles.goodsProduct}>{item.code}# {item.name}</View>
              <View className={styles.goodsLine}></View>
              {
                item.product_colors.map((it, inx) => {
                  return (
                    <View className={styles.itemGoods} key={inx}>
                      <View className={styles.itemPic} style={{ backgroundColor: `rgb(${it?.rgb?.r} ${it?.rgb?.g} ${it?.rgb?.b})` }}></View>
                      <View className={styles.itemRight}>
                        <View className={styles.item_right_top}>
                          <View className={styles.itemName}>{it.code} {it.name}</View>
                          <View className={styles.itemNums}>x{obj?.sale_mode === 0 ? it.roll : it.length / 100}{obj?.sale_mode === 0 ? '条' : 'm'}</View>
                        </View>
                        <View className={styles.item_right_Bottom}>
                          <View className={styles.itemMoney}>¥{it.sale_price / 100}/{obj?.sale_mode === 1 ? 'm' : 'kg'}</View>
                          <View className={styles.itemMoneyOne}>¥{formatPriceDiv(it.estimate_amount)}</View>
                        </View>
                      </View>
                    </View>
                  )
                })
              }
            </View>
          )
        })
      }
    </>

  )
}
const GoodsItemWithMemo = memo(GoodsItem)

const SubmitOrder = () => {
  const router: any = useRouter()
  const [infoObj, setInfoObj] = useState<any>({})
  let selectId = -1

  // 收货方法,1:自提，2物流
  const [receivingStatus, setReceivingStatus] = useState<any>(null)
  // 切换自提或者物流
  const onReceivingStatus = debounce(async(e, value) => {
    e.stopPropagation()
    if (receivingStatus == value) {
      alert.error('不能选择相同的方式')
      return false
    }
    Taro.showLoading({
      title: '请稍等...',
      mask: true,
    })
    setReceivingStatus(value)
    Taro.hideLoading()
  }, 300)

  const { fetchData: infoFetch } = MpSaleOrderPreview()
  const [pussName, setPusername] = useState<String>('')
  // 获取订单详情
  const getDetail = async() => {
    let arr: any[] = []
    setPusername(decodeURIComponent(router.params.purchaser_name))
    arr = JSON.parse(decodeURIComponent(router.params.shopping_cart_product_color_list))
    const list: any[] = []
    arr?.forEach((item) => {
      list.push({
        shopping_cart_product_color_id: item,
        sale_price: 0,
      })
    })
    const query = {
      purchaser_id: Number(router.params.purchaser_id),
      sale_mode: Number(router.params.sale_mode),
      shopping_cart_product_color_list: list,
    }
    const res = await infoFetch(query)
    setInfoObj(res.data)
  }

  // 备注操作
  const [showDesc, setShowDesc] = useState(false)
  const getRemark = useCallback(async(e) => {
    setShowDesc(false)
    setInfoObj(val => ({ ...val, remark: e }))
  }, [])

  const handSelect = (obj) => {
    if (receivingStatus == 1) { return false }
    Taro.navigateTo({
      url: '/pages/addressManager/index?orderId=' + '-100' + `&purchaser_id=${router.params.purchaser_id}`,
    })
  }

  // 提交订单
  const { fetchData: postFetch } = MpSaleOrderPost()
  const handSure = () => {
    if (receivingStatus == 2 && !infoObj.address_id) {
      return alert.error('请选择地址')
    }
    const list: any[] = []
    infoObj.product_list.forEach((item) => {
      item.product_colors.forEach((it) => {
        list.push({
          sale_price: it.sale_price,
          shopping_cart_product_color_id: Number(it.id),
        })
      })
    })
    const query = {
      address_id: Number(infoObj.address_id) ? Number(infoObj.address_id) : 0,
      list,
      physical_warehouse: infoObj.physical_warehouse,
      purchaser_id: Number(router.params.purchaser_id),
      remark: infoObj.remark,
      sale_mode: infoObj.sale_mode,
      shipment_mode: receivingStatus,
    }
    Taro.showModal({
      content: '确认提交吗？',
      confirmText: '确认',
      cancelText: '取消',
      async success(res) {
        if (res.confirm) {
          Taro.showLoading({
            title: '请稍等...',
            mask: true,
          })
          const res = await postFetch(query)
          if (res?.msg === 'success') {
            Taro.showToast({
              title: '成功',
            })
            Taro.hideLoading()
            Taro.redirectTo({
              url: `/pages/orderDetails/index?id=${res.data.id}`,
            })
          }
          else {
            Taro.hideLoading()
            Taro.showToast({
              title: res?.msg,
              icon: 'error',
            })
          }
        }
      },
    })
  }

  useEffect(() => {
    setInfoObj(infoObj)
  }, [infoObj])
  useDidShow(() => {
    // 获取选择的地址
    const pages = Taro.getCurrentPages()
    const currPage = pages[pages.length - 1] // 获取当前页面
    setInfoObj(val => ({
      ...val,
      sale_mode: Number(router.params.sale_mode),
      province_name: currPage.data?.addressObj?.province_name ? currPage.data?.addressObj?.province_name : '',
      address_id: currPage.data?.addressObj?.id ? currPage.data?.addressObj?.id : '',
      city_name: currPage.data?.addressObj?.city_name ? currPage.data?.addressObj?.city_name : '',
      address_detail: currPage.data?.addressObj?.address_detail ? currPage.data?.addressObj?.address_detail : '',
      district_name: currPage.data?.addressObj?.district_name ? currPage.data?.addressObj?.district_name : '',
      target_user_name: currPage.data?.addressObj?.name ? currPage.data?.addressObj?.name : '',
      purchaser_phone: currPage.data?.addressObj?.phone ? currPage.data?.addressObj?.phone : '',
    }))
    selectId = currPage.data?.addressObj?.id
    const obj = currPage?.data?.ids?.filter((item) => { return item == selectId })
    if (currPage?.data?.ids && obj.length === 0) {
      setInfoObj(val => ({
        ...val,
        sale_mode: Number(router.params.sale_mode),
        province_name: '',
        address_id: '',
        city_name: '',
        address_detail: '',
        district_name: '',
        target_user_name: '',
        purchaser_phone: '',
      }))
    }
    if (!currPage.data?.addressObj) {
      setReceivingStatus(1)
    }
    else {
      setReceivingStatus(2)
    }
  })
  useEffect(() => {
    getDetail()
  }, [])
  return (
    <View className={styles.mainBox}>
      <AddressDetailBox
        navSelect={obj => handSelect(obj)}
        obj={infoObj}
        receivingStatus={receivingStatus}
        onReceivingStatus={(e, value) => onReceivingStatus(e, value)}
      ></AddressDetailBox>
      <DefaultBoxWithMemo
        showMode
        title="客户信息"
        modeName={infoObj.sale_mode_name}
      >
        <View className={styles.pussBox}>
          <View className={styles.pussName}>{pussName}</View>
          {/* <View className={styles.pussPhone}>{infoObj.purchaser_phone}</View> */}
        </View>
      </DefaultBoxWithMemo>
      {/* <View className={styles.total}> {infoObj.product_list?.length} 种面料，{infoObj.total_colors} 个颜色，共 {infoObj.sale_mode === 0 ? infoObj.total_number : infoObj.total_number / 100} {infoObj.sale_mode === 0 ? '条' : 'm'}</View> */}
      <View className={styles.productBox}>
        <GoodsItemWithMemo list={infoObj?.product_list} obj={infoObj}></GoodsItemWithMemo>
        <View className={styles.flexMoney}>
          <View className={styles.flexTotalBox}>
            <View className={styles.totalFont}>合计金额</View>
            <IconFont name="icon-tishi" size={28} ></IconFont>
            {/* <View className={classnames('iconfont', 'icon-tishi', styles.tishi)}></View> */}
          </View>
          <View className={styles.shoudPay}>¥{formatPriceDiv(infoObj.estimate_amount)}</View>
        </View>
      </View>
      <DefaultBoxWithMemo title="备注信息" showMode modeName={`${'填写/修改备注'} >`} clickNode={() => setShowDesc(true)}>
        <View className={styles.remarkFont}>{infoObj.remark === '' ? '暂无' : infoObj.remark}</View>
      </DefaultBoxWithMemo>
      <Popup show={showDesc} showTitle={false} onClose={() => setShowDesc(false)}>
        <Remark onSave={e => getRemark(e)} defaultValue={infoObj.remark} showInput={!!showDesc} />
      </Popup>
      <View className={styles.safeBottom}></View>
      <View className={styles.bottomBox}>
        <View className={styles.leftBottom}>
          <View className={styles.topFlex}>
            <View className={styles.topFont}>预估金额:</View>
            <View className={styles.topTotal}>¥{formatPriceDiv(infoObj.estimate_amount)}</View>
          </View>
          <View className={styles.bottomFlex}>{infoObj.product_list?.length} 种面料，{infoObj.total_colors} 种颜色，共 {infoObj.sale_mode === 0 ? infoObj.total_number : infoObj.total_number / 100} {infoObj.sale_mode === 0 ? '条' : 'm'}</View>
        </View>
        <View className={styles.rightBottom} onClick={() => handSure()}>提交订单</View>
      </View>
    </View>
  )
}
export default SubmitOrder
