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 {
  MpEnumReturnExplain,
  MpEnumReturnGoodsStatus,
  MpEnumReturnOrderReturnReason,
  MpReturnApplyOrder,
  MpSaleOrder,
} from '@/api/order'
import Popup from '@/components/popup'
import UploadImage from '@/components/uploadImage'

// 产品商品元素
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 ApplyGoods = () => {
  const router = useRouter()

  const { fetchData: infoFetch } = MpSaleOrder()
  const [infoObj, setInfoObj] = useState<any>({})
  const [ListArr, setListArr] = 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
      })
      setListArr(res.data.av_return_product)
      setInfoObj(res.data)
      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) {
            it.nums = ''
          }
          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 totalNums = useMemo(() => {
    const arr: any[] = []
    ListArr.forEach((item) => {
      item.av_product_color.forEach((it) => {
        if (it.isTui) {
          arr.push(it)
        }
      })
    })
    return arr.length
  }, [ListArr])

  useEffect(() => {
    getDetail()
  }, [])

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

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

  const queryRef = useRef(
    {
      return_reason: 1, // 退货原因
      return_explain: '', // 退货理由
      reasonName: '请选择',
      reasonNameTwo: '请选择',
      GoodStatus: '',
      GoodStatusName: '请选择',
    },
  )
  const [Query, setQuery] = useState<any>({
    // reason_describe: '',//描述说明
    return_reason: 1, // 退货原因
    reasonName: '请选择',
    reasonNameTwo: '请选择',
    return_explain: '', // 退货理由
    GoodStatus: '',
    GoodStatusName: '请选择',
    // goods_status: '',//货物状况
    // fabric_piece_accessory_url:[],//退货图片
    // sale_order_id:infoObj.id,//详情id
  })

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

  /// 获取退货原因
  const { fetchData: resonFetch } = MpEnumReturnOrderReturnReason()
  const [ReasonList, setReasonList] = useState<any[]>([])
  const getReason = async() => {
    const res = await resonFetch()
    if (res.data) {
      setReasonList(res.data.list)
    }
  }

  // 获取退货原因2
  const { fetchData: resonTwoFetch } = MpEnumReturnExplain()
  const [ReasonListTwo, setReasonListTwo] = useState<any[]>([])
  const getReasonTwo = async() => {
    const res = await resonTwoFetch({ return_reason: queryRef.current.return_reason })
    if (res.data) {
      setReasonListTwo(res.data.list)
    }
  }

  // 选择退货原因
  const handReasonOne = (item) => {
    ReasonList.map((it) => {
      if (it.id === item.id) {
        it.default = true
      }
      else {
        it.default = false
      }
      return it
    })
    setQuery(val => ({ ...val, return_reason: item.id, return_explain: '' }))
    queryRef.current.return_reason = item.id
    queryRef.current.reasonName = item.name
    setReasonList([...ReasonList])
    getReasonTwo()
  }

  // 选择退货理由
  const handReasonTwo = (item) => {
    ReasonListTwo.map((it) => {
      if (it.id === item.id) {
        it.default = true
      }
      else {
        it.default = false
      }
      return it
    })
    setReasonListTwo([...ReasonListTwo])
    // queryRef.current.reasonNameTwo = item.name
    setQuery(val => ({ ...val, return_explain: item.id }))

    // queryRef.current.return_explain = item.id
  }
  useEffect(() => {
    getReason()
    getReasonTwo()
  }, [])
  // 数组重置
  const resetArr = (arr) => {
    arr.map((it) => {
      it.default = false
      return it
    })
    return arr
  }
  // 重置
  const handReset = () => {
    queryRef.current.return_reason = 1
    queryRef.current.return_explain = ''
    queryRef.current.reasonName = '请选择'
    queryRef.current.reasonNameTwo = '请选择'
    setQuery(val => ({ ...val, return_reason: 1, return_explain: '', reasonName: '请选择', reasonNameTwo: '请选择' }))
    getReasonTwo()
    const arrOne = resetArr(ReasonList)
    setReasonList([...arrOne])
    const arrTwo = resetArr(ReasonListTwo)
    setReasonListTwo([...arrTwo])
  }

  // 判断选择原因
  const selectIsDisabled = useMemo(() => {
    if (Query.return_explain !== '') {
      return false
    }
    else {
      return true
    }
  }, [Query])

  // 确认选择退货原因
  const handSlect = () => {
    if (queryRef.current?.reasonName == '请选择') {
      Taro.showToast({
        title: '请选择完整',
        icon: 'error',
      })
      return false
    }
    const resOne = ReasonList.filter((item) => {
      return item.default
    })
    queryRef.current.return_reason = resOne[0]?.id
    queryRef.current.reasonName = resOne[0]?.name
    const resTwo = ReasonListTwo.filter((item) => {
      return item.default
    })
    queryRef.current.return_explain = resTwo[0]?.id
    queryRef.current.reasonNameTwo = resTwo[0]?.name
    setQuery(val => ({
      ...val,
      reasonName: queryRef.current.reasonName,
      reasonNameTwo: queryRef.current.reasonNameTwo,
    }))
    setshowPopup(false)
  }

  // 货物情况
  const [DescPopup, setDescPopup] = useState(false)
  const { fetchData: statusFetch } = MpEnumReturnGoodsStatus()
  const [GoodStatusList, setGoodStatusList] = useState<any[]>([])

  const getGoodStatus = async() => {
    const res = await statusFetch()
    if (res.data) {
      setGoodStatusList(res.data.list)
    }
  }
  useEffect(() => {
    getGoodStatus()
  }, [])
  const handStatus = (item) => {
    GoodStatusList.map((it) => {
      if (it.id === item.id) {
        it.default = true
      }
      else {
        it.default = false
      }
      return it
    })
    setQuery(val => ({ ...val, GoodStatus: item.id }))
    setGoodStatusList([...GoodStatusList])
  }

  // 判断状态是否有选
  const StatusIsDisabled = useMemo(() => {
    if (Query.GoodStatus !== '') {
      return false
    }
    else {
      return true
    }
  }, [Query])

  // 重置货物状态
  const handResetStatus = () => {
    const arr = resetArr(GoodStatusList)
    setGoodStatusList([...arr])
    queryRef.current.GoodStatus = ''
    queryRef.current.GoodStatusName = '请选择'
    setQuery(val => ({ ...val, GoodStatus: '', GoodStatusName: '请选择' }))
  }

  // 确认选择货物状况
  const handSlectStatus = () => {
    const res = GoodStatusList.filter((item) => {
      return item.default
    })
    queryRef.current.GoodStatus = res[0].id
    queryRef.current.GoodStatusName = res[0].name
    setQuery(val => ({ ...val, GoodStatus: queryRef.current.GoodStatus, GoodStatusName: queryRef.current.GoodStatusName }))
    setDescPopup(false)
  }

  // 取消返回
  const handCancl = () => {
    Taro.navigateBack({
      delta: 1,
    })
  }
  // 备注信息
  const [TextareaValue, setTextareaValue] = useState('')
  // 确认退货
  const { fetchData: sureFetch } = MpReturnApplyOrder()
  const handSure = () => {
    if (Query.reasonNameTwo == '其他问题' && TextareaValue == '') {
      Taro.showToast({
        title: '请填写其他说明',
        icon: 'error',
        duration: 3000,
      })
      return false
    }
    const arr: any = []
    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,
          })
        }
      })
    })
    const query = {
      reason_describe: TextareaValue,
      fabric_piece_accessory_url: picUrl.current,
      goods_status: Query.GoodStatus,
      return_reason: Query.return_reason,
      return_explain: Query.return_explain,
      roll: 0,
      roll_list: arr,
      sale_order_id: Number(infoObj.id),
    }

    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',
            })
          }
        }
      },
    })
  }
  useEffect(() => {
    setQuery(Query)
  }, [Query])

  const getDesc = (e) => {
    setTextareaValue(e)
  }
  return (
    <View className={styles.main}>
      <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>
            {
              queryRef.current.reasonName === '请选择' && <View className={styles.selectFont}>请选择</View>
            }
            {
              queryRef.current.reasonName !== '请选择' && <View className={styles.selectFont}>{Query.reasonName}/{Query.reasonNameTwo}</View>
            }
          </View>
          <View className={classnames('iconfont', 'icon-chakanquanbukehu', styles.chakanquanbukehu)}></View>
        </View>
        <View className={styles.reasonItem} onClick={() => { setDescPopup?.(true) }}>
          <View className={styles.reasonLeft}>
            <View className={styles.reasonFont}>货物情况</View>
            <Text className={styles.xing}>*</Text>
            {
              queryRef.current.GoodStatusName === '请选择' && <View className={styles.selectFont}>请选择</View>
            }
            {
              queryRef.current.GoodStatusName !== '请选择' && <View className={styles.selectFont}>{Query.GoodStatusName}</View>
            }
          </View>
          <View className={classnames('iconfont', 'icon-chakanquanbukehu', styles.chakanquanbukehu)}></View>
        </View>
        <View className={styles.picBig}>
          <View className={styles.picFont}>拍照上传</View>
          <UploadImage onChange={getImageList} />
        </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 >
          <Button className={classnames(isDisabled ? styles.button : styles.activeButton)} disabled={isDisabled} 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}>
                {
                  ReasonList.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.thirdBox}>
              <View className={styles.thirdTopfont}>退货理由</View>
              <View className={styles.flexModebox}>
                {
                  ReasonListTwo.map((item, index) => {
                    return (
                      <View onClick={() => { handReasonTwo(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(selectIsDisabled ? styles.button1 : styles.activeButton1)} disabled={selectIsDisabled} onClick={() => handSlect()}> 确认</Button >
            </View>
          </View>
        </ScrollView>
      </Popup>
      <Popup title="筛选说明" show={DescPopup} onClose={() => { setDescPopup?.(false) }}>
        <ScrollView scrollY >
          <View className={styles.popupBox}>
            <View className={styles.thirdBox}>
              <View className={styles.thirdTopfont}>货物情况</View>
              <View className={styles.flexModebox}>
                {
                  GoodStatusList.map((item, index) => {
                    return (
                      <View onClick={() => { handStatus(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={() => { handResetStatus() }}> 重置</Button >
              <Button className={classnames(StatusIsDisabled ? styles.button1 : styles.activeButton1)} disabled={StatusIsDisabled} onClick={() => handSlectStatus()}> 确认</Button >
            </View>
          </View>
        </ScrollView>
      </Popup>
    </View>
  )
}
export default ApplyGoods
