import { Button, Image, Input, ScrollView, Text, Textarea, View } from '@tarojs/components'
import Taro, { faceVerifyForPay, useDidShow, useRouter } from '@tarojs/taro'
import { ReactNode, memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import classnames from 'classnames'
import styles from './index.module.scss'
import { formatDateTime, formatHashTag, formatImgUrl, formatPriceDiv, formatWeightDiv } from '@/common/format'
import {
  MpEnumRefundExplainOne,
  MpReturnApplyOrder,
  MpSaleOrder,
} from '@/api/order'
import Popup from '@/components/popup'

// 产品商品元素
interface PropGoods {
  list: any[]
  obj: {
    sale_mode?: number | string
  }
  handTui?: (any) => void
  handCancel?: (any) => void
  onBlur?: (e: any, obj: any) => void
  onInputEven?: (e: any, obj: any) => void
  handReduce?: (any) => void
  handAdd?: (any) => void
}

const GoodsItem = (porps: PropGoods) => {
  const { list = [], obj = {}, handTui, handCancel, onBlur, handReduce, handAdd, onInputEven } = porps
  // const [value, setValue] = useState<any>({ count: 1 })
  // const onInputEven = (e) => {
  //     let res = Number(e.detail.value)
  //     if (res < 1) {
  //         setValue({ count: 1 })
  //     } else {
  //         setValue({ count: res })
  //     }
  // }

  return (
    <>
      {
        list.map((item, index) => {
          return (
            <View className={styles.goodsBox} key={index}>
              <View className={styles.goodsProduct}>{item.product_code}# {item.product_name}</View>
              <View className={styles.goodsLine}></View>
              {
                item.av_product_color.map((it, inx) => {
                  return (
                    <View className={styles.itemGoods} key={inx}>
                      <Image className={styles.itemPic} mode="aspectFill" src="https://test.cdn.zzfzyc.com/mall/no_img.png"></Image>
                      {/* <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.product_color_code} {it.product_color_name}</View>
                        </View>
                        <View className={styles.item_right_Bottom}>
                          <View className={styles.itemMoney}>x{obj?.sale_mode === 0 ? it.roll : it.length / 100}{obj?.sale_mode === 0 ? '条' : 'm'}</View>
                          {
                            !it.isTui && <View className={styles.btn} onClick={() => handTui?.(it)}>退货</View>
                          }
                          {
                            (it.sale_mode != 0 && it.isTui) && <View className={styles.btnOne} onClick={() => handCancel?.(it)}>已选择退货</View>
                          }
                          {
                            (it.sale_mode == 0 && it.isTui) && <View className={styles.inputBox} >
                              <View className={styles.redceBox} onClick={() => handReduce?.(it)}>
                                <View className={styles.reduce}></View>
                              </View>
                              <View className={styles.inputBig}>
                                <Input type="number" value={it.nums} onInput={e => onInputEven?.(e, it)} maxlength={it.roll} onBlur={e => onBlur?.(e, it)}></Input>
                              </View>
                              <View className={styles.addBox} onClick={() => handAdd?.(it)}>
                                                                +
                              </View>
                            </View>
                          }
                        </View>
                      </View>
                    </View>
                  )
                })
              }
            </View>
          )
        })
      }
    </>

  )
}
const GoodsItemWithMemo = memo(GoodsItem)

const ApplyMoney = () => {
  const Router = useRouter()
  const { fetchData: infoFetch } = MpSaleOrder()
  const [ListArr, setListArr] = useState<any[]>([])
  const [infoObj, setInfoObj] = useState<any>({})

  // 获取订单详情
  const getDetail = async() => {
    Taro.showLoading({
      title: '请稍等...',
      mask: true,
    })
    const res = await infoFetch({ id: Router.params.orderId })
    if (res.data) {
      res.data.av_return_product.forEach((item) => {
        item.av_product_color.forEach((it) => {
          it.isTui = false
          it.nums = 1
        })
        return item
      })
      setInfoObj(res.data)
      setListArr(res.data.av_return_product)
      Taro.hideLoading()
    }
  }

  // 点击退货
  const handTui = (val) => {
    const res = ListArr
    res.forEach((item) => {
      item.av_product_color?.map((it) => {
        if (it.sale_order_detail_id == val.sale_order_detail_id) {
          it.isTui = true
        }
        return it
      })
    })
    setListArr([...res])
  }
  // 点击取消退货
  const handCancel = (val) => {
    ListArr.forEach((item) => {
      item.av_product_color.map((it) => {
        if (it.sale_order_detail_id === val.sale_order_detail_id) {
          it.isTui = false
        }
        return it
      })
    })
    setListArr([...ListArr])
  }

  // 点击减
  const handReduce = (val) => {
    ListArr.forEach((item) => {
      item.av_product_color.map((it) => {
        if (it.sale_order_detail_id === val.sale_order_detail_id) {
          if (val.nums === 1) {
            it.isTui = false
            it.nums = 1
          }
          else {
            it.nums--
          }
        }
        return it
      })
    })
    setListArr([...ListArr])
  }

  const onInputEven = (e, val) => {
    ListArr.forEach((item) => {
      item.av_product_color.map((it) => {
        if (it.sale_order_detail_id === val.sale_order_detail_id) {
          if (Number(e.detail.value) < 1 || e.detail.value == '') {
            it.isTui = false
            it.nums = 1
          }
          else {
            it.nums = Number(e.detail.value)
          }
          if (Number(e.detail.value) > it.roll) {
            it.nums = 1
          }
        }
        return it
      })
    })
    setListArr([...ListArr])
  }

  const onBlur = (e, val) => {
    ListArr.forEach((item) => {
      item.av_product_color.map((it) => {
        if (it.sale_order_detail_id === val.sale_order_detail_id) {
          if (Number(e.detail.value) < 1 || e.detail.value == '') {
            it.isTui = false
            it.nums = 1
          }
          else {
            it.nums = Number(e.detail.value)
          }
          if (Number(e.detail.value) > it.roll) {
            it.nums = 1
          }
        }
        return it
      })
    })
    setListArr([...ListArr])
  }

  // 点击加
  const handAdd = (val) => {
    ListArr.forEach((item) => {
      item.av_product_color.forEach((it) => {
        if (it.sale_order_detail_id === val.sale_order_detail_id) {
          if (it.nums < it.roll) {
            it.nums++
          }
        }
      })
    })
    setListArr([...ListArr])
  }

  // 获取枚举
  const [List, setList] = useState<any[]>([])
  const { fetchData: explanFetch } = MpEnumRefundExplainOne()
  const getEnum = async() => {
    const res = await explanFetch()
    if (res.data) {
      setList(res.data.list)
    }
  }
  const queryRef = useRef({
    reasonName: '请选择',
  })
  const [Query, setQuery] = useState<any>({
    reasonId: '',
    reasonName: '请选择',
  })
  // 选择退货原因
  const handReasonOne = (item) => {
    List.map((it) => {
      if (it.id === item.id) {
        it.default = true
      }
      else {
        it.default = false
      }
      return it
    })
    setList([...List])
    setQuery(val => ({ ...val, reasonId: item.id }))
    queryRef.current.reasonName = item.name
  }

  // 筛选内容展示
  const [showPopup, setshowPopup] = useState(false)

  // 备注信息
  const [TextareaValue, setTextareaValue] = useState('')
  const getDesc = (e) => {
    setTextareaValue(e)
  }

  // 取消返回
  const handCancl = () => {
    Taro.navigateBack({
      delta: 1,
    })
  }

  // 确认选择
  const handSlect = () => {
    setQuery(val => ({ ...val, reasonName: queryRef.current.reasonName }))
    setshowPopup(false)
  }

  const totalNums = useMemo(() => {
    const arr: any[] = []
    ListArr.forEach((item) => {
      item.av_product_color.forEach((it) => {
        if (it.isTui) {
          arr.push(it)
        }
      })
    })
    return arr.length
  }, [ListArr])
  // 数组重置
  const resetArr = (arr) => {
    arr.map((it) => {
      it.default = false
      return it
    })
    return arr
  }
  // 重置
  const handReset = () => {
    setQuery(({ reasonId: '', reasonName: '请选择' }))
    queryRef.current.reasonName = '请选择'
    const arrOne = resetArr(List)
    setList([...arrOne])
  }

  // 判断是否允许提交
  const isDisabled = useMemo(() => {
    if (Query.reasonId !== '') {
      return false
    }
    else {
      return true
    }
  }, [Query])

  // 判断是否允许提交
  const canTui = useMemo(() => {
    if (totalNums > 0 && Query.reasonId !== '') {
      return false
    }
    else {
      return true
    }
  }, [Query, totalNums])

  const noGoods = useMemo(() => {
    if (Query.reasonId !== '') {
      return false
    }
    else {
      return true
    }
  }, [Query])
  useEffect(() => {
    getDetail()
    getEnum()
  }, [])

  // 确认退款
  const { fetchData: sureFetch } = MpReturnApplyOrder()
  const handSure = () => {
    if (queryRef.current.reasonName == '其他问题' && TextareaValue == '') {
      Taro.showToast({
        title: '请填写其他说明',
        icon: 'error',
        duration: 3000,
      })
      return false
    }
    const arr: any = []
    if (infoObj.sale_mode == 0 && infoObj.status == 9) {
      ListArr.forEach((item) => {
        item.av_product_color.forEach((it) => {
          if (it.isTui) {
            arr.push({
              product_color_id: it.sale_mode == 0 ? it.product_color_id : '',
              product_id: it.sale_mode == 0 ? it.product_id : '',
              product_roll: it.sale_mode == 0 ? it.nums : 0,
              sale_order_detail_id: it.sale_order_detail_id,
            })
          }
        })
      })
    }
    if ((infoObj.sale_mode == 1 && infoObj.status == 9) || (infoObj.sale_mode == 2 && infoObj.status == 9)) {
      ListArr.forEach((item) => {
        item.av_product_color.forEach((it) => {
          if (it.isTui) {
            arr.push({
              product_color_id: it.product_color_id,
              product_id: it.product_id,
              product_roll: 0,
              sale_order_detail_id: it.sale_order_detail_id,
            })
          }
        })
      })
    }
    const query = {
      reason_describe: TextareaValue,
      fabric_piece_accessory_url: [],
      goods_status: 0,
      return_reason: 1,
      return_explain: Query.reasonId,
      roll: 0,
      roll_list: arr,
      sale_order_id: Number(Router.params.orderId),
    }
    console.log(query, 888)
    Taro.showModal({
      content: '确认退款吗？',
      confirmText: '确认',
      cancelText: '取消',
      async success(res) {
        if (res.confirm) {
          Taro.showLoading({
            title: '请稍等...',
            mask: true,
          })
          const res = await sureFetch(query)
          if (res?.msg === 'success') {
            Taro.showToast({
              title: '成功',
            })
            Taro.hideLoading()
            handCancl()
          }
          else {
            Taro.hideLoading()
            Taro.showToast({
              title: res?.msg,
              icon: 'error',
            })
          }
        }
      },
    })
  }

  const showItem = useMemo(() => {
    if ((infoObj.sale_mode == 0 && infoObj.status == 9) || (infoObj.sale_mode == 1 && infoObj.status == 9) || (infoObj.sale_mode == 2 && infoObj.status == 9)) {
      return true
    }
    else {
      return false
    }
  }, [infoObj])

  return (
    <View className={styles.main}>
      {
        showItem && <View className={styles.bgBox}>
          <GoodsItemWithMemo
            list={ListArr}
            obj={infoObj}
            handTui={item => handTui(item)}
            handCancel={item => handCancel(item)}
            onBlur={(e, item) => onBlur(e, item)}
            handReduce={item => handReduce(item)}
            handAdd={item => handAdd(item)}
            onInputEven={(e, item) => onInputEven(e, item)}
          ></GoodsItemWithMemo>
          <View className={styles.hasSelect}>汇总：已选{totalNums}种商品</View>
        </View>
      }
      <View className={styles.resonBig}>
        <View className={styles.reasonItem} onClick={() => { setshowPopup(true) }}>
          <View className={styles.reasonLeft}>
            <View className={styles.reasonFont}>退款原因</View>
            <Text className={styles.xing}>*</Text>
            {
              Query.reasonName === '请选择' && <View className={styles.selectFont}>请选择</View>
            }
            {
              Query.reasonName !== '请选择' && <View className={styles.selectFont}>{Query.reasonName}</View>
            }
          </View>
          <View className={classnames('iconfont', 'icon-chakanquanbukehu', styles.chakanquanbukehu)}></View>
        </View>
      </View>
      <View className={styles.descBox}>
        <View className={styles.title}>其他说明</View>
        <View className={styles.textBox}>
          <Textarea
            onInput={e => getDesc(e.detail.value)}
            value={TextareaValue}
            // style='background:#f6f6f6;height:210px;padding:15rpx 24rpx 24rpx 24rpx;border-radius: 8rpx;'
            placeholderStyle="font-size: 28rpx;font-weight: 400;"
            placeholder="选填/退款说明中选择（其他问题）必填"
          ></Textarea>
        </View>
      </View>
      <View className={styles.safeBox}>
        <View className={styles.bottomBox}>

          <Button className={styles.resetBox} onClick={() => { handCancl() }}> 取消</Button >
          {
            showItem && <Button className={classnames(canTui ? styles.button : styles.activeButton)} disabled={canTui} onClick={() => handSure()}> 确认退款</Button >

          }
          {
            !showItem && <Button className={classnames(noGoods ? styles.button : styles.activeButton)} disabled={noGoods} onClick={() => handSure()}> 确认退款</Button >

          }
        </View>
      </View>
      <Popup title="筛选情况" show={showPopup} onClose={() => { setshowPopup?.(false) }}>
        <ScrollView scrollY>
          <View className={styles.popupBox}>
            <View className={styles.thirdBox}>
              <View className={styles.thirdTopfont}>退款原因</View>
              <View className={styles.flexModebox}>
                {
                  List.map((item, index) => {
                    return (
                      <View onClick={() => { handReasonOne(item) }} className={classnames(item.default ? styles.activemodeBox : styles.modeBox)} key={index}>{item.name}</View>
                    )
                  })
                }
              </View>
            </View>
            <View className={styles.safeBoxs} ></View>
            <View className={styles.bottomBox1}>

              <Button className={styles.resetBox1} onClick={() => { handReset() }}> 重置</Button >
              <Button className={classnames(isDisabled ? styles.button1 : styles.activeButton1)} disabled={isDisabled} onClick={() => handSlect()}> 确认</Button >
            </View>
          </View>
        </ScrollView>
      </Popup>
    </View>
  )
}
export default ApplyMoney
