import { Button, Image, Input, View } from '@tarojs/components'
import Taro, { faceVerifyForPay, useDidShow, usePullDownRefresh, useRouter } from '@tarojs/taro'
import type { ReactNode } from 'react'
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import classnames from 'classnames'
import styles from './index.module.scss'
import ItemList from './components/itemList'
import OrderState from './components/orderState'
import { formatDateTime, formatHashTag, formatImgUrl, formatPriceDiv, formatWeightDiv } from '@/common/format'
import {
  MpReturnApplyOrder,
  ReturnApplyOrderCancel,
  ReturnApplyOrderUploadAccessory,
} from '@/api/refound'
// import AddressDetailBox from './components/addressDetailBox'
import { IMG_CND_Prefix } from '@/common/constant'
import RefundCodelist from '@/components/RefundCodelist'
import LabAndImg from '@/components/LabAndImg'

enum ReturnEnum {
  Refunded = 3, // 已退款
  RefundedBefore = 5, // 待退款-确认单
  RefundedAfter = 6, // 待退款
}

enum ReturnType {
  TypeOne = 2, // 预收退款
}

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: any
}
const GoodsItem = (porps: PropGoods) => {
  const { list = [], obj = {} } = porps
  const labAndImgObj = useCallback((item) => {
    return { lab: item.lab, rgb: item.rgb, texture_url: item.texture_url }
  }, [])
  return (
    <>
      {
        list.map((item, index) => {
          return (
            <View className={styles.goodsBox} key={index}>
              <View className={styles.goodsProduct}>{formatHashTag(item?.code, item?.name)}</View>
              {
                item?.product_colors.map((it, inx) => {
                  return (
                    <View className={styles.itemGoods} key={inx}>
                      {
                        it.texture_url === ''
                                                && <Image className={styles.itemPic} mode="aspectFill" src="https://test.cdn.zzfzyc.com/mall/no_img.png"></Image>
                      }
                      {
                        it.texture_url !== ''
                                                && <View className={styles.itemPic}>
                                                  <LabAndImg value={labAndImgObj(it)} />
                                                </View>
                      }
                      {/* <View className={styles.itemPic} style={{ backgroundColor: `rgb(${it?.rgb?.r} ${it?.rgb?.g} ${it?.rgb?.b})` }}></View> */}
                      <View className={styles.clear}> </View>
                      <View className={styles.itemRight}>
                        <View className={styles.item_right_top}>
                          <View className={styles.itemName}>{formatHashTag(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> */}
                          {
                            obj.sale_mode == 0 && <View className={styles.itemNums}>x{obj.stage == 0 || obj.stage == 1 || obj.stage == 2
                              ? it.roll
                              : obj.stage == 5 || obj.stage == 6 || obj.stage == 3
                                ? it.return_roll
                                : it.roll}{obj?.sale_mode == 0 ? '条' : 'm'}</View>
                          }
                          {
                            obj.sale_mode != 0 && <View className={styles.itemNums}>x{it.length / 100}m</View>
                          }
                        </View>
                        <View className={styles.item_right_Bottom}>
                          <View className={styles.itemMoney}>¥{it.sale_price / 100}/{obj?.sale_mode == 0 ? 'kg' : 'm'}</View>
                          {/* <View className={styles.itemMoneyOne}>¥{formatPriceDiv(it.total_sale_price)}</View> */}
                        </View>
                      </View>
                    </View>
                  )
                })
              }
            </View>
          )
        })
      }
    </>

  )
}
const GoodsItemWithMemo = memo(GoodsItem)

const RefundMoneyDetail = () => {
  const router = useRouter()

  // 获取详情
  const { fetchData: detailFetch } = MpReturnApplyOrder()
  const [DeatailObj, setDeatailObj] = useState<any>({})

  // 分辨用质检中还是质检前的数组
  const productList = useMemo(() => {
    if (DeatailObj?.stage == 0 || DeatailObj?.type == 3 || DeatailObj?.type == 2) {
      return DeatailObj?.product_list
    }
    else {
      return DeatailObj?.quality_check_pass_product
    }
  }, [DeatailObj])

  // 订单信息文字数组
  const [orderMsg, setOrderMsg] = useState<any[]>([
    {
      leftTitle: '售后编号：',
      rightTitle: '------',
      showBtn: true,
    },
    {
      leftTitle: '订单号：',
      rightTitle: '------',
      showBtn: true,
    },
    {
      leftTitle: '退货原因：',
      rightTitle: '------',
    },
    {
      leftTitle: '退货说明：',
      rightTitle: '------',
    },
    {
      leftTitle: '其他说明：',
      rightTitle: '------',
    },
    // {
    //     leftTitle: '货物状况：',
    //     rightTitle: '------',
    // },
    {
      leftTitle: '申请时间：',
      rightTitle: '------',
    },
  ])

  // 复制功能
  const clipboardData = (val) => {
    Taro.setClipboardData({
      data: val || '',
      success(res) {
        Taro.showToast({
          icon: 'none',
          title: '复制成功',
        })
      },
    })
  }
  const getDetail = async() => {
    Taro.showLoading({
      title: '加载中...',
      mask: true,
    })
    const res = await detailFetch({ id: Number(router.params.id) })
    if (res.data) {
      setDeatailObj(res.data)
      orderMsg.forEach((it) => {
        if (it.leftTitle === '售后编号：') {
          it.rightTitle = res.data.return_order_no
        }
        if (it.leftTitle === '订单号：') {
          it.rightTitle = res.data.order_no
        }
        if (it.leftTitle === '退货原因：') {
          it.rightTitle = res.data.return_reason_name
        }
        if (it.leftTitle === '退货说明：') {
          it.rightTitle = res.data.return_explain_name
        }
        if (it.leftTitle === '其他说明：') {
          it.rightTitle = res.data.reason_describe
        }
        // if (it.leftTitle === '货物状况：') {
        //     it.rightTitle = res.data.goods_status_name
        // }
        if (it.leftTitle === '申请时间：') {
          it.rightTitle = formatDateTime(res.data.apply_time)
        }
      })
      setOrderMsg([...orderMsg])
      Taro.stopPullDownRefresh()
      // setPicList([...res.data?.accessory_url !== null ? res.data?.accessory_url : []])
      Taro.hideLoading()
    }
  }
  // 取消退货
  const { fetchData: cancelFetch } = ReturnApplyOrderCancel()
  const handCancle = async() => {
    Taro.showModal({
      content: '确定要取消吗？',
      confirmText: '确认',
      cancelText: '取消',
      async success(res) {
        if (res.confirm) {
          const res = await cancelFetch({ id: Number(DeatailObj.id) })
          Taro.showLoading({
            title: '请稍等...',
            mask: true,
          })
          if (res.msg === 'success') {
            Taro.showToast({
              title: '取消成功',
            })
            Taro.hideLoading()
            getDetail()
          }
          else {
            Taro.showToast({
              title: res.msg,
              icon: 'error',
            })
          }
        }
      },
    })
  }
  // //查看图片
  // const [ShowPic, setShowPic] = useState(false)

  // const [PicList, setPicList] = useState<any[]>([])

  // const handUp = (value) => {
  //     setShowPic(true)
  // }

  // const onlyRead = useMemo(() => {
  //     if (DeatailObj.stage == 1) {
  //         return false
  //     } else {
  //         return true
  //     }
  // }, [DeatailObj])

  // //获取图片列表
  // const picUrl = useRef([])
  // const getImageList = useCallback((list) => {
  //     picUrl.current = list
  // }, [])

  const proview = (item) => {
    Taro.previewImage({
      current: IMG_CND_Prefix + item, // 当前显示图片的 http 链接
      urls: DeatailObj.fabric_piece_accessory_url.map((item) => {
        item = IMG_CND_Prefix + item
        return item
      }), // 需要预览的图片 http 链接列表
    })
  }
  const [ShowCode, setShowCode] = useState(false)
  const handSee = () => {
    setShowCode(true)
  }

  useEffect(() => {
    getDetail()
  }, [])
  // 页面下拉刷新
  usePullDownRefresh(() => {
    getDetail()
  })

  // 待退款和已退款需要变更字段
  const totalGoods = useMemo(() => {
    if ((DeatailObj.stage == ReturnEnum.Refunded || DeatailObj.stage == ReturnEnum.RefundedBefore || DeatailObj.stage == ReturnEnum.RefundedAfter) && DeatailObj.type != ReturnType.TypeOne) {
      return DeatailObj.quality_check_pass_fabrics
    }
    if ((DeatailObj.stage != ReturnEnum.Refunded || DeatailObj.stage != ReturnEnum.RefundedBefore || DeatailObj.stage != ReturnEnum.RefundedAfter) && DeatailObj.type != ReturnType.TypeOne) {
      return DeatailObj.total_fabrics
    }
    if (DeatailObj.type == ReturnType.TypeOne) {
      return DeatailObj.total_fabrics
    }
  }, [DeatailObj])
  // 待退款和已退款需要变更字段
  const totalColors = useMemo(() => {
    if ((DeatailObj.stage == ReturnEnum.Refunded || DeatailObj.stage == ReturnEnum.RefundedBefore || DeatailObj.stage == ReturnEnum.RefundedAfter) && DeatailObj.type != ReturnType.TypeOne) {
      return DeatailObj.quality_check_pass_colors
    }
    if ((DeatailObj.stage != ReturnEnum.Refunded || DeatailObj.stage != ReturnEnum.RefundedBefore || DeatailObj.stage != ReturnEnum.RefundedAfter) && DeatailObj.type != ReturnType.TypeOne) {
      return DeatailObj.total_colors
    }
    if (DeatailObj.type == ReturnType.TypeOne) {
      return DeatailObj.total_colors
    }
  }, [DeatailObj])
  // 待退款和已退款需要变更字段
  const totalNums = useMemo(() => {
    if ((DeatailObj.stage == ReturnEnum.Refunded || DeatailObj.stage == ReturnEnum.RefundedBefore || DeatailObj.stage == ReturnEnum.RefundedAfter) && DeatailObj.sale_mode == 0 && DeatailObj.type != ReturnType.TypeOne) {
      return DeatailObj.quality_check_pass_number
    }
    if ((DeatailObj.stage == ReturnEnum.Refunded || DeatailObj.stage == ReturnEnum.RefundedBefore || DeatailObj.stage == ReturnEnum.RefundedAfter) && DeatailObj.sale_mode != 0 && DeatailObj.type != ReturnType.TypeOne) {
      return DeatailObj.quality_check_pass_number / 100
    }
    if ((DeatailObj.stage != ReturnEnum.Refunded || DeatailObj.stage != ReturnEnum.RefundedBefore || DeatailObj.stage != ReturnEnum.RefundedAfter) && DeatailObj.sale_mode == 0 && DeatailObj.type != ReturnType.TypeOne) {
      return DeatailObj.return_roll
    }
    if ((DeatailObj.stage != ReturnEnum.Refunded || DeatailObj.stage != ReturnEnum.RefundedBefore || DeatailObj.stage != ReturnEnum.RefundedAfter) && DeatailObj.sale_mode != 0 && DeatailObj.type != ReturnType.TypeOne) {
      return DeatailObj.total_number / 100
    }
    if (DeatailObj.type == ReturnType.TypeOne) {
      return DeatailObj.total_number / 100
    }
  }, [DeatailObj])

  return (
    <View className={styles.main}>
      <OrderState orderInfo={DeatailObj} />
      {/* <AddressDetailBox
                obj={DeatailObj}
                handUp={() => handUp(DeatailObj)}
            ></AddressDetailBox> */}
      <DefaultBoxWithMemo
        showMode
        title="客户信息"
        modeName={DeatailObj.sale_mode_name}
      >
        <View className={styles.pussBox}>
          <View className={styles.pussName}>{DeatailObj.purchaser_name}</View>
          <View className={styles.pussPhone}>{DeatailObj.purchaser_phone}</View>
        </View>
      </DefaultBoxWithMemo>
      <DefaultBoxWithMemo title="退款信息">
        <GoodsItemWithMemo list={productList} obj={DeatailObj}></GoodsItemWithMemo>
        <View className={styles.totalBox}>
          <View className={styles.totalLeft}>总计</View>
          <View className={styles.totalRight}>{totalGoods} 种面料，{totalColors} 种颜色，共 { totalNums} {DeatailObj?.sale_mode == 0 ? '条' : '米'}</View>
        </View>
        {
          DeatailObj.stage == 0 && <View className={styles.totalBox}>

            <View className={styles.totalLeft}>合计金额</View>
            <View className={styles.totalRight} style={{ color: '#F64861' }}>￥{
              formatPriceDiv(DeatailObj.total_refund_amount)
            }</View>
          </View>
        }
        {
          (DeatailObj.stage == 3) && <View className={styles.totalBox}>
            <View className={styles.totalLeft}>退款金额</View>
            <View className={styles.totalRight} style={{ color: '#F64861' }}>￥{
              formatPriceDiv(DeatailObj.refund_amount)
            }</View>
          </View>
        }
        {
          (DeatailObj.stage == 3) && <View className={styles.totalBox}>
            <View className={styles.totalLeft}>其他扣除金额</View>
            <View className={styles.totalRight} style={{ color: '#F64861' }}>￥{
              formatPriceDiv(DeatailObj.other_deduction_amount)
            }</View>
          </View>
        }
        {
          (DeatailObj.stage == 3) && <View className={styles.totalBox}>
            <View className={styles.totalLeft}>退款去向</View>
            <View className={styles.totalRight} style={{ color: '#F64861' }}>{
              DeatailObj.refund_flow_name
            }</View>
          </View>
        }
      </DefaultBoxWithMemo>
      <DefaultBoxWithMemo title="订单信息">
        {
          orderMsg.map((item, index) => {
            return (
              <View className={styles.detailBox} key={index}>
                <View className={styles.detailFont}>
                  {item.leftTitle}
                </View>
                <View className={styles.detailRightFlex}>
                  <View className={styles.detailRight}>{item.rightTitle}</View>
                  {item.showBtn && <View className={styles.detailBtn} onClick={() => clipboardData(item.rightTitle)}>复制</View>}
                </View>

              </View>
            )
          })
        }

      </DefaultBoxWithMemo>
      <DefaultBoxWithMemo title="售后图片">
        <View className={styles.picBox}>
          {
            DeatailObj?.fabric_piece_accessory_url?.length > 0 && DeatailObj?.fabric_piece_accessory_url.map((item, index) => {
              return (
                <Image className={styles.pic} lazyLoad key={index} onClick={() => proview(item)}
                  mode="aspectFill" src={IMG_CND_Prefix + item}
                ></Image>
              )
            })
          }
          {
            DeatailObj?.fabric_piece_accessory_url?.length === 0 && <View className={styles.noPic}>暂无图片</View>
          }
        </View>
      </DefaultBoxWithMemo>
      <View className={styles.safeBox}></View>
      <View className={styles.bottomMuck}>
        {
          (DeatailObj.stage === 0 || DeatailObj.stage === 1) && <View className={styles.cancleBtn} onClick={() => handCancle()}>取消退货</View>

        }
        {
          (DeatailObj.sale_mode == 0 && DeatailObj.stage == 3 && (DeatailObj.type == 1 || DeatailObj.type == 3)) && <View className={styles.seeButon} onClick={() => { handSee() }}>查看码单</View>
        }

      </View>
      <RefundCodelist
        obj={DeatailObj}
        // picUrl={PicUrl}
        showPopup={ShowCode}
        popupClose={() => setShowCode(false)}
      ></RefundCodelist>
    </View>
  )
}
export default RefundMoneyDetail
